CmsOrderDonServiceImpl.java 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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. //调用第三方接口退款
  265. String outNo = centerRefund(refundReq, orderDon);
  266. orderDon.setRefundDesc(refundReq.getRefundDesc());
  267. //记录退款信息
  268. commonRefund(orderDon, goodsDon, sku, outNo, refundType);
  269. //修改订单状态
  270. orderDon.setStatus(OrderDon.Status.refund);
  271. orderDonMapper.updateById(orderDon);
  272. //提交过工单的订单
  273. //将用户异常订单关闭
  274. workOrderMapper.update(null, Wrappers.lambdaUpdate(WorkOrder.class)
  275. .set(WorkOrder::getStatus, WorkOrder.Status.close)
  276. .eq(WorkOrder::getStatus, WorkOrder.Status.waiting)
  277. .eq(WorkOrder::getUserId, orderDon.getUserId())
  278. .eq(WorkOrder::getRelationId, orderDon.getRelationId()));
  279. }
  280. public String wxRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
  281. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) <=0){
  282. return StrUtil.EMPTY;
  283. }
  284. long time = System.currentTimeMillis();
  285. //退款订单号
  286. String outRefundNo = Codec.DoDigest.custom()
  287. .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
  288. .setStringData(time + String.valueOf(orderDon.getId()))
  289. .toHexString();
  290. weChatService.refundWxOrder(weChatConfig.getAppid(),
  291. Optional.ofNullable(orderDon.getShopId()).orElse(ShopConfig.WX_DEFAULT_APP_ID),
  292. orderDon.getTransactionId(),
  293. outRefundNo,
  294. orderDon.getMoney(),
  295. refundReq.getRefundMoney(),
  296. weChatConfig.getDomain() + "manage/order/wx/refund/notify");
  297. //记录退款信息
  298. return outRefundNo;
  299. }
  300. @Override
  301. public void wxRefundNotify(Map<String, String> map) throws Exception {
  302. // 对退款数据 解密
  303. String md5Key = Codec.DoDigest.custom().setAlgorithm(Codec.DoDigest.Algorithm.MD5).setStringData(shopConfigMapper.getByAppId(map.get("mch_id")).getSecret()).toHexString();
  304. String reqInfoXml = Codec.DoCipher.custom().setAlgorithm(Codec.DoCipher.Trans.AES_ECB_PKCS7Padding).setBase64Data(map.get("req_info")).setStringKey(md5Key).ofDecrypt().toText();
  305. log.info("=== 退款数据解密: \n {}", reqInfoXml);
  306. Map<String, String> reqInfoMap = Xmls.toMap(reqInfoXml);
  307. // 退款失败
  308. if (StrUtil.equals("CHANGE", reqInfoMap.get("refund_status"))) {
  309. throw BusinessRuntimeException.getInstance("退款异常.");
  310. } else if (StrUtil.equals("REFUNDCLOSE", reqInfoMap.get("refund_status"))) {
  311. throw BusinessRuntimeException.getInstance("退款关闭.");
  312. }
  313. /* 此处处理业务逻辑 */
  314. String outRefundNo = reqInfoMap.get("out_refund_no");
  315. String transactionId = reqInfoMap.get("transaction_id");
  316. String refundFee = reqInfoMap.get("refund_fee");
  317. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getTransactionId, transactionId).last("limit 1"));
  318. if (orderDon == null) {
  319. log.error("退款回调,transactionId:{}订单不存在", transactionId);
  320. return;
  321. }
  322. log.info("微信退款: 退款单号[{}] 退款成功.", outRefundNo);
  323. }
  324. @Override
  325. @Transactional(rollbackFor = Throwable.class)
  326. public void changeRelation(ChangeRelationReq req) throws Exception {
  327. Long relationId = req.getRelationId();
  328. Long groupId = req.getGroupsId();
  329. UserTicketClearedRecord.Source source = req.getSource();
  330. if (source == null) source = UserTicketClearedRecord.Source.change_ticket;
  331. GroupsRelation relation = relationMapper.selectById(relationId);
  332. Long yhsId = relation.getYhsId();
  333. Assert.notNull(relation, "车票已不存在");
  334. if (relation.getRechargeStatus() != null) {
  335. throw BusinessRuntimeException.getInstance("代充账号车票无法更换车票");
  336. }
  337. Long userId = relation.getUserId();
  338. log.info("用户userId:{}更换车票relationId:{}", userId, relationId);
  339. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  340. .eq(OrderDon::getUserId, userId)
  341. .eq(OrderDon::getRelationId, relationId)
  342. .notIn(OrderDon::getStatus, Constant.noOrderStatus)
  343. .orderByDesc(OrderDon::getId)
  344. .last("limit 1"));
  345. OrderDiscountPlusPurchaseSkuRelation plusPurchaseSkuRelation = null;
  346. List<Long> plus_relationList = null;
  347. if (orderDon == null) {
  348. List<OrderDiscountPlusPurchaseSkuRelation> plusPurchaseSkuRelations = orderDiscountPlusPurchaseSkuRelationMapper.selectPlusRelationByIdAndUserId(relation.getId(), relation.getUserId());
  349. for (OrderDiscountPlusPurchaseSkuRelation data : plusPurchaseSkuRelations) {
  350. String relationIds = data.getRelationIds();
  351. if (StrUtil.isEmpty(relationIds)) {
  352. return;
  353. }
  354. List<Long> relationList = Jsons.parseList(relationIds, Long.class);
  355. if (relationList.contains(relationId)) {
  356. plusPurchaseSkuRelation = data;
  357. break;
  358. }
  359. }
  360. if (plusPurchaseSkuRelation != null) {
  361. String relationIds = plusPurchaseSkuRelation.getRelationIds();
  362. if (StrUtil.isNotEmpty(relationIds)) {
  363. plus_relationList = Jsons.parseList(relationIds, Long.class);
  364. if (plus_relationList.contains(relationId)) {
  365. orderDon = new OrderDon();
  366. GroupsRelationView groupsRelationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder().field(GroupsRelationView::getId, relationId).build());
  367. Assert.notNull(groupsRelationView, "车票已不存在");
  368. orderDon.setUserId(groupsRelationView.getUserId());
  369. orderDon.setSkuId(groupsRelationView.getSkuId());
  370. orderDon.setGoodsId(groupsRelationView.getGoodsId());
  371. orderDon.setStatus(OrderDon.Status.complete);
  372. }
  373. }
  374. }
  375. }
  376. Assert.notNull(orderDon, "订单不存在");
  377. if (orderDon.getStatus() == OrderDon.Status.refund) {
  378. throw BusinessRuntimeException.getInstance("订单已退款");
  379. }
  380. //获取新车队
  381. LambdaQueryWrapper<GroupsTrips> queryWrapper = Wrappers.lambdaQuery(GroupsTrips.class)
  382. .eq(GroupsTrips::getSkuId, orderDon.getSkuId())
  383. .eq(GroupsTrips::getId, groupId)
  384. .ne(GroupsTrips::getId, relation.getGroupsId())
  385. .ne(GroupsTrips::getStatus, GroupsTrips.Status.down)
  386. .last("limit 1");
  387. GroupsTrips groups = groupsMapper.selectOne(queryWrapper);
  388. if (groups == null) throw BusinessRuntimeException.getInstance("车队不存在或已下架");
  389. if (!Constant.AI_goodsIds.contains(orderDon.getGoodsId()) && groups.getAvailableNum() <= 0) {
  390. throw BusinessRuntimeException.getInstance("该新车位人员已满");
  391. }
  392. Integer relationNum = groups.getNum();
  393. //获取新车队车位
  394. GroupsRelation newRelation;
  395. Boolean isOutside = req.getIsOutside();
  396. if (Constant.AI_goodsIds.contains(orderDon.getGoodsId()) && ((isOutside != null && isOutside) || groups.getAvailableNum() == 0)) {
  397. //Ai车队 额外增加车位 并不让上车
  398. newRelation = getChatGPTOutsideRelation(orderDon.getUserId(), groupId, relationNum, 1);
  399. } else {
  400. newRelation = getRelationThisTrips(orderDon.getUserId(), groupId, 1);
  401. }
  402. newRelation.setUserId(userId);
  403. newRelation.setStartTime(relation.getStartTime());
  404. newRelation.setExpiryTime(relation.getExpiryTime());
  405. newRelation.setYhsId(yhsId);
  406. newRelation.setCustomerService(relation.getCustomerService());
  407. if (newRelation.getStatus() != GroupsRelation.Status.outside) {
  408. newRelation.setStatus(GroupsRelation.Status.validity);
  409. }
  410. //清除原先车票
  411. relation.setNewRelationId(newRelation.getId());
  412. relationClearService.clearTicket(relation, source);
  413. if (plusPurchaseSkuRelation != null && plus_relationList != null) {
  414. plus_relationList.remove(relationId);
  415. plus_relationList.add(newRelation.getId());
  416. plusPurchaseSkuRelation.setRelationIds(plus_relationList.toString());
  417. orderDiscountPlusPurchaseSkuRelationMapper.updateById(plusPurchaseSkuRelation);
  418. }
  419. if (source != null && source == UserTicketClearedRecord.Source.abnormal) {
  420. //将用户异常订单关闭
  421. workOrderMapper.update(null, Wrappers.lambdaUpdate(WorkOrder.class)
  422. .set(WorkOrder::getStatus, WorkOrder.Status.close)
  423. .eq(WorkOrder::getStatus, WorkOrder.Status.waiting)
  424. .eq(WorkOrder::getUserId, userId)
  425. .eq(WorkOrder::getRelationId, relationId));
  426. }
  427. if (orderDon.getMoney() != null && orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  428. //是否是实物权益车票
  429. UserPayEquipmentReceiveBenefitsRecord receiveBenefitsRecord = receiveBenefitsRecordMapper.selectOne(Wrappers.lambdaQuery(UserPayEquipmentReceiveBenefitsRecord.class)
  430. .eq(UserPayEquipmentReceiveBenefitsRecord::getTicketOrderId, orderDon.getId())
  431. .eq(UserPayEquipmentReceiveBenefitsRecord::getRelationId, relationId).last("limit 1"));
  432. if (receiveBenefitsRecord != null) {
  433. receiveBenefitsRecord.setRelationId(newRelation.getId());
  434. receiveBenefitsRecordMapper.updateById(receiveBenefitsRecord);
  435. }
  436. }
  437. if ((newRelation.getStartTime() == null || newRelation.getExpiryTime() == null)) {
  438. List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.hasPayment));
  439. if (orderDonList.isEmpty()) {
  440. orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class)
  441. .eq(OrderDon::getUserId, userId)
  442. .eq(OrderDon::getRelationId, relationId)
  443. .eq(OrderDon::getStatus, OrderDon.Status.complete)
  444. .orderByDesc(OrderDon::getId)
  445. .last("limit 1"));
  446. }
  447. if (groups.getStatus() == GroupsTrips.Status.waiting) {
  448. orderDonList.forEach(hasPaymentOrder -> {
  449. hasPaymentOrder.setRelationId(newRelation.getId());
  450. orderDonMapper.updateById(hasPaymentOrder);
  451. });
  452. relationMapper.updateById(newRelation);
  453. return;
  454. }
  455. orderDonList.forEach((hasPaymentOrder) -> {
  456. //如果续费增加时间,如果首次则设置当前时间为初始时间
  457. Date expiryTime = Optional.ofNullable(newRelation.getExpiryTime()).orElse(new Date());
  458. GoodsDonSku donSku = skuMapper.selectById(hasPaymentOrder.getSkuId());
  459. Date newDate;
  460. if (donSku.getDays() != null && donSku.getDays() > 0) {
  461. newDate = DateUtil.offsetDay(expiryTime, donSku.getDays() * hasPaymentOrder.getNum());
  462. } else {
  463. newDate = DateUtil.offset(expiryTime, DateField.MONTH, donSku.getMonths() * hasPaymentOrder.getNum());
  464. }
  465. newRelation.setExpiryTime(newDate);
  466. newRelation.setStartTime(newRelation.getStartTime() == null ? new Date() : null);
  467. relationMapper.updateById(newRelation);
  468. hasPaymentOrder.setStatus(OrderDon.Status.complete);
  469. hasPaymentOrder.setRelationId(newRelation.getId());
  470. orderDonMapper.updateById(hasPaymentOrder);
  471. });
  472. return;
  473. }
  474. List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.complete));
  475. orderDonList.forEach(completeOrder->{
  476. completeOrder.setRelationId(newRelation.getId());
  477. orderDonMapper.updateById(completeOrder);
  478. });
  479. log.info("userId:{}更换车票,原座位号relationId:{}======>新座位号newRelationId:{}", newRelation.getUserId(), relationId, newRelation.getId());
  480. relationMapper.updateById(newRelation);
  481. }
  482. public String zfbRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
  483. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) <=0){
  484. return StrUtil.EMPTY;
  485. }
  486. AlipayTradeRefundResponse response;
  487. //支付宝退款
  488. AlipayClient alipayClient = AliPayClientFactory.getAlipayClient(Optional.ofNullable(orderDon.getShopId()).orElse(ShopConfig.ZFB_DEFAULT_APP_ID));
  489. AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
  490. AlipayTradeRefundModel model = new AlipayTradeRefundModel();
  491. //支付宝交易号
  492. model.setTradeNo(orderDon.getTransactionId());
  493. model.setRefundAmount(refundReq.getRefundMoney().divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_EVEN).toString());
  494. model.setQueryOptions(List.of("gmt_refund_pay"));
  495. long time = System.currentTimeMillis();
  496. //退款订单号
  497. String outRefundNo = Codec.DoDigest.custom()
  498. .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
  499. .setStringData(time + String.valueOf(orderDon.getId()))
  500. .toHexString();
  501. //退款请求号
  502. model.setOutRequestNo(outRefundNo);
  503. request.setBizModel(model);
  504. String shopId = orderDon.getShopId();
  505. ShopConfig shopConfig = shopConfigMapper.selectOne(Wrappers.lambdaQuery(ShopConfig.class).eq(ShopConfig::getAppId, orderDon.getShopId()));
  506. if (shopId != null && shopConfig != null && shopConfig.getIsCert()) {
  507. response = alipayClient.certificateExecute(request);
  508. } else {
  509. response = alipayClient.execute(request);
  510. }
  511. if (!response.isSuccess()) throw BusinessRuntimeException.getInstance("退款失败,e:{0}", response.getSubMsg());
  512. // AliPayRefundRep aliPayRefundRep = Jsons.parseObject(response.getBody(), AliPayRefundRep.class);
  513. // AliPayRefundRep.AlipayTradeRefundResponse res = aliPayRefundRep.getResponse();
  514. // orderDon.setRefundMoney(res.getRefundFee().multiply(BigDecimal.valueOf(100)));
  515. return outRefundNo;
  516. }
  517. /**
  518. * 校验订单是否符合退款操作
  519. */
  520. private void checkOrderRefund(OrderDon orderDon, GoodsDon goodsDon, GoodsDonSku sku, OrderRefundReq refundReq) {
  521. if (orderDon == null) {
  522. throw BusinessRuntimeException.getInstance("订单不存在");
  523. }
  524. BigDecimal orderDonRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  525. String refundType = refundReq.getRefundType();
  526. if (orderDon.getType() == OrderDon.Type.BALANCE && !OrderDon.Type.BALANCE.getType().equals(refundType)) {
  527. throw BusinessRuntimeException.getInstance("余额支付的订单不支持金额退款");
  528. }
  529. if (OrderDon.Status.refund == orderDon.getStatus()) {
  530. throw BusinessRuntimeException.getInstance("该订单已退款");
  531. }
  532. if (OrderDon.Status.noPayment == orderDon.getStatus() || OrderDon.Status.close == orderDon.getStatus()) {
  533. throw BusinessRuntimeException.getInstance("订单{0}状态不支持退款", orderDon.getStatus());
  534. }
  535. if (goodsDon.getType() == 1 && sku != null) {
  536. //虚拟原订单是否已过期
  537. Integer months = sku.getMonths();
  538. Integer days = sku.getDays();
  539. Integer num = orderDon.getNum();
  540. DateTime now = DateTime.now();
  541. DateTime endTime;
  542. if (days != null && days > 0) {
  543. endTime = DateUtil.offsetDay(orderDon.getCreatedTime(), days * num);
  544. } else {
  545. endTime = DateUtil.offsetMonth(orderDon.getCreatedTime(), months * num);
  546. }
  547. if (now.isAfter(endTime)) {
  548. throw BusinessRuntimeException.getInstance("该订单车票已过期");
  549. }
  550. if (orderDon.getOrderType() == 1) {
  551. //是否有其他付款订单是否过期
  552. OrderDon otherOrder = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  553. .eq(OrderDon::getRelationId, orderDon.getRelationId())
  554. .eq(OrderDon::getUserId, orderDon.getUserId())
  555. .ne(OrderDon::getId, orderDon.getId())
  556. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  557. .eq(OrderDon::getOrderType, 2)
  558. .orderByDesc(OrderDon::getId)
  559. .last("limit 1"));
  560. if (otherOrder != null) {
  561. throw BusinessRuntimeException.getInstance("该笔订单存在续费订单,请先退掉续费订单");
  562. }
  563. }
  564. }
  565. BigDecimal refundMoney = refundReq.getRefundMoney();
  566. BigDecimal money = orderDon.getMoney();
  567. //余额退款
  568. if (OrderDon.Type.BALANCE.getType().equals(refundType)) {
  569. BigDecimal balance = orderDon.getBalance();
  570. if (OrderDon.Type.BALANCE == orderDon.getType() && refundMoney.compareTo(balance) > 0) {
  571. throw BusinessRuntimeException.getInstance("退款余额大于订单支付余额");
  572. }
  573. if (OrderDon.Type.BALANCE != orderDon.getType() && refundMoney.compareTo(money) > 0) {
  574. throw BusinessRuntimeException.getInstance("退款余额大于订单支付金额");
  575. }
  576. orderDon.setRefundBalance(refundMoney);
  577. orderDon.setRefundMoney(BigDecimal.ZERO);
  578. } else {
  579. //退金额
  580. if (refundMoney.compareTo(money) > 0) {
  581. throw BusinessRuntimeException.getInstance("退款金额大于订单支付金额");
  582. }
  583. refundMoney = refundMoney.add(orderDonRefundMoney);
  584. orderDon.setRefundMoney(refundMoney);
  585. }
  586. //礼品卡是否已使用
  587. GiftCardUserRecord giftCardUserRecord = null;
  588. if (goodsDon.getSpecialType() != null && goodsDon.getSpecialType() == GoodsDon.SpecialType.giftCard) {
  589. giftCardUserRecord = giftCardUserRecordMapper.selectOne(Wrappers.lambdaQuery(GiftCardUserRecord.class)
  590. .eq(GiftCardUserRecord::getOrderId, orderDon.getId()).last("limit 1"));
  591. if (giftCardUserRecord != null && giftCardUserRecord.getIsUsed()) {
  592. throw BusinessRuntimeException.getInstance("该礼品卡已使用无法退款");
  593. }
  594. }
  595. if (!redisService.setNx(String.format("%s", refundReq.getOrderId()), refundReq.getOrderId(), 10l)) {
  596. throw BusinessRuntimeException.getInstance("请勿重复点击,正在退款中..");
  597. }
  598. //礼品卡购买状态
  599. if (giftCardUserRecord != null) {
  600. giftCardUserRecord.setIsPay(false);
  601. giftCardUserRecordMapper.updateById(giftCardUserRecord);
  602. }
  603. }
  604. /**
  605. * 退款后 处理关联
  606. */
  607. public void commonRefund(OrderDon orderDon, GoodsDon goodsDon, GoodsDonSku sku, String outNo, String refundType) {
  608. TASK_POOL.execute(() -> {
  609. refundRecord(orderDon, goodsDon, sku, outNo, refundType);
  610. //退款一次
  611. goodsDonStockService.upStockRelate(null, orderDon.getId(), "refund");
  612. try {
  613. //虚物订单退款,清出车队,车票变为已过期
  614. orderCommonService.clearUnrealGoodsDetail(orderDon, goodsDon.getType(), sku);
  615. } catch (Exception e) {
  616. log.error("清除车票错误:{}", StringUtil.getErrorText(e));
  617. }
  618. //若存在优惠券使用,退还优惠券
  619. if (orderDon.getCouponUserId() != 0) {
  620. couponFontService.updateOrderDonCouponStatus(orderDon);
  621. }
  622. //若存在余额支付,退还余额
  623. if (orderDon.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  624. userBenefitsService.addUserBalance(orderDon.getUserId(), orderDon.getBalance(), UserBalanceSourceRecord.Source.balance, orderDon.getYhsId());
  625. }
  626. try {
  627. marketFrontService.subSpecificChanceNum(orderDon.getUserId(), orderDon.getId(), orderDon.getGoodsId(), orderDon.getUpdateTime());
  628. if (goodsDon.getType() == 2) {
  629. equipmentDistributeService.subDistributeBenefitsChance(orderDon.getUserId(), orderDon.getId());
  630. //扣除用户自身实物权益
  631. userRealOrderBenefitsService.deductUserRealGoodsBenefits(orderDon.getId());
  632. }
  633. } catch (Exception e) {
  634. log.error("wx减少抽奖机会错误,orderId:{},error:{}", orderDon.getId(), e);
  635. }
  636. if (OrderDon.Type.BALANCE.getType().equals(refundType)) {
  637. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) > 0) {
  638. userBenefitsService.addUserBalance(orderDon.getUserId(), orderDon.getRefundBalance(), UserBalanceSourceRecord.Source.refund, orderDon.getYhsId());
  639. }
  640. } else {
  641. //余额退款不需要扣除积分
  642. //分销提成积分扣除
  643. deductDsPoints(orderDon);
  644. //店铺 分销提成金额扣除
  645. yhShopDistributeService.deductDsMoney(orderDon);
  646. }
  647. if (orderDon.getIsFixedDistribute()) {
  648. //商务提成 因订单退款去掉
  649. UserDistributeBusinessOrderDonRecord record = businessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(UserDistributeBusinessOrderDonRecord.class)
  650. .eq(UserDistributeBusinessOrderDonRecord::getOrderId, orderDon.getId())
  651. .eq(UserDistributeBusinessOrderDonRecord::getStatus, UserDistributeBusinessOrderDonRecord.Status.success)
  652. .last("limit 1"));
  653. if (record != null) {
  654. record.setStatus(UserDistributeBusinessOrderDonRecord.Status.refund);
  655. businessOrderDonRecordMapper.updateById(record);
  656. }
  657. }
  658. //店铺商务提成
  659. if (orderDon.getYhsId() != null && orderDon.getYhsId() > 0) {
  660. YhShopUserDistributeBusinessOrderDonRecord shop_record = yhShopBusinessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(YhShopUserDistributeBusinessOrderDonRecord.class)
  661. .eq(YhShopUserDistributeBusinessOrderDonRecord::getOrderId, orderDon.getId())
  662. .eq(YhShopUserDistributeBusinessOrderDonRecord::getStatus, YhShopUserDistributeBusinessOrderDonRecord.Status.success)
  663. .last("limit 1"));
  664. if (shop_record != null) {
  665. shop_record.setStatus(YhShopUserDistributeBusinessOrderDonRecord.Status.refund);
  666. yhShopBusinessOrderDonRecordMapper.updateById(shop_record);
  667. }
  668. }
  669. //是否是优惠加购关联订单
  670. if (orderDon.getIsDp()) {
  671. OrderDiscountPlusPurchaseSkuRelation discountPlusPurchaseSkuRelation = orderDiscountPlusPurchaseSkuRelationMapper.selectOne(Wrappers.lambdaQuery(OrderDiscountPlusPurchaseSkuRelation.class)
  672. .eq(OrderDiscountPlusPurchaseSkuRelation::getOrderId, orderDon.getId()).last("limit 1"));
  673. if (discountPlusPurchaseSkuRelation != null) {
  674. String relationIdsStr = discountPlusPurchaseSkuRelation.getRelationIds();
  675. if (StrUtil.isNotBlank(relationIdsStr)) {
  676. try {
  677. List<Long> relationIds = Jsons.parseList(relationIdsStr, Long.class);
  678. List<GroupsRelation> groupsRelations = relationMapper.selectList(Wrappers.lambdaQuery(GroupsRelation.class)
  679. .in(GroupsRelation::getId, relationIds));
  680. log.info("优惠加购订单orderId:{}退款,清除相关车票relation_ids:{}", orderDon.getId(), relationIds);
  681. groupsRelations.forEach(relation -> relationClearService.clearTicket(relation, UserTicketClearedRecord.Source.dp));
  682. } catch (Exception e) {
  683. }
  684. }
  685. String plusOrderIds = discountPlusPurchaseSkuRelation.getPlusOrderIds();
  686. if (StrUtil.isNotBlank(plusOrderIds)) {
  687. try {
  688. log.info("关闭优惠加购orderId:{}关联实物订单", orderDon.getId());
  689. List<Long> plusOrderIdList = Jsons.parseList(plusOrderIds, Long.class);
  690. List<OrderDon> relate_orderDons = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class)
  691. .in(OrderDon::getId, plusOrderIdList)
  692. .notIn(OrderDon::getStatus, Constant.noOrderStatus));
  693. relate_orderDons.forEach(relate_o->{
  694. //扣除用户自身实物权益
  695. userRealOrderBenefitsService.deductUserRealGoodsBenefits(relate_o.getId());
  696. });
  697. orderDonMapper.update(null, Wrappers.lambdaUpdate(OrderDon.class)
  698. .set(OrderDon::getStatus, OrderDon.Status.refund)
  699. .in(OrderDon::getId, plusOrderIdList)
  700. .ne(OrderDon::getStatus, OrderDon.Status.refund));
  701. } catch (Exception e) {
  702. }
  703. }
  704. }
  705. }
  706. //同步车票退款 重购记录
  707. TASK_POOL.execute(() -> {
  708. GroupsRelationExpiryRecord groupsRelationExpiryRecord = groupsRelationExpiryRecordService.getOne(Wrappers.lambdaQuery(GroupsRelationExpiryRecord.class)
  709. .in(GroupsRelationExpiryRecord::getReBuyOrderId, orderDon.getId())
  710. .eq(GroupsRelationExpiryRecord::getRelationId, orderDon.getRelationId()).last("limit 1"));
  711. if (groupsRelationExpiryRecord == null) {
  712. log.info("订单orderId:{}退款,同步是否有重购记录不是直接续费车票",orderDon.getId());
  713. List<GroupsRelationExpiryRecord> groupsRelationExpiryRecords = groupsRelationExpiryRecordService.list(Wrappers.lambdaQuery(GroupsRelationExpiryRecord.class)
  714. .in(GroupsRelationExpiryRecord::getReBuyOrderId, orderDon.getId()));
  715. log.info("订单orderId:{}退款,重购记录不是直接续费车票大小:{}",groupsRelationExpiryRecords.size());
  716. if (CollUtil.isNotEmpty(groupsRelationExpiryRecords)) {
  717. groupsRelationExpiryRecords.forEach(data -> {
  718. data.setIsReBuy(false);
  719. });
  720. groupsRelationExpiryRecordService.saveOrUpdateBatch(groupsRelationExpiryRecords);
  721. }
  722. }
  723. if (groupsRelationExpiryRecord != null) {
  724. groupsRelationExpiryRecord.setIsReBuy(false);
  725. groupsRelationExpiryRecordService.saveOrUpdate(groupsRelationExpiryRecord);
  726. }
  727. });
  728. //是否是礼品卡 现金支付订单
  729. BigDecimal gcCash = orderDon.getGcCash();
  730. if (gcCash != null && gcCash.compareTo(BigDecimal.ZERO) > 0) {
  731. giftCardOrderUseRecordService.returnGiftCardCash(orderDon.getId());
  732. }
  733. });
  734. }
  735. /**
  736. * 退款 分销提成积分扣除
  737. */
  738. public void deductDsPoints(OrderDon orderDon) {
  739. if (orderDon.getIsDistribute()) {
  740. DistributeWaitingSendPoints distributeWaitingSendPoints = distributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(DistributeWaitingSendPoints.class).eq(DistributeWaitingSendPoints::getOrderId, orderDon.getId()).last("limit 1"));
  741. if (distributeWaitingSendPoints != null) {
  742. BigDecimal money = orderDon.getMoney();
  743. BigDecimal refundMoney = orderDon.getRefundMoney();
  744. //已发送 发送中 部分 全额退款
  745. DistributeWaitingSendPoints.Status sendStatus = distributeWaitingSendPoints.getSendStatus();
  746. BigDecimal points = distributeWaitingSendPoints.getPoints();
  747. if (sendStatus == DistributeWaitingSendPoints.Status.waiting) {
  748. if (refundMoney.compareTo(money) == 0) {
  749. //待发送状态 全额退款
  750. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  751. distributeWaitingSendPoints.setRefundPoints(points);
  752. distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
  753. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  754. return;
  755. }
  756. Integer thisGoodsRate = distributeWaitingSendPoints.getRate();
  757. if (thisGoodsRate == null || thisGoodsRate == 0) {
  758. thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
  759. }
  760. if (thisGoodsRate > 0) {
  761. BigDecimal needSubPoints = refundMoney.multiply(BigDecimal.valueOf(thisGoodsRate).divide(BigDecimal.valueOf(100))).multiply(BigDecimal.valueOf(10));
  762. if (needSubPoints.compareTo(points) > 0) {
  763. //全扣除
  764. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  765. needSubPoints = points;
  766. }
  767. distributeWaitingSendPoints.setRefundPoints(needSubPoints);
  768. //剩余积分
  769. BigDecimal remainPoints = points.subtract(needSubPoints);
  770. distributeWaitingSendPoints.setPoints(remainPoints);
  771. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  772. }
  773. } else if (sendStatus == DistributeWaitingSendPoints.Status.success) {
  774. //已发送的提成 部分退款 全额退款 需要扣除用户积分
  775. //扣除固定推广者积分
  776. if (refundMoney.compareTo(money) == 0) {
  777. userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), points);
  778. distributeWaitingSendPoints.setRefundPoints(points);
  779. distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
  780. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  781. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  782. return;
  783. }
  784. Integer thisGoodsRate = distributeWaitingSendPoints.getRate();
  785. if (thisGoodsRate == null || thisGoodsRate == 0) {
  786. thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
  787. }
  788. if (thisGoodsRate > 0) {
  789. BigDecimal needSubPoints = refundMoney.multiply(BigDecimal.valueOf(thisGoodsRate).divide(BigDecimal.valueOf(100))).multiply(BigDecimal.valueOf(10));
  790. if (needSubPoints.compareTo(points) > 0) {
  791. //全扣除
  792. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  793. needSubPoints = points;
  794. }
  795. userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), needSubPoints);
  796. //部分退款
  797. distributeWaitingSendPoints.setRefundPoints(needSubPoints);
  798. distributeWaitingSendPoints.setPoints(points.subtract(needSubPoints));
  799. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  800. }
  801. }
  802. }
  803. }
  804. }
  805. /**
  806. * 记录退款信息
  807. */
  808. @Override
  809. public void refundRecord(OrderDon orderDon, GoodsDon goodsDon, GoodsDonSku sku, String outRefundNo, String refundType) {
  810. RefundOrderDon refund = new RefundOrderDon();
  811. refund.setOrderId(orderDon.getId());
  812. refund.setOutRefundNo(outRefundNo);
  813. refund.setTotalFee(orderDon.getMoney());
  814. refund.setRefundDesc(orderDon.getRefundDesc());
  815. //退款金额
  816. refund.setRefundFee(orderDon.getRefundMoney());
  817. refund.setUserId(orderDon.getUserId());
  818. refund.setGoodsId(orderDon.getGoodsId());
  819. refund.setGoodsTitle(goodsDon == null ? null : goodsDon.getTitle());
  820. refund.setSkuId(orderDon.getSkuId());
  821. refund.setSpecVal(sku == null ? null : String.format("%s%s", sku.getSpecVal(), sku.getPrice().divide(BigDecimal.valueOf(100))));
  822. refund.setRefundMethod(orderDon.getType().name());
  823. refund.setGoodsType(goodsDon == null ? 0 : goodsDon.getType());
  824. //退款方式
  825. if (StrUtil.isNotBlank(refundType) && refundType.equals(OrderDon.Type.BALANCE.getType())) {
  826. refund.setRefundMethod(refundType);
  827. refund.setRefundFee(orderDon.getRefundBalance());
  828. }
  829. refundOrderDonMapper.insert(refund);
  830. }
  831. @Override
  832. public void refundPriceDiffer(OrderRefundReq orderRefundReq) throws Exception {
  833. Long orderId = orderRefundReq.getOrderId();
  834. OrderDon orderDon = orderDonMapper.selectById(orderId);
  835. if (orderDon == null) {
  836. throw BusinessRuntimeException.getInstance("订单不存在");
  837. }
  838. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  839. throw BusinessRuntimeException.getInstance("该订单是0元订单,无法补差价");
  840. }
  841. if (Constant.noOrderAllStatus.contains(orderDon.getStatus().name())) {
  842. throw BusinessRuntimeException.getInstance("订单不是已支付状态");
  843. }
  844. //默认补差价余额
  845. String refundType = Optional.ofNullable(orderRefundReq.getRefundType()).orElse("balance");
  846. BigDecimal refundMoney = orderRefundReq.getRefundMoney();
  847. if ("money".equals(refundType)) {
  848. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  849. throw BusinessRuntimeException.getInstance("该订单为0元订单,无法补差价至用户账户");
  850. }
  851. if (refundMoney == null || refundMoney.compareTo(BigDecimal.ZERO) <= 0) {
  852. throw BusinessRuntimeException.getInstance("请输入正确的差价金额");
  853. }
  854. if (refundMoney.compareTo(orderDon.getMoney()) >= 0) {
  855. throw BusinessRuntimeException.getInstance("补差价金额应不大于订单金额");
  856. }
  857. //退款
  858. String outNo = centerRefund(orderRefundReq, orderDon);
  859. BigDecimal orderRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  860. orderDon.setRefundMoney(orderRefundMoney.add(refundMoney));
  861. orderDonMapper.updateById(orderDon);
  862. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  863. GoodsDonSku sku = null;
  864. if (orderDon.getSkuId() != null) {
  865. sku = skuMapper.selectById(orderDon.getSkuId());
  866. }
  867. orderDon.setRefundDesc("补差价");
  868. refundRecord(orderDon, goodsDon, sku, outNo, refundType);
  869. return;
  870. }
  871. BigDecimal refundBalance = refundMoney;
  872. if (refundBalance == null || refundBalance.compareTo(BigDecimal.ZERO) <= 0 || refundBalance.compareTo(orderDon.getMoney()) > 0) {
  873. throw BusinessRuntimeException.getInstance("请输入正确的差价金额");
  874. }
  875. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.price_differ, orderDon.getYhsId());
  876. }
  877. /**
  878. * 寻找该车队空余车位
  879. */
  880. public GroupsRelation getRelationThisTrips(Long userId, Long groupsId, Integer retryNum) {
  881. //寻找快满编车队进行占座
  882. GroupsRelation relation = relationMapper.selectRandomOneRelationByGroupsId(groupsId);
  883. if (relation == null) {
  884. throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  885. }
  886. Long relationId = relation.getId();
  887. if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
  888. if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  889. retryNum++;
  890. getRelationThisTrips(userId, groupsId, retryNum);
  891. }
  892. int count = groupsMapper.decrAvailableNum(relation.getGroupsId());
  893. if (count == 0) {
  894. log.error("车位异常 groupId:{}", groupsId);
  895. groupsMapper.updateAvailableNum(groupsId);
  896. throw new BusinessRuntimeException("车位异常");
  897. }
  898. return relation;
  899. }
  900. private GroupsRelation getChatGPTOutsideRelation(Long userId, Long groupsId, Integer relationNum, Integer retryNum) {
  901. //寻找快满编车队额外座位
  902. GroupsRelation relation = relationMapper.selectOutsideRelationByGroupsId(groupsId, relationNum);
  903. if (relation == null) {
  904. relation = new GroupsRelation();
  905. relation.setStatus(GroupsRelation.Status.outside);
  906. relation.setUserId(userId);
  907. relation.setGroupsId(groupsId);
  908. GroupsRelation maxNumRelation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getGroupsId, groupsId).orderByDesc(GroupsRelation::getNum).last("limit 1"));
  909. relation.setNum(maxNumRelation.getNum() + 1);
  910. relationMapper.insert(relation);
  911. return relation;
  912. }
  913. Long relationId = relation.getId();
  914. if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
  915. if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  916. retryNum++;
  917. getChatGPTOutsideRelation(userId, groupsId, relationNum, retryNum);
  918. }
  919. return relation;
  920. }
  921. public String centerRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
  922. OrderDon.Type type = orderDon.getType();
  923. String refundType = refundReq.getRefundType();
  924. if (type == OrderDon.Type.WeChat && !refundType.equals(OrderDon.Type.BALANCE.getType())) {
  925. return wxRefund(refundReq, orderDon);
  926. }
  927. if (type == OrderDon.Type.ALI_PAY && !refundType.equals(OrderDon.Type.BALANCE.getType())) {
  928. return zfbRefund(refundReq, orderDon);
  929. }
  930. if (type == OrderDon.Type.PAYPAL && !refundType.equals(OrderDon.Type.BALANCE.getType())) {
  931. payPalService.refund(refundReq, orderDon);
  932. }
  933. if (type == OrderDon.Type.STRIPE && !refundType.equals(OrderDon.Type.BALANCE.getType())) {
  934. stripeService.refund(refundReq, orderDon);
  935. }
  936. return StrUtil.EMPTY;
  937. }
  938. }