CmsOrderDonServiceImpl.java 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  1. package com.cyksj.service.mange.impl;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.date.DateField;
  4. import cn.hutool.core.date.DateTime;
  5. import cn.hutool.core.date.DateUtil;
  6. import cn.hutool.core.lang.Assert;
  7. import cn.hutool.core.util.StrUtil;
  8. import com.alipay.api.AlipayClient;
  9. import com.alipay.api.domain.AlipayTradeRefundModel;
  10. import com.alipay.api.request.AlipayTradeRefundRequest;
  11. import com.alipay.api.response.AlipayTradeRefundResponse;
  12. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  13. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  14. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  15. import com.cyksj.common.constant.Constant;
  16. import com.cyksj.common.exception.BusinessRuntimeException;
  17. import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
  18. import com.cyksj.common.util.Codec;
  19. import com.cyksj.common.util.Jsons;
  20. import com.cyksj.common.util.StringUtil;
  21. import com.cyksj.common.util.Xmls;
  22. import com.cyksj.config.WeChatConfig;
  23. import com.cyksj.config.zfb.AliPayClientFactory;
  24. import com.cyksj.dto.RedisKey;
  25. import com.cyksj.mapper.*;
  26. import com.cyksj.mapper.channel.ShopConfigMapper;
  27. import com.cyksj.mapper.channel.UserPayEquipmentReceiveBenefitsRecordMapper;
  28. import com.cyksj.mapper.manage.cms.CmsUserMapper;
  29. import com.cyksj.mapper.manage.distribute.DistributeWaitingSendPointsMapper;
  30. import com.cyksj.mapper.manage.distribute.UserDistributeBusinessOrderDonRecordMapper;
  31. import com.cyksj.mapper.manage.distribute.UserDistributeMapper;
  32. import com.cyksj.mapper.manage.distribute.equipment.EquipmentUserDistributeTransportBenefitsMapper;
  33. import com.cyksj.mapper.manage.sys.WorkOrderMapper;
  34. import com.cyksj.mapper.shop.YhShopUserDistributeBusinessOrderDonRecordMapper;
  35. import com.cyksj.mapper.stock.GoodsSkuStockRelateMapper;
  36. import com.cyksj.model.entity.*;
  37. import com.cyksj.model.excel.ExcelOrderDonInfo;
  38. import com.cyksj.model.manage.request.ReqSetLogisticsPost;
  39. import com.cyksj.model.manage.views.GroupsRelationView;
  40. import com.cyksj.model.request.ChangeRelationReq;
  41. import com.cyksj.model.request.ClickOutReq;
  42. import com.cyksj.model.request.OrderRefundReq;
  43. import com.cyksj.redis.RedisService;
  44. import com.cyksj.service.coupon.CouponFontService;
  45. import com.cyksj.service.distribute.equipment.EquipmentDistributeService;
  46. import com.cyksj.service.giftcard.GiftCardOrderUseRecordService;
  47. import com.cyksj.service.mange.CmsOrderDonService;
  48. import com.cyksj.service.mange.stock.GoodsDonStockService;
  49. import com.cyksj.service.market.MarketFrontService;
  50. import com.cyksj.service.order.OrderCommonService;
  51. import com.cyksj.service.order.UserRealOrderBenefitsService;
  52. import com.cyksj.service.paypal.PayPalService;
  53. import com.cyksj.service.relation.GroupRelationClearService;
  54. import com.cyksj.service.relation.GroupsRelationExpiryRecordService;
  55. import com.cyksj.service.shop.YhShopDistributeService;
  56. import com.cyksj.service.stripe.StripeService;
  57. import com.cyksj.service.user.UserBenefitsService;
  58. import com.cyksj.service.wechat.WeChatService;
  59. import com.ejlchina.searcher.BeanSearcher;
  60. import com.ejlchina.searcher.util.MapUtils;
  61. import lombok.RequiredArgsConstructor;
  62. import lombok.extern.slf4j.Slf4j;
  63. import org.springframework.dao.DuplicateKeyException;
  64. import org.springframework.stereotype.Service;
  65. import org.springframework.transaction.annotation.Transactional;
  66. import java.math.BigDecimal;
  67. import java.math.RoundingMode;
  68. import java.util.Date;
  69. import java.util.List;
  70. import java.util.Map;
  71. import java.util.Optional;
  72. /**
  73. * @author chan
  74. * @date 2021/10/25 下午10:14
  75. */
  76. @Service
  77. @Slf4j
  78. @RequiredArgsConstructor
  79. public class CmsOrderDonServiceImpl extends ServiceImpl<OrderDonMapper,OrderDon> implements CmsOrderDonService {
  80. private final OrderDonTransportMapper transportMapper;
  81. private final OrderDonWaybillMapper orderDonWaybillMapper;
  82. private final GoodsSkuStockRelateMapper skuStockRelateMapper;
  83. private final GoodsDonStockService goodsDonStockService;
  84. private final GoodsDonSkuMapper goodsDonSkuMapper;
  85. private final UserRealOrderBenefitsService userRealOrderBenefitsService;
  86. private final UserRelationKickOutRecordMapper kickOutRecordMapper;
  87. private final CmsUserMapper cmsUserMapper;
  88. private final OrderCommonService orderCommonService;
  89. private final GoodsDonMapper goodsDonMapper;
  90. private final RedisService redisService;
  91. private final UserBenefitsService userBenefitsService;
  92. private final DistributeWaitingSendPointsMapper distributeWaitingSendPointsMapper;
  93. private final RefundOrderDonMapper refundOrderDonMapper;
  94. private final UserDistributeMapper userDistributeMapper;
  95. private final OrderDonMapper orderDonMapper;
  96. private final MarketFrontService marketFrontService;
  97. private final EquipmentDistributeService equipmentDistributeService;
  98. private final CouponFontService couponFontService;
  99. private final WeChatService weChatService;
  100. private final WeChatConfig weChatConfig;
  101. private final ShopConfigMapper shopConfigMapper;
  102. private final GroupRelationClearService relationClearService;
  103. private final GroupsRelationMapper relationMapper;
  104. private final GroupsMapper groupsMapper;
  105. private final GoodsDonSkuMapper skuMapper;
  106. private final UserDistributeBusinessOrderDonRecordMapper businessOrderDonRecordMapper;
  107. private final WorkOrderMapper workOrderMapper;
  108. private final PayPalService payPalService;
  109. private final StripeService stripeService;
  110. private final OrderDiscountPlusPurchaseSkuRelationMapper orderDiscountPlusPurchaseSkuRelationMapper;
  111. private final EquipmentUserDistributeTransportBenefitsMapper transportBenefitsMapper;
  112. private final BeanSearcher beanSearcher;
  113. private final UserPayEquipmentReceiveBenefitsRecordMapper receiveBenefitsRecordMapper;
  114. private final GroupsRelationExpiryRecordService groupsRelationExpiryRecordService;
  115. private final GiftCardOrderUseRecordService giftCardOrderUseRecordService;
  116. private final GiftCardUserRecordMapper giftCardUserRecordMapper;
  117. private final YhShopDistributeService yhShopDistributeService;
  118. private final YhShopUserDistributeBusinessOrderDonRecordMapper yhShopBusinessOrderDonRecordMapper;
  119. private static final GlobalThreadPoolTaskExecutor TASK_POOL = GlobalThreadPoolTaskExecutor.getInstance();
  120. @Override
  121. public List<ExcelOrderDonInfo> exportOrderInfo(Long promotionId, String start, String end) {
  122. return this.getBaseMapper().exportOrderInfo(promotionId,start,end);
  123. }
  124. @Override
  125. public OrderDonTransport getTransport(Long orderId) {
  126. return transportMapper.selectOne(Wrappers.lambdaQuery(OrderDonTransport.class).eq(OrderDonTransport::getOrderId, orderId));
  127. }
  128. @Transactional(rollbackFor = Throwable.class)
  129. @Override
  130. public OrderDonWaybill setWaybill(ReqSetLogisticsPost reqSetLogisticsPost) {
  131. OrderDonWaybill orderDonWaybill = Optional.ofNullable(orderDonWaybillMapper.selectOne(Wrappers.lambdaQuery(OrderDonWaybill.class).eq(OrderDonWaybill::getOrderId, reqSetLogisticsPost.getOrderId()))).orElse(new OrderDonWaybill());
  132. orderDonWaybill.setCodeCn(reqSetLogisticsPost.getCodeCn());
  133. orderDonWaybill.setTrackingNumber(reqSetLogisticsPost.getTrackingNumber());
  134. orderDonWaybill.setOrderId(reqSetLogisticsPost.getOrderId());
  135. orderDonWaybill.setRemark(reqSetLogisticsPost.getRemark());
  136. OrderDon orderDon = getById(orderDonWaybill.getOrderId());
  137. if(orderDonWaybill.getId() == null){
  138. try {
  139. orderDonWaybillMapper.insert(orderDonWaybill);
  140. } catch (DuplicateKeyException e) {
  141. return orderDonWaybill;
  142. }
  143. orderDon.setStatus(OrderDon.Status.transport);
  144. updateById(orderDon);
  145. GoodsDonSku sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  146. //库存扣减逻辑
  147. List<GoodsSkuStockRelate> relateList = skuStockRelateMapper.selectList(Wrappers.lambdaQuery(GoodsSkuStockRelate.class).eq(GoodsSkuStockRelate::getSkuId,orderDon.getSkuId()));
  148. if(!relateList.isEmpty()){
  149. relateList.forEach((relate)->{
  150. goodsDonStockService.upStockRelate(relate.getStockId(),orderDon.getId(),"transport");
  151. });
  152. }
  153. //发放实物购买权益
  154. Boolean isReceivedAll = true;
  155. if (sku != null) {
  156. if (sku.getIsBenefits()) {
  157. if (StrUtil.isNotEmpty(sku.getBenefitsList())) {
  158. try {
  159. List<GoodsDonSku> goodsDonSkus = Jsons.parseList(sku.getBenefitsList(), GoodsDonSku.class);
  160. //自购实物 获取权益
  161. isReceivedAll = userRealOrderBenefitsService.getPayRealGoodsBenefits(orderDon.getUserId(), orderDon.getId(), orderDon.getYhsId(), goodsDonSkus);
  162. } catch (Exception e) {
  163. }
  164. }
  165. }
  166. }
  167. final Boolean flag = isReceivedAll;
  168. //发送微信模板消息
  169. // TASK_POOL.execute(()->{
  170. // try {
  171. // log.info("发送发货通知至{}用户", orderDon.getUserId());
  172. // templateCommonService.sendTransportMsgNotify(orderDon, reqSetLogisticsPost, flag);
  173. // } catch (Exception e) {
  174. // log.error("发送发货通知至{}用户失败:{}", orderDon.getUserId(), e);
  175. // }
  176. // });
  177. }else {
  178. if (orderDon.getStatus() == OrderDon.Status.hasPayment) {
  179. orderDon.setStatus(OrderDon.Status.transport);
  180. updateById(orderDon);
  181. }
  182. orderDonWaybillMapper.updateById(orderDonWaybill);
  183. }
  184. //实物分销订单是否存在
  185. DistributeWaitingSendPoints waitingSendPoints = distributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(DistributeWaitingSendPoints.class)
  186. .eq(DistributeWaitingSendPoints::getOrderId, orderDon.getId())
  187. .eq(DistributeWaitingSendPoints::getIsDelivery, false)
  188. .last("limit 1"));
  189. if (waitingSendPoints != null) {
  190. //实物分销订单发货后再 进行提成结算期
  191. waitingSendPoints.setIsDelivery(true);
  192. distributeWaitingSendPointsMapper.updateById(waitingSendPoints);
  193. }
  194. //分销有礼 分销实物是否有发货后用户权益
  195. EquipmentUserDistributeTransportBenefits transportBenefits = transportBenefitsMapper.selectOne(Wrappers.lambdaQuery(EquipmentUserDistributeTransportBenefits.class)
  196. .eq(EquipmentUserDistributeTransportBenefits::getOrderId, orderDon.getId())
  197. .eq(EquipmentUserDistributeTransportBenefits::getStatus, EquipmentUserDistributeTransportBenefits.Status.hasPayment).last("limit 1"));
  198. if (transportBenefits != null) {
  199. if (transportBenefits.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  200. //7天后余额到账
  201. transportBenefitsMapper.update(null, Wrappers.lambdaUpdate(EquipmentUserDistributeTransportBenefits.class)
  202. .set(EquipmentUserDistributeTransportBenefits::getStatus, EquipmentUserDistributeTransportBenefits.Status.transport)
  203. .set(EquipmentUserDistributeTransportBenefits::getSendTime, DateUtil.offsetDay(DateTime.now(), 7))
  204. .eq(EquipmentUserDistributeTransportBenefits::getOrderId, orderDon.getId())
  205. .eq(EquipmentUserDistributeTransportBenefits::getStatus, EquipmentUserDistributeTransportBenefits.Status.hasPayment));
  206. }
  207. }
  208. return orderDonWaybill;
  209. }
  210. @Override
  211. public void kickOutRelationId(long adminId, ClickOutReq req) {
  212. Long orderId = req.getOrderId();
  213. OrderDon orderDon = getById(orderId);
  214. if (orderDon != null && !orderDon.getIsKickOut()) {
  215. try {
  216. UserRelationKickOutRecord kickOutRecord = new UserRelationKickOutRecord();
  217. kickOutRecord.setUserId(orderDon.getUserId());
  218. kickOutRecord.setRelationId(orderDon.getRelationId());
  219. kickOutRecord.setGoodsId(orderDon.getGoodsId());
  220. kickOutRecord.setSkuId(orderDon.getSkuId());
  221. kickOutRecord.setReason(req.getReason());
  222. kickOutRecord.setImg(req.getImg());
  223. kickOutRecord.setRemark(req.getRemark());
  224. kickOutRecord.setOrderId(orderDon.getId());
  225. kickOutRecord.setOrderNo(orderDon.getOrderNo());
  226. Optional.ofNullable(cmsUserMapper.selectById(adminId)).ifPresent(cmsUser -> kickOutRecord.setOperator(cmsUser.getNickname()));
  227. kickOutRecordMapper.insert(kickOutRecord);
  228. orderDon.setIsKickOut(true);
  229. updateById(orderDon);
  230. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  231. GoodsDonSku goodsDonSku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  232. //清除车票
  233. orderCommonService.clearUnrealGoodsDetail(orderDon, goodsDon.getType(), goodsDonSku);
  234. } catch (DuplicateKeyException e) {
  235. }
  236. }
  237. }
  238. @Override
  239. @Transactional(rollbackFor = Throwable.class)
  240. public void unifiedRefund(OrderRefundReq refundReq) throws Exception {
  241. OrderDon orderDon = orderDonMapper.selectById(refundReq.getOrderId());
  242. GoodsDonSku sku = null;
  243. if (orderDon.getSkuId() != null) {
  244. sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  245. }
  246. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  247. if (StrUtil.isEmpty(refundReq.getRefundType())) {
  248. refundReq.setRefundType("money");
  249. }
  250. String refundType = refundReq.getRefundType();
  251. //校验订单是否符合退款
  252. checkOrderRefund(orderDon, goodsDon, sku, refundReq);
  253. //空订单关闭
  254. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0 && orderDon.getBalance().compareTo(BigDecimal.ZERO) == 0
  255. && orderDon.getRelationId() == 0) {
  256. orderDon.setStatus(OrderDon.Status.refund);
  257. orderDonMapper.updateById(orderDon);
  258. if (goodsDon.getType() == 2) {
  259. //扣除用户自身实物权益
  260. userRealOrderBenefitsService.deductUserRealGoodsBenefits(orderDon.getId());
  261. }
  262. return;
  263. }
  264. OrderDon.Type type = orderDon.getType();
  265. String outNo = StrUtil.EMPTY;
  266. if (type == OrderDon.Type.WeChat && !refundType.equals(OrderDon.Type.BALANCE.getType())) {
  267. outNo = wxRefund(refundReq, orderDon);
  268. }
  269. if (type == OrderDon.Type.ALI_PAY && !refundType.equals(OrderDon.Type.BALANCE.getType())) {
  270. outNo = zfbRefund(refundReq, orderDon);
  271. }
  272. if (type == OrderDon.Type.PAYPAL && !refundType.equals(OrderDon.Type.BALANCE.getType())) {
  273. payPalService.refund(refundReq, orderDon);
  274. }
  275. if (type == OrderDon.Type.STRIPE && !refundType.equals(OrderDon.Type.BALANCE.getType())) {
  276. stripeService.refund(refundReq, orderDon);
  277. }
  278. orderDon.setRefundDesc(refundReq.getRefundDesc());
  279. //记录退款信息
  280. commonRefund(orderDon, goodsDon, sku, outNo, refundType);
  281. //修改订单状态
  282. orderDon.setStatus(OrderDon.Status.refund);
  283. orderDonMapper.updateById(orderDon);
  284. //提交过工单的订单
  285. //将用户异常订单关闭
  286. workOrderMapper.update(null, Wrappers.lambdaUpdate(WorkOrder.class)
  287. .set(WorkOrder::getStatus, WorkOrder.Status.close)
  288. .eq(WorkOrder::getStatus, WorkOrder.Status.waiting)
  289. .eq(WorkOrder::getUserId, orderDon.getUserId())
  290. .eq(WorkOrder::getRelationId, orderDon.getRelationId()));
  291. }
  292. public String wxRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
  293. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) <=0){
  294. return StrUtil.EMPTY;
  295. }
  296. long time = System.currentTimeMillis();
  297. //退款订单号
  298. String outRefundNo = Codec.DoDigest.custom()
  299. .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
  300. .setStringData(time + String.valueOf(orderDon.getId()))
  301. .toHexString();
  302. weChatService.refundWxOrder(weChatConfig.getAppid(),
  303. Optional.ofNullable(orderDon.getShopId()).orElse(ShopConfig.WX_DEFAULT_APP_ID),
  304. orderDon.getTransactionId(),
  305. outRefundNo,
  306. orderDon.getMoney(),
  307. refundReq.getRefundMoney(),
  308. weChatConfig.getDomain() + "manage/order/wx/refund/notify");
  309. //记录退款信息
  310. return outRefundNo;
  311. }
  312. @Override
  313. public void wxRefundNotify(Map<String, String> map) throws Exception {
  314. // 对退款数据 解密
  315. String md5Key = Codec.DoDigest.custom().setAlgorithm(Codec.DoDigest.Algorithm.MD5).setStringData(shopConfigMapper.getByAppId(map.get("mch_id")).getSecret()).toHexString();
  316. String reqInfoXml = Codec.DoCipher.custom().setAlgorithm(Codec.DoCipher.Trans.AES_ECB_PKCS7Padding).setBase64Data(map.get("req_info")).setStringKey(md5Key).ofDecrypt().toText();
  317. log.info("=== 退款数据解密: \n {}", reqInfoXml);
  318. Map<String, String> reqInfoMap = Xmls.toMap(reqInfoXml);
  319. // 退款失败
  320. if (StrUtil.equals("CHANGE", reqInfoMap.get("refund_status"))) {
  321. throw BusinessRuntimeException.getInstance("退款异常.");
  322. } else if (StrUtil.equals("REFUNDCLOSE", reqInfoMap.get("refund_status"))) {
  323. throw BusinessRuntimeException.getInstance("退款关闭.");
  324. }
  325. /* 此处处理业务逻辑 */
  326. String outRefundNo = reqInfoMap.get("out_refund_no");
  327. String transactionId = reqInfoMap.get("transaction_id");
  328. String refundFee = reqInfoMap.get("refund_fee");
  329. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getTransactionId, transactionId).last("limit 1"));
  330. if (orderDon == null) {
  331. log.error("退款回调,transactionId:{}订单不存在", transactionId);
  332. return;
  333. }
  334. log.info("微信退款: 退款单号[{}] 退款成功.", outRefundNo);
  335. }
  336. @Override
  337. @Transactional(rollbackFor = Throwable.class)
  338. public void changeRelation(ChangeRelationReq req) throws Exception {
  339. Long relationId = req.getRelationId();
  340. Long groupId = req.getGroupsId();
  341. UserTicketClearedRecord.Source source = req.getSource();
  342. if (source == null) source = UserTicketClearedRecord.Source.change_ticket;
  343. GroupsRelation relation = relationMapper.selectById(relationId);
  344. Long yhsId = relation.getYhsId();
  345. Assert.notNull(relation, "车票已不存在");
  346. if (relation.getRechargeStatus() != null) {
  347. throw BusinessRuntimeException.getInstance("代充账号车票无法更换车票");
  348. }
  349. Long userId = relation.getUserId();
  350. log.info("用户userId:{}更换车票relationId:{}", userId, relationId);
  351. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  352. .eq(OrderDon::getUserId, userId)
  353. .eq(OrderDon::getRelationId, relationId)
  354. .notIn(OrderDon::getStatus, Constant.noOrderStatus)
  355. .orderByDesc(OrderDon::getId)
  356. .last("limit 1"));
  357. OrderDiscountPlusPurchaseSkuRelation plusPurchaseSkuRelation = null;
  358. List<Long> plus_relationList = null;
  359. if (orderDon == null) {
  360. List<OrderDiscountPlusPurchaseSkuRelation> plusPurchaseSkuRelations = orderDiscountPlusPurchaseSkuRelationMapper.selectPlusRelationByIdAndUserId(relation.getId(), relation.getUserId());
  361. for (OrderDiscountPlusPurchaseSkuRelation data : plusPurchaseSkuRelations) {
  362. String relationIds = data.getRelationIds();
  363. if (StrUtil.isEmpty(relationIds)) {
  364. return;
  365. }
  366. List<Long> relationList = Jsons.parseList(relationIds, Long.class);
  367. if (relationList.contains(relationId)) {
  368. plusPurchaseSkuRelation = data;
  369. break;
  370. }
  371. }
  372. if (plusPurchaseSkuRelation != null) {
  373. String relationIds = plusPurchaseSkuRelation.getRelationIds();
  374. if (StrUtil.isNotEmpty(relationIds)) {
  375. plus_relationList = Jsons.parseList(relationIds, Long.class);
  376. if (plus_relationList.contains(relationId)) {
  377. orderDon = new OrderDon();
  378. GroupsRelationView groupsRelationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder().field(GroupsRelationView::getId, relationId).build());
  379. Assert.notNull(groupsRelationView, "车票已不存在");
  380. orderDon.setUserId(groupsRelationView.getUserId());
  381. orderDon.setSkuId(groupsRelationView.getSkuId());
  382. orderDon.setGoodsId(groupsRelationView.getGoodsId());
  383. orderDon.setStatus(OrderDon.Status.complete);
  384. }
  385. }
  386. }
  387. }
  388. Assert.notNull(orderDon, "订单不存在");
  389. if (orderDon.getStatus() == OrderDon.Status.refund) {
  390. throw BusinessRuntimeException.getInstance("订单已退款");
  391. }
  392. //获取新车队
  393. LambdaQueryWrapper<GroupsTrips> queryWrapper = Wrappers.lambdaQuery(GroupsTrips.class)
  394. .eq(GroupsTrips::getSkuId, orderDon.getSkuId())
  395. .eq(GroupsTrips::getId, groupId)
  396. .ne(GroupsTrips::getId, relation.getGroupsId())
  397. .ne(GroupsTrips::getStatus, GroupsTrips.Status.down)
  398. .last("limit 1");
  399. GroupsTrips groups = groupsMapper.selectOne(queryWrapper);
  400. if (groups == null) throw BusinessRuntimeException.getInstance("车队不存在或已下架");
  401. if (!Constant.AI_goodsIds.contains(orderDon.getGoodsId()) && groups.getAvailableNum() <= 0) {
  402. throw BusinessRuntimeException.getInstance("该新车位人员已满");
  403. }
  404. Integer relationNum = groups.getNum();
  405. //获取新车队车位
  406. GroupsRelation newRelation;
  407. Boolean isOutside = req.getIsOutside();
  408. if (Constant.AI_goodsIds.contains(orderDon.getGoodsId()) && ((isOutside != null && isOutside) || groups.getAvailableNum() == 0)) {
  409. //Ai车队 额外增加车位 并不让上车
  410. newRelation = getChatGPTOutsideRelation(orderDon.getUserId(), groupId, relationNum, 1);
  411. } else {
  412. newRelation = getRelationThisTrips(orderDon.getUserId(), groupId, 1);
  413. }
  414. newRelation.setUserId(userId);
  415. newRelation.setStartTime(relation.getStartTime());
  416. newRelation.setExpiryTime(relation.getExpiryTime());
  417. newRelation.setYhsId(yhsId);
  418. newRelation.setCustomerService(relation.getCustomerService());
  419. if (newRelation.getStatus() != GroupsRelation.Status.outside) {
  420. newRelation.setStatus(GroupsRelation.Status.validity);
  421. }
  422. //清除原先车票
  423. relation.setNewRelationId(newRelation.getId());
  424. relationClearService.clearTicket(relation, source);
  425. if (plusPurchaseSkuRelation != null && plus_relationList != null) {
  426. plus_relationList.remove(relationId);
  427. plus_relationList.add(newRelation.getId());
  428. plusPurchaseSkuRelation.setRelationIds(plus_relationList.toString());
  429. orderDiscountPlusPurchaseSkuRelationMapper.updateById(plusPurchaseSkuRelation);
  430. }
  431. if (source != null && source == UserTicketClearedRecord.Source.abnormal) {
  432. //将用户异常订单关闭
  433. workOrderMapper.update(null, Wrappers.lambdaUpdate(WorkOrder.class)
  434. .set(WorkOrder::getStatus, WorkOrder.Status.close)
  435. .eq(WorkOrder::getStatus, WorkOrder.Status.waiting)
  436. .eq(WorkOrder::getUserId, userId)
  437. .eq(WorkOrder::getRelationId, relationId));
  438. }
  439. if (orderDon.getMoney() != null && orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  440. //是否是实物权益车票
  441. UserPayEquipmentReceiveBenefitsRecord receiveBenefitsRecord = receiveBenefitsRecordMapper.selectOne(Wrappers.lambdaQuery(UserPayEquipmentReceiveBenefitsRecord.class)
  442. .eq(UserPayEquipmentReceiveBenefitsRecord::getTicketOrderId, orderDon.getId())
  443. .eq(UserPayEquipmentReceiveBenefitsRecord::getRelationId, relationId).last("limit 1"));
  444. if (receiveBenefitsRecord != null) {
  445. receiveBenefitsRecord.setRelationId(newRelation.getId());
  446. receiveBenefitsRecordMapper.updateById(receiveBenefitsRecord);
  447. }
  448. }
  449. if ((newRelation.getStartTime() == null || newRelation.getExpiryTime() == null)) {
  450. List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.hasPayment));
  451. if (orderDonList.isEmpty()) {
  452. orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class)
  453. .eq(OrderDon::getUserId, userId)
  454. .eq(OrderDon::getRelationId, relationId)
  455. .eq(OrderDon::getStatus, OrderDon.Status.complete)
  456. .orderByDesc(OrderDon::getId)
  457. .last("limit 1"));
  458. }
  459. if (groups.getStatus() == GroupsTrips.Status.waiting) {
  460. orderDonList.forEach(hasPaymentOrder -> {
  461. hasPaymentOrder.setRelationId(newRelation.getId());
  462. orderDonMapper.updateById(hasPaymentOrder);
  463. });
  464. relationMapper.updateById(newRelation);
  465. return;
  466. }
  467. orderDonList.forEach((hasPaymentOrder) -> {
  468. //如果续费增加时间,如果首次则设置当前时间为初始时间
  469. Date expiryTime = Optional.ofNullable(newRelation.getExpiryTime()).orElse(new Date());
  470. GoodsDonSku donSku = skuMapper.selectById(hasPaymentOrder.getSkuId());
  471. Date newDate;
  472. if (donSku.getDays() != null && donSku.getDays() > 0) {
  473. newDate = DateUtil.offsetDay(expiryTime, donSku.getDays() * hasPaymentOrder.getNum());
  474. } else {
  475. newDate = DateUtil.offset(expiryTime, DateField.MONTH, donSku.getMonths() * hasPaymentOrder.getNum());
  476. }
  477. newRelation.setExpiryTime(newDate);
  478. newRelation.setStartTime(newRelation.getStartTime() == null ? new Date() : null);
  479. relationMapper.updateById(newRelation);
  480. hasPaymentOrder.setStatus(OrderDon.Status.complete);
  481. hasPaymentOrder.setRelationId(newRelation.getId());
  482. orderDonMapper.updateById(hasPaymentOrder);
  483. });
  484. return;
  485. }
  486. List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.complete));
  487. orderDonList.forEach(completeOrder->{
  488. completeOrder.setRelationId(newRelation.getId());
  489. orderDonMapper.updateById(completeOrder);
  490. });
  491. log.info("userId:{}更换车票,原座位号relationId:{}======>新座位号newRelationId:{}", newRelation.getUserId(), relationId, newRelation.getId());
  492. relationMapper.updateById(newRelation);
  493. }
  494. public String zfbRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
  495. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) <=0){
  496. return StrUtil.EMPTY;
  497. }
  498. AlipayTradeRefundResponse response;
  499. //支付宝退款
  500. AlipayClient alipayClient = AliPayClientFactory.getAlipayClient(Optional.ofNullable(orderDon.getShopId()).orElse(ShopConfig.ZFB_DEFAULT_APP_ID));
  501. AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
  502. AlipayTradeRefundModel model = new AlipayTradeRefundModel();
  503. //支付宝交易号
  504. model.setTradeNo(orderDon.getTransactionId());
  505. model.setRefundAmount(refundReq.getRefundMoney().divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_EVEN).toString());
  506. model.setQueryOptions(List.of("gmt_refund_pay"));
  507. long time = System.currentTimeMillis();
  508. //退款订单号
  509. String outRefundNo = Codec.DoDigest.custom()
  510. .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
  511. .setStringData(time + String.valueOf(orderDon.getId()))
  512. .toHexString();
  513. //退款请求号
  514. model.setOutRequestNo(outRefundNo);
  515. request.setBizModel(model);
  516. String shopId = orderDon.getShopId();
  517. ShopConfig shopConfig = shopConfigMapper.selectOne(Wrappers.lambdaQuery(ShopConfig.class).eq(ShopConfig::getAppId, orderDon.getShopId()));
  518. if (shopId != null && shopConfig != null && shopConfig.getIsCert()) {
  519. response = alipayClient.certificateExecute(request);
  520. } else {
  521. response = alipayClient.execute(request);
  522. }
  523. if (!response.isSuccess()) throw BusinessRuntimeException.getInstance("退款失败,e:{0}", response.getSubMsg());
  524. // AliPayRefundRep aliPayRefundRep = Jsons.parseObject(response.getBody(), AliPayRefundRep.class);
  525. // AliPayRefundRep.AlipayTradeRefundResponse res = aliPayRefundRep.getResponse();
  526. // orderDon.setRefundMoney(res.getRefundFee().multiply(BigDecimal.valueOf(100)));
  527. return outRefundNo;
  528. }
  529. /**
  530. * 校验订单是否符合退款操作
  531. */
  532. private void checkOrderRefund(OrderDon orderDon, GoodsDon goodsDon, GoodsDonSku sku, OrderRefundReq refundReq) {
  533. if (orderDon == null) {
  534. throw BusinessRuntimeException.getInstance("订单不存在");
  535. }
  536. String refundType = refundReq.getRefundType();
  537. if (orderDon.getType() == OrderDon.Type.BALANCE && !OrderDon.Type.BALANCE.getType().equals(refundType)) {
  538. throw BusinessRuntimeException.getInstance("余额支付的订单不支持金额退款");
  539. }
  540. if (OrderDon.Status.refund == orderDon.getStatus()) {
  541. throw BusinessRuntimeException.getInstance("该订单已退款");
  542. }
  543. if (OrderDon.Status.noPayment == orderDon.getStatus() || OrderDon.Status.close == orderDon.getStatus()) {
  544. throw BusinessRuntimeException.getInstance("订单{0}状态不支持退款", orderDon.getStatus());
  545. }
  546. if (goodsDon.getType() == 1 && sku != null) {
  547. //虚拟原订单是否已过期
  548. Integer months = sku.getMonths();
  549. Integer days = sku.getDays();
  550. Integer num = orderDon.getNum();
  551. DateTime now = DateTime.now();
  552. DateTime endTime;
  553. if (days != null && days > 0) {
  554. endTime = DateUtil.offsetDay(orderDon.getCreatedTime(), days * num);
  555. } else {
  556. endTime = DateUtil.offsetMonth(orderDon.getCreatedTime(), months * num);
  557. }
  558. if (now.isAfter(endTime)) {
  559. throw BusinessRuntimeException.getInstance("该订单车票已过期");
  560. }
  561. if (orderDon.getOrderType() == 1) {
  562. //是否有其他付款订单是否过期
  563. OrderDon otherOrder = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  564. .eq(OrderDon::getRelationId, orderDon.getRelationId())
  565. .eq(OrderDon::getUserId, orderDon.getUserId())
  566. .ne(OrderDon::getId, orderDon.getId())
  567. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  568. .eq(OrderDon::getOrderType, 2)
  569. .orderByDesc(OrderDon::getId)
  570. .last("limit 1"));
  571. if (otherOrder != null) {
  572. throw BusinessRuntimeException.getInstance("该笔订单存在续费订单,请先退掉续费订单");
  573. }
  574. }
  575. }
  576. BigDecimal refundMoney = refundReq.getRefundMoney();
  577. BigDecimal money = orderDon.getMoney();
  578. //余额退款
  579. if (OrderDon.Type.BALANCE.getType().equals(refundType)) {
  580. BigDecimal balance = orderDon.getBalance();
  581. if (OrderDon.Type.BALANCE == orderDon.getType() && refundMoney.compareTo(balance) > 0) {
  582. throw BusinessRuntimeException.getInstance("退款余额大于订单支付余额");
  583. }
  584. if (OrderDon.Type.BALANCE != orderDon.getType() && refundMoney.compareTo(money) > 0) {
  585. throw BusinessRuntimeException.getInstance("退款余额大于订单支付金额");
  586. }
  587. orderDon.setRefundBalance(refundMoney);
  588. orderDon.setRefundMoney(BigDecimal.ZERO);
  589. } else {
  590. //退金额
  591. if (refundMoney.compareTo(money) > 0) {
  592. throw BusinessRuntimeException.getInstance("退款金额大于订单支付金额");
  593. }
  594. orderDon.setRefundMoney(refundMoney);
  595. }
  596. //礼品卡是否已使用
  597. GiftCardUserRecord giftCardUserRecord = null;
  598. if (goodsDon.getSpecialType() != null && goodsDon.getSpecialType() == GoodsDon.SpecialType.giftCard) {
  599. giftCardUserRecord = giftCardUserRecordMapper.selectOne(Wrappers.lambdaQuery(GiftCardUserRecord.class)
  600. .eq(GiftCardUserRecord::getOrderId, orderDon.getId()).last("limit 1"));
  601. if (giftCardUserRecord != null && giftCardUserRecord.getIsUsed()) {
  602. throw BusinessRuntimeException.getInstance("该礼品卡已使用无法退款");
  603. }
  604. }
  605. if (!redisService.setNx(String.format("%s", refundReq.getOrderId()), refundReq.getOrderId(), 10l)) {
  606. throw BusinessRuntimeException.getInstance("请勿重复点击,正在退款中..");
  607. }
  608. //礼品卡购买状态
  609. if (giftCardUserRecord != null) {
  610. giftCardUserRecord.setIsPay(false);
  611. giftCardUserRecordMapper.updateById(giftCardUserRecord);
  612. }
  613. }
  614. /**
  615. * 退款后 处理关联
  616. */
  617. public void commonRefund(OrderDon orderDon, GoodsDon goodsDon, GoodsDonSku sku, String outNo, String refundType) {
  618. TASK_POOL.execute(() -> {
  619. refundRecord(orderDon, goodsDon, sku, outNo, refundType);
  620. //退款一次
  621. goodsDonStockService.upStockRelate(null, orderDon.getId(), "refund");
  622. try {
  623. //虚物订单退款,清出车队,车票变为已过期
  624. orderCommonService.clearUnrealGoodsDetail(orderDon, goodsDon.getType(), sku);
  625. } catch (Exception e) {
  626. log.error("清除车票错误:{}", StringUtil.getErrorText(e));
  627. }
  628. //若存在优惠券使用,退还优惠券
  629. if (orderDon.getCouponUserId() != 0) {
  630. couponFontService.updateOrderDonCouponStatus(orderDon);
  631. }
  632. //若存在余额支付,退还余额
  633. if (orderDon.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  634. userBenefitsService.addUserBalance(orderDon.getUserId(), orderDon.getBalance(), UserBalanceSourceRecord.Source.balance, orderDon.getYhsId());
  635. }
  636. try {
  637. marketFrontService.subSpecificChanceNum(orderDon.getUserId(), orderDon.getId(), orderDon.getGoodsId(), orderDon.getUpdateTime());
  638. if (goodsDon.getType() == 2) {
  639. equipmentDistributeService.subDistributeBenefitsChance(orderDon.getUserId(), orderDon.getId());
  640. //扣除用户自身实物权益
  641. userRealOrderBenefitsService.deductUserRealGoodsBenefits(orderDon.getId());
  642. }
  643. } catch (Exception e) {
  644. log.error("wx减少抽奖机会错误,orderId:{},error:{}", orderDon.getId(), e);
  645. }
  646. if (OrderDon.Type.BALANCE.getType().equals(refundType)) {
  647. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) > 0) {
  648. userBenefitsService.addUserBalance(orderDon.getUserId(), orderDon.getRefundBalance(), UserBalanceSourceRecord.Source.refund, orderDon.getYhsId());
  649. }
  650. } else {
  651. //余额退款不需要扣除积分
  652. //分销提成积分扣除
  653. deductDsPoints(orderDon);
  654. //店铺 分销提成金额扣除
  655. yhShopDistributeService.deductDsMoney(orderDon);
  656. }
  657. if (orderDon.getIsFixedDistribute()) {
  658. //商务提成 因订单退款去掉
  659. UserDistributeBusinessOrderDonRecord record = businessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(UserDistributeBusinessOrderDonRecord.class)
  660. .eq(UserDistributeBusinessOrderDonRecord::getOrderId, orderDon.getId())
  661. .eq(UserDistributeBusinessOrderDonRecord::getStatus, UserDistributeBusinessOrderDonRecord.Status.success)
  662. .last("limit 1"));
  663. if (record != null) {
  664. record.setStatus(UserDistributeBusinessOrderDonRecord.Status.refund);
  665. businessOrderDonRecordMapper.updateById(record);
  666. }
  667. }
  668. //店铺商务提成
  669. if (orderDon.getYhsId() != null && orderDon.getYhsId() > 0) {
  670. YhShopUserDistributeBusinessOrderDonRecord shop_record = yhShopBusinessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(YhShopUserDistributeBusinessOrderDonRecord.class)
  671. .eq(YhShopUserDistributeBusinessOrderDonRecord::getOrderId, orderDon.getId())
  672. .eq(YhShopUserDistributeBusinessOrderDonRecord::getStatus, YhShopUserDistributeBusinessOrderDonRecord.Status.success)
  673. .last("limit 1"));
  674. if (shop_record != null) {
  675. shop_record.setStatus(YhShopUserDistributeBusinessOrderDonRecord.Status.refund);
  676. yhShopBusinessOrderDonRecordMapper.updateById(shop_record);
  677. }
  678. }
  679. //是否是优惠加购关联订单
  680. if (orderDon.getIsDp()) {
  681. OrderDiscountPlusPurchaseSkuRelation discountPlusPurchaseSkuRelation = orderDiscountPlusPurchaseSkuRelationMapper.selectOne(Wrappers.lambdaQuery(OrderDiscountPlusPurchaseSkuRelation.class)
  682. .eq(OrderDiscountPlusPurchaseSkuRelation::getOrderId, orderDon.getId()).last("limit 1"));
  683. if (discountPlusPurchaseSkuRelation != null) {
  684. String relationIdsStr = discountPlusPurchaseSkuRelation.getRelationIds();
  685. if (StrUtil.isNotBlank(relationIdsStr)) {
  686. try {
  687. List<Long> relationIds = Jsons.parseList(relationIdsStr, Long.class);
  688. List<GroupsRelation> groupsRelations = relationMapper.selectList(Wrappers.lambdaQuery(GroupsRelation.class)
  689. .in(GroupsRelation::getId, relationIds));
  690. log.info("优惠加购订单orderId:{}退款,清除相关车票relation_ids:{}", orderDon.getId(), relationIds);
  691. groupsRelations.forEach(relation -> relationClearService.clearTicket(relation, UserTicketClearedRecord.Source.dp));
  692. } catch (Exception e) {
  693. }
  694. }
  695. String plusOrderIds = discountPlusPurchaseSkuRelation.getPlusOrderIds();
  696. if (StrUtil.isNotBlank(plusOrderIds)) {
  697. try {
  698. log.info("关闭优惠加购orderId:{}关联实物订单", orderDon.getId());
  699. List<Long> plusOrderIdList = Jsons.parseList(plusOrderIds, Long.class);
  700. List<OrderDon> relate_orderDons = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class)
  701. .in(OrderDon::getId, plusOrderIdList)
  702. .notIn(OrderDon::getStatus, Constant.noOrderStatus));
  703. relate_orderDons.forEach(relate_o->{
  704. //扣除用户自身实物权益
  705. userRealOrderBenefitsService.deductUserRealGoodsBenefits(relate_o.getId());
  706. });
  707. orderDonMapper.update(null, Wrappers.lambdaUpdate(OrderDon.class)
  708. .set(OrderDon::getStatus, OrderDon.Status.refund)
  709. .in(OrderDon::getId, plusOrderIdList)
  710. .ne(OrderDon::getStatus, OrderDon.Status.refund));
  711. } catch (Exception e) {
  712. }
  713. }
  714. }
  715. }
  716. //同步车票退款 重购记录
  717. TASK_POOL.execute(() -> {
  718. GroupsRelationExpiryRecord groupsRelationExpiryRecord = groupsRelationExpiryRecordService.getOne(Wrappers.lambdaQuery(GroupsRelationExpiryRecord.class)
  719. .in(GroupsRelationExpiryRecord::getReBuyOrderId, orderDon.getId())
  720. .eq(GroupsRelationExpiryRecord::getRelationId, orderDon.getRelationId()).last("limit 1"));
  721. if (groupsRelationExpiryRecord == null) {
  722. log.info("订单orderId:{}退款,同步是否有重购记录不是直接续费车票",orderDon.getId());
  723. List<GroupsRelationExpiryRecord> groupsRelationExpiryRecords = groupsRelationExpiryRecordService.list(Wrappers.lambdaQuery(GroupsRelationExpiryRecord.class)
  724. .in(GroupsRelationExpiryRecord::getReBuyOrderId, orderDon.getId()));
  725. log.info("订单orderId:{}退款,重购记录不是直接续费车票大小:{}",groupsRelationExpiryRecords.size());
  726. if (CollUtil.isNotEmpty(groupsRelationExpiryRecords)) {
  727. groupsRelationExpiryRecords.forEach(data -> {
  728. data.setIsReBuy(false);
  729. });
  730. groupsRelationExpiryRecordService.saveOrUpdateBatch(groupsRelationExpiryRecords);
  731. }
  732. }
  733. if (groupsRelationExpiryRecord != null) {
  734. groupsRelationExpiryRecord.setIsReBuy(false);
  735. groupsRelationExpiryRecordService.saveOrUpdate(groupsRelationExpiryRecord);
  736. }
  737. });
  738. //是否是礼品卡 现金支付订单
  739. BigDecimal gcCash = orderDon.getGcCash();
  740. if (gcCash != null && gcCash.compareTo(BigDecimal.ZERO) > 0) {
  741. giftCardOrderUseRecordService.returnGiftCardCash(orderDon.getId());
  742. }
  743. });
  744. }
  745. /**
  746. * 退款 分销提成积分扣除
  747. */
  748. public void deductDsPoints(OrderDon orderDon) {
  749. if (orderDon.getIsDistribute()) {
  750. DistributeWaitingSendPoints distributeWaitingSendPoints = distributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(DistributeWaitingSendPoints.class).eq(DistributeWaitingSendPoints::getOrderId, orderDon.getId()).last("limit 1"));
  751. if (distributeWaitingSendPoints != null) {
  752. BigDecimal money = orderDon.getMoney();
  753. BigDecimal refundMoney = orderDon.getRefundMoney();
  754. //已发送 发送中 部分 全额退款
  755. DistributeWaitingSendPoints.Status sendStatus = distributeWaitingSendPoints.getSendStatus();
  756. BigDecimal points = distributeWaitingSendPoints.getPoints();
  757. if (sendStatus == DistributeWaitingSendPoints.Status.waiting) {
  758. if (refundMoney.compareTo(money) == 0) {
  759. //待发送状态 全额退款
  760. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  761. distributeWaitingSendPoints.setRefundPoints(points);
  762. distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
  763. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  764. return;
  765. }
  766. Integer thisGoodsRate = distributeWaitingSendPoints.getRate();
  767. if (thisGoodsRate == null || thisGoodsRate == 0) {
  768. thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
  769. }
  770. if (thisGoodsRate > 0) {
  771. BigDecimal needSubPoints = refundMoney.multiply(BigDecimal.valueOf(thisGoodsRate).divide(BigDecimal.valueOf(100))).multiply(BigDecimal.valueOf(10));
  772. if (needSubPoints.compareTo(points) > 0) {
  773. //全扣除
  774. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  775. needSubPoints = points;
  776. }
  777. distributeWaitingSendPoints.setRefundPoints(needSubPoints);
  778. //剩余积分
  779. BigDecimal remainPoints = points.subtract(needSubPoints);
  780. distributeWaitingSendPoints.setPoints(remainPoints);
  781. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  782. }
  783. } else if (sendStatus == DistributeWaitingSendPoints.Status.success) {
  784. //已发送的提成 部分退款 全额退款 需要扣除用户积分
  785. //扣除固定推广者积分
  786. if (refundMoney.compareTo(money) == 0) {
  787. userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), points);
  788. distributeWaitingSendPoints.setRefundPoints(points);
  789. distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
  790. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  791. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  792. return;
  793. }
  794. Integer thisGoodsRate = distributeWaitingSendPoints.getRate();
  795. if (thisGoodsRate == null || thisGoodsRate == 0) {
  796. thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
  797. }
  798. if (thisGoodsRate > 0) {
  799. BigDecimal needSubPoints = refundMoney.multiply(BigDecimal.valueOf(thisGoodsRate).divide(BigDecimal.valueOf(100))).multiply(BigDecimal.valueOf(10));
  800. if (needSubPoints.compareTo(points) > 0) {
  801. //全扣除
  802. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  803. needSubPoints = points;
  804. }
  805. userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), needSubPoints);
  806. //部分退款
  807. distributeWaitingSendPoints.setRefundPoints(needSubPoints);
  808. distributeWaitingSendPoints.setPoints(points.subtract(needSubPoints));
  809. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  810. }
  811. }
  812. }
  813. }
  814. }
  815. /**
  816. * 记录退款信息
  817. */
  818. @Override
  819. public void refundRecord(OrderDon orderDon, GoodsDon goodsDon, GoodsDonSku sku, String outRefundNo, String refundType) {
  820. RefundOrderDon refund = new RefundOrderDon();
  821. refund.setOrderId(orderDon.getId());
  822. refund.setOutRefundNo(outRefundNo);
  823. refund.setTotalFee(orderDon.getMoney());
  824. refund.setRefundDesc(orderDon.getRefundDesc());
  825. //退款金额
  826. refund.setRefundFee(orderDon.getRefundMoney());
  827. refund.setUserId(orderDon.getUserId());
  828. refund.setGoodsId(orderDon.getGoodsId());
  829. refund.setGoodsTitle(goodsDon == null ? null : goodsDon.getTitle());
  830. refund.setSkuId(orderDon.getSkuId());
  831. refund.setSpecVal(sku == null ? null : String.format("%s%s", sku.getSpecVal(), sku.getPrice().divide(BigDecimal.valueOf(100))));
  832. refund.setRefundMethod(orderDon.getType().name());
  833. refund.setGoodsType(goodsDon == null ? 0 : goodsDon.getType());
  834. //退款方式
  835. if (StrUtil.isNotBlank(refundType) && refundType.equals(OrderDon.Type.BALANCE.getType())) {
  836. refund.setRefundMethod(refundType);
  837. refund.setRefundFee(orderDon.getRefundBalance());
  838. }
  839. refundOrderDonMapper.insert(refund);
  840. }
  841. @Override
  842. public void refundPriceDiffer(OrderRefundReq orderRefundReq) {
  843. Long orderId = orderRefundReq.getOrderId();
  844. OrderDon orderDon = orderDonMapper.selectById(orderId);
  845. if (orderDon == null) {
  846. throw BusinessRuntimeException.getInstance("订单不存在");
  847. }
  848. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  849. throw BusinessRuntimeException.getInstance("该订单是0元订单,无法补差价");
  850. }
  851. if (Constant.noOrderAllStatus.contains(orderDon.getStatus().name())) {
  852. throw BusinessRuntimeException.getInstance("订单不是已支付状态");
  853. }
  854. BigDecimal refundBalance = orderRefundReq.getRefundBalance();
  855. if (refundBalance == null || refundBalance.compareTo(BigDecimal.ZERO) <= 0 || refundBalance.compareTo(orderDon.getMoney()) > 0) {
  856. throw BusinessRuntimeException.getInstance("请输入正确的差价金额");
  857. }
  858. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.price_differ, orderDon.getYhsId());
  859. }
  860. /**
  861. * 寻找该车队空余车位
  862. */
  863. public GroupsRelation getRelationThisTrips(Long userId, Long groupsId, Integer retryNum) {
  864. //寻找快满编车队进行占座
  865. GroupsRelation relation = relationMapper.selectRandomOneRelationByGroupsId(groupsId);
  866. if (relation == null) {
  867. throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  868. }
  869. Long relationId = relation.getId();
  870. if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
  871. if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  872. retryNum++;
  873. getRelationThisTrips(userId, groupsId, retryNum);
  874. }
  875. int count = groupsMapper.decrAvailableNum(relation.getGroupsId());
  876. if (count == 0) {
  877. log.error("车位异常 groupId:{}", groupsId);
  878. groupsMapper.updateAvailableNum(groupsId);
  879. throw new BusinessRuntimeException("车位异常");
  880. }
  881. return relation;
  882. }
  883. private GroupsRelation getChatGPTOutsideRelation(Long userId, Long groupsId, Integer relationNum, Integer retryNum) {
  884. //寻找快满编车队额外座位
  885. GroupsRelation relation = relationMapper.selectOutsideRelationByGroupsId(groupsId, relationNum);
  886. if (relation == null) {
  887. relation = new GroupsRelation();
  888. relation.setStatus(GroupsRelation.Status.outside);
  889. relation.setUserId(userId);
  890. relation.setGroupsId(groupsId);
  891. GroupsRelation maxNumRelation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getGroupsId, groupsId).orderByDesc(GroupsRelation::getNum).last("limit 1"));
  892. relation.setNum(maxNumRelation.getNum() + 1);
  893. relationMapper.insert(relation);
  894. return relation;
  895. }
  896. Long relationId = relation.getId();
  897. if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
  898. if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  899. retryNum++;
  900. getChatGPTOutsideRelation(userId, groupsId, relationNum, retryNum);
  901. }
  902. return relation;
  903. }
  904. }