CmsOrderDonServiceImpl.java 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338
  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.UserPayEquipmentAvailableBenefitsMapper;
  28. import com.cyksj.mapper.channel.UserPayEquipmentReceiveBenefitsRecordMapper;
  29. import com.cyksj.mapper.manage.cms.CmsUserMapper;
  30. import com.cyksj.mapper.manage.distribute.DistributeWaitingSendPointsMapper;
  31. import com.cyksj.mapper.manage.distribute.UserDistributeBusinessOrderDonRecordMapper;
  32. import com.cyksj.mapper.manage.distribute.UserDistributeMapper;
  33. import com.cyksj.mapper.manage.distribute.equipment.EquipmentUserDistributeTransportBenefitsMapper;
  34. import com.cyksj.mapper.manage.distribute.sub.UserDistributeSubMapper;
  35. import com.cyksj.mapper.manage.distribute.sub.UserDistributeSubRewardsMapper;
  36. import com.cyksj.mapper.manage.distribute.sub.UserDistributeSubWaitingMapper;
  37. import com.cyksj.mapper.manage.sys.WorkOrderMapper;
  38. import com.cyksj.mapper.shop.YhShopUserDistributeBusinessOrderDonRecordMapper;
  39. import com.cyksj.mapper.stock.GoodsSkuStockRelateMapper;
  40. import com.cyksj.model.entity.*;
  41. import com.cyksj.model.excel.ExcelOrderDonInfo;
  42. import com.cyksj.model.manage.request.ReqSetLogisticsPost;
  43. import com.cyksj.model.manage.views.GroupsRelationView;
  44. import com.cyksj.model.request.ChangeRelationReq;
  45. import com.cyksj.model.request.ClickOutReq;
  46. import com.cyksj.model.request.OrderBalanceRefundReq;
  47. import com.cyksj.model.request.OrderRefundReq;
  48. import com.cyksj.redis.RedisService;
  49. import com.cyksj.service.coupon.CouponFontService;
  50. import com.cyksj.service.distribute.equipment.EquipmentDistributeService;
  51. import com.cyksj.service.giftcard.GiftCardOrderUseRecordService;
  52. import com.cyksj.service.mange.CmsOrderDonService;
  53. import com.cyksj.service.mange.MirrorUserCleatService;
  54. import com.cyksj.service.mange.stock.GoodsDonStockService;
  55. import com.cyksj.service.market.MarketFrontService;
  56. import com.cyksj.service.order.OrderCommonService;
  57. import com.cyksj.service.order.OrderRefundService;
  58. import com.cyksj.service.order.UserRealOrderBenefitsService;
  59. import com.cyksj.service.relation.GroupRelationClearService;
  60. import com.cyksj.service.relation.GroupRelationFrontService;
  61. import com.cyksj.service.relation.GroupsRelationExpiryRecordService;
  62. import com.cyksj.service.relation.GroupsRelationNetflixService;
  63. import com.cyksj.service.shop.YhShopDistributeService;
  64. import com.cyksj.service.user.UserBenefitsService;
  65. import com.cyksj.service.user.UserBindRelationService;
  66. import com.cyksj.service.wechat.WeChatService;
  67. import com.ejlchina.searcher.BeanSearcher;
  68. import com.ejlchina.searcher.util.MapUtils;
  69. import lombok.RequiredArgsConstructor;
  70. import lombok.extern.slf4j.Slf4j;
  71. import org.springframework.dao.DuplicateKeyException;
  72. import org.springframework.stereotype.Service;
  73. import org.springframework.transaction.annotation.Transactional;
  74. import java.math.BigDecimal;
  75. import java.math.RoundingMode;
  76. import java.util.Date;
  77. import java.util.List;
  78. import java.util.Map;
  79. import java.util.Optional;
  80. import java.util.stream.Collectors;
  81. /**
  82. * @author chan
  83. * @date 2021/10/25 下午10:14
  84. */
  85. @Service
  86. @Slf4j
  87. @RequiredArgsConstructor
  88. public class CmsOrderDonServiceImpl extends ServiceImpl<OrderDonMapper,OrderDon> implements CmsOrderDonService {
  89. private final OrderDonTransportMapper transportMapper;
  90. private final OrderDonWaybillMapper orderDonWaybillMapper;
  91. private final GoodsSkuStockRelateMapper skuStockRelateMapper;
  92. private final GoodsDonStockService goodsDonStockService;
  93. private final GoodsDonSkuMapper goodsDonSkuMapper;
  94. private final UserRealOrderBenefitsService userRealOrderBenefitsService;
  95. private final UserRelationKickOutRecordMapper kickOutRecordMapper;
  96. private final CmsUserMapper cmsUserMapper;
  97. private final OrderCommonService orderCommonService;
  98. private final GoodsDonMapper goodsDonMapper;
  99. private final RedisService redisService;
  100. private final UserBenefitsService userBenefitsService;
  101. private final DistributeWaitingSendPointsMapper distributeWaitingSendPointsMapper;
  102. private final RefundOrderDonMapper refundOrderDonMapper;
  103. private final UserDistributeMapper userDistributeMapper;
  104. private final OrderDonMapper orderDonMapper;
  105. private final MarketFrontService marketFrontService;
  106. private final EquipmentDistributeService equipmentDistributeService;
  107. private final CouponFontService couponFontService;
  108. private final WeChatService weChatService;
  109. private final WeChatConfig weChatConfig;
  110. private final ShopConfigMapper shopConfigMapper;
  111. private final GroupRelationClearService relationClearService;
  112. private final GroupsRelationMapper relationMapper;
  113. private final GroupsMapper groupsMapper;
  114. private final GoodsDonSkuMapper skuMapper;
  115. private final UserDistributeBusinessOrderDonRecordMapper businessOrderDonRecordMapper;
  116. private final WorkOrderMapper workOrderMapper;
  117. private final OrderRefundService orderRefundService;
  118. private final OrderDiscountPlusPurchaseSkuRelationMapper orderDiscountPlusPurchaseSkuRelationMapper;
  119. private final EquipmentUserDistributeTransportBenefitsMapper transportBenefitsMapper;
  120. private final BeanSearcher beanSearcher;
  121. private final UserPayEquipmentReceiveBenefitsRecordMapper receiveBenefitsRecordMapper;
  122. private final GroupsRelationExpiryRecordService groupsRelationExpiryRecordService;
  123. private final GiftCardOrderUseRecordService giftCardOrderUseRecordService;
  124. private final GiftCardUserRecordMapper giftCardUserRecordMapper;
  125. private final YhShopDistributeService yhShopDistributeService;
  126. private final YhShopUserDistributeBusinessOrderDonRecordMapper yhShopBusinessOrderDonRecordMapper;
  127. private final UserPayEquipmentAvailableBenefitsMapper availableBenefitsMapper;
  128. private final GroupRelationFrontService groupRelationFrontService;
  129. private final UserMapper userMapper;
  130. private final ChatgptUserMapper chatgptUserMapper;
  131. private final UserDistributeSubMapper userDistributeSubMapper;
  132. private final UserDistributeSubWaitingMapper subWaitingMapper;
  133. private final UserDistributeSubRewardsMapper userDistributeSubRewardsMapper;
  134. private final UpgradeOrderDonMapper upgradeOrderDonMapper;
  135. private final UpgradePackageMapper upgradePackageMapper;
  136. private final MidjourneyUserMapper midjourneyUserMapper;
  137. private final GroupsRelationMapper groupsRelationMapper;
  138. private final UserBindRelationService userBindRelationService;
  139. private final GroupsRelationNetflixService groupsRelationNetflixService;
  140. private final AccountMapper accountMapper;
  141. private final MirrorUserCleatService mirrorUserCleatService;
  142. private static final GlobalThreadPoolTaskExecutor TASK_POOL = GlobalThreadPoolTaskExecutor.getInstance();
  143. @Override
  144. public List<ExcelOrderDonInfo> exportOrderInfo(Long promotionId, String start, String end) {
  145. return this.getBaseMapper().exportOrderInfo(promotionId,start,end);
  146. }
  147. @Override
  148. public OrderDonTransport getTransport(Long orderId) {
  149. return transportMapper.selectOne(Wrappers.lambdaQuery(OrderDonTransport.class).eq(OrderDonTransport::getOrderId, orderId));
  150. }
  151. @Transactional(rollbackFor = Throwable.class)
  152. @Override
  153. public OrderDonWaybill setWaybill(ReqSetLogisticsPost reqSetLogisticsPost) {
  154. OrderDonWaybill orderDonWaybill = Optional.ofNullable(orderDonWaybillMapper.selectOne(Wrappers.lambdaQuery(OrderDonWaybill.class).eq(OrderDonWaybill::getOrderId, reqSetLogisticsPost.getOrderId()))).orElse(new OrderDonWaybill());
  155. orderDonWaybill.setCodeCn(reqSetLogisticsPost.getCodeCn());
  156. orderDonWaybill.setTrackingNumber(reqSetLogisticsPost.getTrackingNumber());
  157. orderDonWaybill.setOrderId(reqSetLogisticsPost.getOrderId());
  158. orderDonWaybill.setRemark(reqSetLogisticsPost.getRemark());
  159. OrderDon orderDon = getById(orderDonWaybill.getOrderId());
  160. Integer type = Optional.ofNullable(reqSetLogisticsPost.getType()).orElse(0);
  161. //实物发货
  162. if (type == 0 || type == 1) {
  163. if (orderDonWaybill.getId() == null) {
  164. try {
  165. orderDonWaybillMapper.insert(orderDonWaybill);
  166. } catch (DuplicateKeyException e) {
  167. return orderDonWaybill;
  168. }
  169. orderDon.setStatus(OrderDon.Status.transport);
  170. updateById(orderDon);
  171. //库存扣减逻辑
  172. List<GoodsSkuStockRelate> relateList = skuStockRelateMapper.selectList(Wrappers.lambdaQuery(GoodsSkuStockRelate.class).eq(GoodsSkuStockRelate::getSkuId, orderDon.getSkuId()));
  173. if (!relateList.isEmpty()) {
  174. relateList.forEach((relate) -> {
  175. goodsDonStockService.upStockRelate(relate.getStockId(), orderDon.getId(), "transport");
  176. });
  177. }
  178. } else {
  179. if (orderDon.getStatus() == OrderDon.Status.hasPayment) {
  180. orderDon.setStatus(OrderDon.Status.transport);
  181. updateById(orderDon);
  182. }
  183. orderDonWaybillMapper.updateById(orderDonWaybill);
  184. }
  185. //实物分销订单是否存在
  186. DistributeWaitingSendPoints waitingSendPoints = distributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(DistributeWaitingSendPoints.class)
  187. .eq(DistributeWaitingSendPoints::getOrderId, orderDon.getId())
  188. .eq(DistributeWaitingSendPoints::getIsDelivery, false)
  189. .last("limit 1"));
  190. if (waitingSendPoints != null) {
  191. //实物分销订单发货后再 进行提成结算期
  192. waitingSendPoints.setIsDelivery(true);
  193. distributeWaitingSendPointsMapper.updateById(waitingSendPoints);
  194. }
  195. //分销有礼 分销实物是否有发货后用户权益
  196. EquipmentUserDistributeTransportBenefits transportBenefits = transportBenefitsMapper.selectOne(Wrappers.lambdaQuery(EquipmentUserDistributeTransportBenefits.class)
  197. .eq(EquipmentUserDistributeTransportBenefits::getOrderId, orderDon.getId())
  198. .eq(EquipmentUserDistributeTransportBenefits::getStatus, EquipmentUserDistributeTransportBenefits.Status.hasPayment).last("limit 1"));
  199. if (transportBenefits != null) {
  200. if (transportBenefits.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  201. //7天后余额到账
  202. transportBenefitsMapper.update(null, Wrappers.lambdaUpdate(EquipmentUserDistributeTransportBenefits.class)
  203. .set(EquipmentUserDistributeTransportBenefits::getStatus, EquipmentUserDistributeTransportBenefits.Status.transport)
  204. .set(EquipmentUserDistributeTransportBenefits::getSendTime, DateUtil.offsetDay(DateTime.now(), 7))
  205. .eq(EquipmentUserDistributeTransportBenefits::getOrderId, orderDon.getId())
  206. .eq(EquipmentUserDistributeTransportBenefits::getStatus, EquipmentUserDistributeTransportBenefits.Status.hasPayment));
  207. }
  208. }
  209. }
  210. //权益发货
  211. if (type == 0 || type == 2) {
  212. GoodsDonSku sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  213. if (sku != null && sku.getIsBenefits()) {
  214. //是否实物权益已发放
  215. Integer count = receiveBenefitsRecordMapper.selectCount(Wrappers.lambdaQuery(UserPayEquipmentReceiveBenefitsRecord.class)
  216. .eq(UserPayEquipmentReceiveBenefitsRecord::getRealOrderId, orderDon.getId()));
  217. if (count == 0) {
  218. count = availableBenefitsMapper.selectCount(Wrappers.lambdaQuery(UserPayEquipmentAvailableBenefits.class)
  219. .eq(UserPayEquipmentAvailableBenefits::getRealOrderId, orderDon.getId()));
  220. }
  221. if (count == 0) {
  222. //实物权益未发
  223. String benefitsKey = RedisService.key.REAL_GOODS_BENEFITS_KEY.getNameFormat(orderDon.getId());
  224. if (redisService.setNx(benefitsKey, orderDon.getId(), RedisService.key.REAL_GOODS_BENEFITS_KEY.getTimeout())) {
  225. //发放实物购买权益
  226. if (StrUtil.isNotEmpty(sku.getBenefitsList())) {
  227. try {
  228. List<GoodsDonSku> goodsDonSkus = Jsons.parseList(sku.getBenefitsList(), GoodsDonSku.class);
  229. //自购实物 获取权益
  230. userRealOrderBenefitsService.getPayRealGoodsBenefits(orderDon.getUserId(), orderDon.getId(), orderDon.getYhsId(), goodsDonSkus);
  231. } catch (Exception e) {
  232. redisService.del(benefitsKey);
  233. }
  234. }
  235. }
  236. }
  237. }
  238. }
  239. return orderDonWaybill;
  240. }
  241. @Override
  242. public void kickOutRelationId(long adminId, ClickOutReq req) {
  243. Long orderId = req.getOrderId();
  244. OrderDon orderDon = getById(orderId);
  245. if (orderDon != null && !orderDon.getIsKickOut()) {
  246. try {
  247. UserRelationKickOutRecord kickOutRecord = new UserRelationKickOutRecord();
  248. kickOutRecord.setUserId(orderDon.getUserId());
  249. kickOutRecord.setRelationId(orderDon.getRelationId());
  250. kickOutRecord.setGoodsId(orderDon.getGoodsId());
  251. kickOutRecord.setSkuId(orderDon.getSkuId());
  252. kickOutRecord.setReason(req.getReason());
  253. kickOutRecord.setImg(req.getImg());
  254. kickOutRecord.setRemark(req.getRemark());
  255. kickOutRecord.setOrderId(orderDon.getId());
  256. kickOutRecord.setOrderNo(orderDon.getOrderNo());
  257. Optional.ofNullable(cmsUserMapper.selectById(adminId)).ifPresent(cmsUser -> kickOutRecord.setOperator(cmsUser.getNickname()));
  258. kickOutRecordMapper.insert(kickOutRecord);
  259. orderDon.setIsKickOut(true);
  260. updateById(orderDon);
  261. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  262. GoodsDonSku goodsDonSku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  263. //清除车票
  264. orderCommonService.clearUnrealGoodsDetail(orderDon, goodsDon.getType(), goodsDonSku);
  265. } catch (DuplicateKeyException e) {
  266. }
  267. }
  268. }
  269. @Override
  270. @Transactional(rollbackFor = Throwable.class)
  271. public void unifiedRefund(OrderRefundReq refundReq) throws Exception {
  272. OrderDon orderDon = orderDonMapper.selectById(refundReq.getOrderId());
  273. GoodsDonSku sku = null;
  274. if (orderDon.getSkuId() != null) {
  275. sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  276. }
  277. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  278. if (StrUtil.isEmpty(refundReq.getRefundType())) {
  279. refundReq.setRefundType("money");
  280. }
  281. String refundType = refundReq.getRefundType();
  282. //校验订单是否符合退款
  283. checkOrderRefund(orderDon, goodsDon, sku, refundReq);
  284. //空订单关闭
  285. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0 && orderDon.getBalance().compareTo(BigDecimal.ZERO) == 0
  286. && orderDon.getRelationId() == 0) {
  287. orderDon.setStatus(OrderDon.Status.refund);
  288. orderDonMapper.updateById(orderDon);
  289. if (goodsDon.getType() == 2) {
  290. //扣除用户自身实物权益
  291. userRealOrderBenefitsService.deductUserRealGoodsBenefits(orderDon.getId());
  292. }
  293. return;
  294. }
  295. //调用第三方接口退款
  296. String outNo = StrUtil.EMPTY;
  297. if (refundReq.getRefundMoney() != null && refundReq.getRefundMoney().compareTo(BigDecimal.ZERO) > 0) {
  298. outNo = orderRefundService.centerRefund(refundReq, orderDon);
  299. }
  300. orderDon.setRefundDesc(refundReq.getRefundDesc());
  301. //记录退款信息
  302. commonRefund(orderDon, refundReq.getRefundMoney(), refundReq.getOperator(), goodsDon, sku, outNo, refundType, refundReq.getIsOnly(), refundReq.getRefundBalance(), refundReq.getChatImg(), refundReq.getDeductBalance());
  303. //修改订单状态
  304. orderDon.setStatus(OrderDon.Status.refund);
  305. orderDonMapper.updateById(orderDon);
  306. //提交过工单的订单
  307. //将用户异常订单关闭
  308. workOrderMapper.update(null, Wrappers.lambdaUpdate(WorkOrder.class)
  309. .set(WorkOrder::getStatus, WorkOrder.Status.close)
  310. .eq(WorkOrder::getStatus, WorkOrder.Status.waiting)
  311. .eq(WorkOrder::getUserId, orderDon.getUserId())
  312. .eq(WorkOrder::getRelationId, orderDon.getRelationId()));
  313. //将GPT规格的车队 下次可停车时间置空
  314. groupRelationFrontService.setGroupsTripsParkingTimeEmpty(sku, orderDon.getRelationId());
  315. }
  316. @Override
  317. @Transactional(rollbackFor = Throwable.class)
  318. public void unifiedUpgradeRefund(OrderRefundReq refundReq) throws Exception {
  319. UpgradeOrderDon orderDon = upgradeOrderDonMapper.selectById(refundReq.getOrderId());
  320. UpgradePackage upgradePackage = upgradePackageMapper.selectById(orderDon.getPackageId());
  321. if (StrUtil.isEmpty(refundReq.getRefundType())) {
  322. refundReq.setRefundType("money");
  323. }
  324. String refundType = refundReq.getRefundType();
  325. //校验订单是否符合退款
  326. checkUpgradeOrderRefund(orderDon, refundReq);
  327. //空订单关闭
  328. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0 && orderDon.getBalance().compareTo(BigDecimal.ZERO) == 0) {
  329. orderDon.setStatus(UpgradeOrderDon.Status.refund);
  330. upgradeOrderDonMapper.updateById(orderDon);
  331. return;
  332. }
  333. Long userId = orderDon.getUserId();
  334. List<Long> userIdList = null;
  335. //检验gpt套餐
  336. if (upgradePackage.getGoodsId() == 18) {
  337. userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  338. //是否有更高级的套餐
  339. UpgradeOrderDon more = upgradeOrderDonMapper.selectOne(Wrappers.lambdaQuery(UpgradeOrderDon.class)
  340. .in(UpgradeOrderDon::getUserId, userIdList)
  341. .eq(UpgradeOrderDon::getRelationId, orderDon.getRelationId())
  342. .gt(UpgradeOrderDon::getNum, orderDon.getNum())
  343. .eq(UpgradeOrderDon::getStatus, UpgradeOrderDon.Status.complete)
  344. .last("limit 1"));
  345. if (more != null) {
  346. throw BusinessRuntimeException.getInstance("请先退掉其更高级套餐");
  347. }
  348. }
  349. //调用第三方接口退款
  350. String outNo = orderRefundService.centerUpgradeRefund(refundReq, orderDon);
  351. orderDon.setRefundDesc(refundReq.getRefundDesc());
  352. //记录退款信息
  353. commonUpgradeRefund(orderDon, refundReq.getRefundMoney(), refundReq.getOperator(), upgradePackage, outNo, refundType, refundReq.getIsOnly(), refundReq.getRefundBalance(), refundReq.getChatImg());
  354. //修改订单状态
  355. orderDon.setStatus(UpgradeOrderDon.Status.refund);
  356. upgradeOrderDonMapper.updateById(orderDon);
  357. //扣除套餐次数
  358. if (upgradePackage.getGoodsId() == 26) {
  359. MidjourneyUser midjourneyUser = midjourneyUserMapper.selectOne(Wrappers.lambdaQuery(MidjourneyUser.class).eq(MidjourneyUser::getRelationId, orderDon.getRelationId()));
  360. if (midjourneyUser != null) {
  361. int update = midjourneyUserMapper.update(null, Wrappers.lambdaUpdate(MidjourneyUser.class)
  362. .set(MidjourneyUser::getMjFastNum, midjourneyUser.getMjFastNum() < upgradePackage.getNum() ? 0 : midjourneyUser.getMjFastNum() - upgradePackage.getNum())
  363. .eq(MidjourneyUser::getId, midjourneyUser.getId()));
  364. if (update == 0) {
  365. log.info("midjourneyUser 套餐包增值失败 id:{},orderId:{}", midjourneyUser.getId(), orderDon.getId());
  366. }
  367. Long decr = redisService.decr(RedisService.key.MIDJOURNEY_FAST_LIMIT.getName() + midjourneyUser.getId(), upgradePackage.getNum().longValue());
  368. if (decr < 0) {
  369. redisService.set(RedisService.key.MIDJOURNEY_FAST_LIMIT.getName() + midjourneyUser.getId(), 0L);
  370. }
  371. }
  372. }
  373. //扣除gpt套餐升级
  374. if (upgradePackage.getGoodsId() == 18) {
  375. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class).eq(ChatgptUser::getRelationId, orderDon.getRelationId()));
  376. if (chatgptUser != null) {
  377. GroupsRelation relation = groupsRelationMapper.selectById(chatgptUser.getRelationId());
  378. GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
  379. GoodsDonSku sku = skuMapper.selectById(groupsTrips.getSkuId());
  380. //原先sku的套餐
  381. Long gptLimitTime = sku.getGptLimitTime();
  382. Integer gptLimitNum = sku.getGptLimitNum();
  383. //次等套餐的规格
  384. UpgradeOrderDon secondUpgrade = upgradeOrderDonMapper.selectOne(Wrappers.lambdaQuery(UpgradeOrderDon.class)
  385. .in(UpgradeOrderDon::getUserId, userIdList)
  386. .eq(UpgradeOrderDon::getRelationId, orderDon.getRelationId())
  387. .lt(UpgradeOrderDon::getNum, orderDon.getNum())
  388. .eq(UpgradeOrderDon::getStatus, UpgradeOrderDon.Status.complete)
  389. .last("limit 1"));
  390. if (secondUpgrade != null) {
  391. gptLimitTime = secondUpgrade.getTime();
  392. gptLimitNum = secondUpgrade.getNum();
  393. }
  394. Long packageId = 0l;
  395. //降级套餐
  396. if (secondUpgrade != null) {
  397. packageId = secondUpgrade.getPackageId();
  398. }
  399. int update = chatgptUserMapper.update(null, Wrappers.lambdaUpdate(ChatgptUser.class)
  400. .set(ChatgptUser::getLimitTime, gptLimitTime)
  401. .set(ChatgptUser::getLimitNum, gptLimitNum)
  402. .set(ChatgptUser::getPackageId, packageId)
  403. //无次等套餐 不需要清除套餐时间
  404. .set(secondUpgrade == null, ChatgptUser::getClearPackageTime, null)
  405. .eq(ChatgptUser::getId, chatgptUser.getId()));
  406. if (update == 0) {
  407. log.info("chatgptUser 升级套餐包增值失败 id:{},orderId:{}", chatgptUser.getId(), orderDon.getId());
  408. }
  409. }
  410. }
  411. }
  412. /**
  413. * 退款后 处理关联
  414. */
  415. public void commonUpgradeRefund(UpgradeOrderDon orderDon, BigDecimal refundMoney, String operator, UpgradePackage upgradePackage, String outNo, String refundType, Boolean isOnly, BigDecimal refundBalance, String chatImg) {
  416. TASK_POOL.execute(() -> {
  417. orderRefundService.refundUpgradeRecord(orderDon, refundMoney,upgradePackage, operator, outNo, refundType, chatImg);
  418. //退等比例
  419. if (isOnly != null && isOnly) {
  420. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.refund, 0L, orderDon.getId(), upgradePackage.getName()+ UserBalanceSourceRecord.Source.refund.getDesc(), true);
  421. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  422. orderDon.setRefundBalance(orderDonRefundBalance.add(refundBalance));
  423. }
  424. //若存在余额支付,退还余额
  425. if (isOnly == null && orderDon.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  426. userBenefitsService.addUserBalance(orderDon.getUserId(), orderDon.getBalance(), UserBalanceSourceRecord.Source.refund, 0L, orderDon.getId(), upgradePackage.getName() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  427. }
  428. if (UpgradeOrderDon.Type.BALANCE.getType().equals(refundType)) {
  429. if (isOnly == null && orderDon.getMoney().compareTo(BigDecimal.ZERO) > 0) {
  430. userBenefitsService.addUserBalance(orderDon.getUserId(), orderDon.getRefundBalance(), UserBalanceSourceRecord.Source.refund, 0L, orderDon.getId(), upgradePackage.getName() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  431. }
  432. }
  433. });
  434. }
  435. /**
  436. * 校验订单是否符合退款操作
  437. */
  438. private void checkUpgradeOrderRefund(UpgradeOrderDon orderDon, OrderRefundReq refundReq) {
  439. if (orderDon == null) {
  440. throw BusinessRuntimeException.getInstance("订单不存在");
  441. }
  442. BigDecimal orderDonRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  443. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  444. String refundType = refundReq.getRefundType();
  445. if (orderDon.getType() == UpgradeOrderDon.Type.BALANCE && !UpgradeOrderDon.Type.BALANCE.getType().equals(refundType)) {
  446. throw BusinessRuntimeException.getInstance("余额支付的订单不支持金额退款");
  447. }
  448. if (UpgradeOrderDon.Status.refund == orderDon.getStatus()) {
  449. throw BusinessRuntimeException.getInstance("该订单已退款");
  450. }
  451. if (UpgradeOrderDon.Status.noPayment == orderDon.getStatus() || UpgradeOrderDon.Status.close == orderDon.getStatus()) {
  452. throw BusinessRuntimeException.getInstance("订单{0}状态不支持退款", orderDon.getStatus());
  453. }
  454. BigDecimal refundMoney = refundReq.getRefundMoney();
  455. BigDecimal money = orderDon.getMoney();
  456. //余额退款
  457. if (UpgradeOrderDon.Type.BALANCE.getType().equals(refundType)) {
  458. BigDecimal balance = orderDon.getBalance();
  459. refundMoney = orderDonRefundBalance.add(refundMoney);
  460. if (UpgradeOrderDon.Type.BALANCE == orderDon.getType() && refundMoney.compareTo(balance) > 0) {
  461. throw BusinessRuntimeException.getInstance("退款余额大于订单支付余额");
  462. }
  463. if (UpgradeOrderDon.Type.BALANCE != orderDon.getType() && refundMoney.compareTo(money) > 0) {
  464. throw BusinessRuntimeException.getInstance("退款余额大于订单支付金额");
  465. }
  466. orderDon.setRefundBalance(refundMoney);
  467. orderDon.setRefundMoney(BigDecimal.ZERO);
  468. } else {
  469. //退金额
  470. refundMoney = orderDonRefundMoney.add(refundMoney);
  471. if (refundMoney.compareTo(money) > 0) {
  472. throw BusinessRuntimeException.getInstance("退款金额大于订单支付金额");
  473. }
  474. orderDon.setRefundMoney(refundMoney);
  475. }
  476. if (!redisService.setNx(String.format("%s", refundReq.getOrderId()), refundReq.getOrderId(), 10l)) {
  477. throw BusinessRuntimeException.getInstance("请勿重复点击,正在退款中..");
  478. }
  479. }
  480. public String wxRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
  481. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) <=0){
  482. return StrUtil.EMPTY;
  483. }
  484. long time = System.currentTimeMillis();
  485. //退款订单号
  486. String outRefundNo = Codec.DoDigest.custom()
  487. .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
  488. .setStringData(time + String.valueOf(orderDon.getId()))
  489. .toHexString();
  490. weChatService.refundWxOrder(weChatConfig.getAppid(),
  491. Optional.ofNullable(orderDon.getShopId()).orElse(ShopConfig.WX_DEFAULT_APP_ID),
  492. orderDon.getTransactionId(),
  493. outRefundNo,
  494. orderDon.getMoney(),
  495. refundReq.getRefundMoney(),
  496. weChatConfig.getDomain() + "manage/order/wx/refund/notify");
  497. //记录退款信息
  498. return outRefundNo;
  499. }
  500. @Override
  501. public void wxRefundNotify(Map<String, String> map) throws Exception {
  502. // 对退款数据 解密
  503. String md5Key = Codec.DoDigest.custom().setAlgorithm(Codec.DoDigest.Algorithm.MD5).setStringData(shopConfigMapper.getByAppId(map.get("mch_id")).getSecret()).toHexString();
  504. String reqInfoXml = Codec.DoCipher.custom().setAlgorithm(Codec.DoCipher.Trans.AES_ECB_PKCS7Padding).setBase64Data(map.get("req_info")).setStringKey(md5Key).ofDecrypt().toText();
  505. log.info("=== 退款数据解密: \n {}", reqInfoXml);
  506. Map<String, String> reqInfoMap = Xmls.toMap(reqInfoXml);
  507. // 退款失败
  508. if (StrUtil.equals("CHANGE", reqInfoMap.get("refund_status"))) {
  509. throw BusinessRuntimeException.getInstance("退款异常.");
  510. } else if (StrUtil.equals("REFUNDCLOSE", reqInfoMap.get("refund_status"))) {
  511. throw BusinessRuntimeException.getInstance("退款关闭.");
  512. }
  513. /* 此处处理业务逻辑 */
  514. String outRefundNo = reqInfoMap.get("out_refund_no");
  515. String transactionId = reqInfoMap.get("transaction_id");
  516. String refundFee = reqInfoMap.get("refund_fee");
  517. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getTransactionId, transactionId).last("limit 1"));
  518. if (orderDon == null) {
  519. log.error("退款回调,transactionId:{}订单不存在", transactionId);
  520. return;
  521. }
  522. log.info("微信退款: 退款单号[{}] 退款成功.", outRefundNo);
  523. }
  524. @Override
  525. @Transactional(rollbackFor = Throwable.class)
  526. public void changeRelation(ChangeRelationReq req) throws Exception {
  527. Long relationId = req.getRelationId();
  528. Long groupId = req.getGroupsId();
  529. UserTicketClearedRecord.Source source = req.getSource();
  530. if (source == null) source = UserTicketClearedRecord.Source.change_ticket;
  531. GroupsRelation relation = relationMapper.selectById(relationId);
  532. Long yhsId = relation.getYhsId();
  533. Assert.notNull(relation, "车票已不存在");
  534. if (relation.getRechargeStatus() != null) {
  535. throw BusinessRuntimeException.getInstance("代充账号车票无法更换车票");
  536. }
  537. Long userId = relation.getUserId();
  538. log.info("用户userId:{}更换车票relationId:{}", userId, relationId);
  539. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  540. .eq(OrderDon::getUserId, userId)
  541. .eq(OrderDon::getRelationId, relationId)
  542. .notIn(OrderDon::getStatus, Constant.noOrderStatus)
  543. .orderByDesc(OrderDon::getId)
  544. .last("limit 1"));
  545. OrderDiscountPlusPurchaseSkuRelation plusPurchaseSkuRelation = null;
  546. List<Long> plus_relationList = null;
  547. if (orderDon == null) {
  548. List<OrderDiscountPlusPurchaseSkuRelation> plusPurchaseSkuRelations = orderDiscountPlusPurchaseSkuRelationMapper.selectPlusRelationByIdAndUserId(relation.getId(), relation.getUserId());
  549. for (OrderDiscountPlusPurchaseSkuRelation data : plusPurchaseSkuRelations) {
  550. String relationIds = data.getRelationIds();
  551. if (StrUtil.isEmpty(relationIds)) {
  552. return;
  553. }
  554. List<Long> relationList = Jsons.parseList(relationIds, Long.class);
  555. if (relationList.contains(relationId)) {
  556. plusPurchaseSkuRelation = data;
  557. break;
  558. }
  559. }
  560. if (plusPurchaseSkuRelation != null) {
  561. String relationIds = plusPurchaseSkuRelation.getRelationIds();
  562. if (StrUtil.isNotEmpty(relationIds)) {
  563. plus_relationList = Jsons.parseList(relationIds, Long.class);
  564. if (plus_relationList.contains(relationId)) {
  565. orderDon = new OrderDon();
  566. GroupsRelationView groupsRelationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder().field(GroupsRelationView::getId, relationId).build());
  567. Assert.notNull(groupsRelationView, "车票已不存在");
  568. orderDon.setUserId(groupsRelationView.getUserId());
  569. orderDon.setSkuId(groupsRelationView.getSkuId());
  570. orderDon.setGoodsId(groupsRelationView.getGoodsId());
  571. orderDon.setStatus(OrderDon.Status.complete);
  572. orderDon.setOrderType(1);
  573. }
  574. }
  575. }
  576. }
  577. Assert.notNull(orderDon, "订单不存在");
  578. if (orderDon.getStatus() == OrderDon.Status.refund) {
  579. throw BusinessRuntimeException.getInstance("订单已退款");
  580. }
  581. //获取新车队
  582. LambdaQueryWrapper<GroupsTrips> queryWrapper = Wrappers.lambdaQuery(GroupsTrips.class)
  583. .eq(GroupsTrips::getSkuId, orderDon.getSkuId())
  584. .eq(GroupsTrips::getId, groupId)
  585. .ne(GroupsTrips::getId, relation.getGroupsId())
  586. .ne(GroupsTrips::getStatus, GroupsTrips.Status.down)
  587. .last("limit 1");
  588. GroupsTrips groups = groupsMapper.selectOne(queryWrapper);
  589. if (groups == null) throw BusinessRuntimeException.getInstance("车队不存在或已下架");
  590. if (!Constant.AI_goodsIds.contains(orderDon.getGoodsId()) && groups.getAvailableNum() <= 0) {
  591. throw BusinessRuntimeException.getInstance("该新车位人员已满");
  592. }
  593. Integer relationNum = groups.getNum();
  594. //获取新车队车位
  595. GroupsRelation newRelation;
  596. Boolean isOutside = req.getIsOutside();
  597. if (Constant.AI_goodsIds.contains(orderDon.getGoodsId()) && ((isOutside != null && isOutside) || groups.getAvailableNum() == 0) && groups.getNum() > 1) {
  598. //Ai车队 额外增加车位 并不让上车
  599. newRelation = getChatGPTOutsideRelation(orderDon.getUserId(), groupId, relationNum, 1);
  600. } else {
  601. newRelation = getRelationThisTrips(orderDon.getUserId(), groupId, 1);
  602. }
  603. newRelation.setUserId(userId);
  604. newRelation.setStartTime(relation.getStartTime());
  605. newRelation.setExpiryTime(relation.getExpiryTime());
  606. newRelation.setYhsId(yhsId);
  607. newRelation.setCustomerService(relation.getCustomerService());
  608. if (newRelation.getStatus() != GroupsRelation.Status.outside) {
  609. newRelation.setStatus(GroupsRelation.Status.validity);
  610. }
  611. //清除原先车票
  612. relation.setNewRelationId(newRelation.getId());
  613. relationClearService.clearTicket(relation, source);
  614. //奈飞车票
  615. if (orderDon.getGoodsId() == 1) {
  616. User user = userMapper.selectById(newRelation.getUserId());
  617. GroupsTrips groupsTrips = groupsMapper.selectById(newRelation.getGroupsId());
  618. Account account = accountMapper.selectById(groupsTrips.getAccountId());
  619. groupsRelationNetflixService.timingSetNetflix(newRelation.getNum(), user.getNickname(), account.getAccount(), account.getPassword(), newRelation.getExpiryTime());
  620. }
  621. if (plusPurchaseSkuRelation != null && plus_relationList != null) {
  622. plus_relationList.remove(relationId);
  623. plus_relationList.add(newRelation.getId());
  624. plusPurchaseSkuRelation.setRelationIds(plus_relationList.toString());
  625. orderDiscountPlusPurchaseSkuRelationMapper.updateById(plusPurchaseSkuRelation);
  626. }
  627. if (source != null && source == UserTicketClearedRecord.Source.abnormal) {
  628. //将用户异常订单关闭
  629. workOrderMapper.update(null, Wrappers.lambdaUpdate(WorkOrder.class)
  630. .set(WorkOrder::getStatus, WorkOrder.Status.close)
  631. .eq(WorkOrder::getStatus, WorkOrder.Status.waiting)
  632. .eq(WorkOrder::getUserId, userId)
  633. .eq(WorkOrder::getRelationId, relationId));
  634. }
  635. if (orderDon.getMoney() != null && orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  636. //是否是实物权益车票
  637. UserPayEquipmentReceiveBenefitsRecord receiveBenefitsRecord = receiveBenefitsRecordMapper.selectOne(Wrappers.lambdaQuery(UserPayEquipmentReceiveBenefitsRecord.class)
  638. .eq(UserPayEquipmentReceiveBenefitsRecord::getTicketOrderId, orderDon.getId())
  639. .eq(UserPayEquipmentReceiveBenefitsRecord::getRelationId, relationId).last("limit 1"));
  640. if (receiveBenefitsRecord != null) {
  641. receiveBenefitsRecord.setRelationId(newRelation.getId());
  642. receiveBenefitsRecordMapper.updateById(receiveBenefitsRecord);
  643. }
  644. }
  645. if ((newRelation.getStartTime() == null || newRelation.getExpiryTime() == null)) {
  646. List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.hasPayment));
  647. if (orderDonList.isEmpty()) {
  648. orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class)
  649. .eq(OrderDon::getUserId, userId)
  650. .eq(OrderDon::getRelationId, relationId)
  651. .eq(OrderDon::getStatus, OrderDon.Status.complete)
  652. .orderByDesc(OrderDon::getId)
  653. .last("limit 1"));
  654. }
  655. if (groups.getStatus() == GroupsTrips.Status.waiting) {
  656. orderDonList.forEach(hasPaymentOrder -> {
  657. hasPaymentOrder.setRelationId(newRelation.getId());
  658. orderDonMapper.updateById(hasPaymentOrder);
  659. });
  660. relationMapper.updateById(newRelation);
  661. return;
  662. }
  663. orderDonList.forEach((hasPaymentOrder) -> {
  664. //如果续费增加时间,如果首次则设置当前时间为初始时间
  665. Date expiryTime = Optional.ofNullable(newRelation.getExpiryTime()).orElse(new Date());
  666. GoodsDonSku donSku = skuMapper.selectById(hasPaymentOrder.getSkuId());
  667. Date newDate;
  668. if (donSku.getDays() != null && donSku.getDays() > 0) {
  669. newDate = DateUtil.offsetDay(expiryTime, donSku.getDays() * hasPaymentOrder.getNum());
  670. } else {
  671. newDate = DateUtil.offset(expiryTime, DateField.MONTH, donSku.getMonths() * hasPaymentOrder.getNum());
  672. }
  673. newRelation.setExpiryTime(newDate);
  674. newRelation.setStartTime(newRelation.getStartTime() == null ? new Date() : null);
  675. relationMapper.updateById(newRelation);
  676. hasPaymentOrder.setStatus(OrderDon.Status.complete);
  677. hasPaymentOrder.setRelationId(newRelation.getId());
  678. orderDonMapper.updateById(hasPaymentOrder);
  679. });
  680. return;
  681. }
  682. List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.complete));
  683. orderDonList.forEach(completeOrder->{
  684. completeOrder.setRelationId(newRelation.getId());
  685. orderDonMapper.updateById(completeOrder);
  686. });
  687. log.info("userId:{}更换车票,原座位号relationId:{}======>新座位号newRelationId:{}", newRelation.getUserId(), relationId, newRelation.getId());
  688. relationMapper.updateById(newRelation);
  689. //更换车票 调整GPT相关规格新车队 上车数
  690. GoodsDonSku sku = goodsDonSkuMapper.selectById(groups.getSkuId());
  691. groupRelationFrontService.adjustGroupsParkingTime(newRelation.getId(), sku);
  692. }
  693. public String zfbRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
  694. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) <=0){
  695. return StrUtil.EMPTY;
  696. }
  697. AlipayTradeRefundResponse response;
  698. //支付宝退款
  699. AlipayClient alipayClient = AliPayClientFactory.getAlipayClient(Optional.ofNullable(orderDon.getShopId()).orElse(ShopConfig.ZFB_DEFAULT_APP_ID));
  700. AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
  701. AlipayTradeRefundModel model = new AlipayTradeRefundModel();
  702. //支付宝交易号
  703. model.setTradeNo(orderDon.getTransactionId());
  704. model.setRefundAmount(refundReq.getRefundMoney().divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_EVEN).toString());
  705. model.setQueryOptions(List.of("gmt_refund_pay"));
  706. long time = System.currentTimeMillis();
  707. //退款订单号
  708. String outRefundNo = Codec.DoDigest.custom()
  709. .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
  710. .setStringData(time + String.valueOf(orderDon.getId()))
  711. .toHexString();
  712. //退款请求号
  713. model.setOutRequestNo(outRefundNo);
  714. request.setBizModel(model);
  715. String shopId = orderDon.getShopId();
  716. ShopConfig shopConfig = shopConfigMapper.selectOne(Wrappers.lambdaQuery(ShopConfig.class).eq(ShopConfig::getAppId, orderDon.getShopId()));
  717. if (shopId != null && shopConfig != null && shopConfig.getIsCert()) {
  718. response = alipayClient.certificateExecute(request);
  719. } else {
  720. response = alipayClient.execute(request);
  721. }
  722. if (!response.isSuccess()) throw BusinessRuntimeException.getInstance("退款失败,e:{0}", response.getSubMsg());
  723. // AliPayRefundRep aliPayRefundRep = Jsons.parseObject(response.getBody(), AliPayRefundRep.class);
  724. // AliPayRefundRep.AlipayTradeRefundResponse res = aliPayRefundRep.getResponse();
  725. // orderDon.setRefundMoney(res.getRefundFee().multiply(BigDecimal.valueOf(100)));
  726. return outRefundNo;
  727. }
  728. /**
  729. * 校验订单是否符合退款操作
  730. */
  731. private void checkOrderRefund(OrderDon orderDon, GoodsDon goodsDon, GoodsDonSku sku, OrderRefundReq refundReq) {
  732. if (orderDon == null) {
  733. throw BusinessRuntimeException.getInstance("订单不存在");
  734. }
  735. BigDecimal orderDonRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  736. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  737. String refundType = refundReq.getRefundType();
  738. if (orderDon.getType() == OrderDon.Type.BALANCE && !OrderDon.Type.BALANCE.getType().equals(refundType)) {
  739. throw BusinessRuntimeException.getInstance("余额支付的订单不支持金额退款");
  740. }
  741. if (OrderDon.Status.refund == orderDon.getStatus()) {
  742. throw BusinessRuntimeException.getInstance("该订单已退款");
  743. }
  744. if (OrderDon.Status.noPayment == orderDon.getStatus() || OrderDon.Status.close == orderDon.getStatus()) {
  745. throw BusinessRuntimeException.getInstance("订单{0}状态不支持退款", orderDon.getStatus());
  746. }
  747. if (goodsDon.getType() == 1 && sku != null) {
  748. //虚拟原订单是否已过期
  749. Integer months = sku.getMonths();
  750. Integer days = sku.getDays();
  751. Integer num = orderDon.getNum();
  752. DateTime now = DateTime.now();
  753. DateTime endTime;
  754. if (days != null && days > 0) {
  755. endTime = DateUtil.offsetDay(orderDon.getCreatedTime(), days * num);
  756. } else {
  757. endTime = DateUtil.offsetMonth(orderDon.getCreatedTime(), months * num);
  758. }
  759. if (now.isAfter(endTime)) {
  760. throw BusinessRuntimeException.getInstance("该订单车票已过期");
  761. }
  762. if (orderDon.getOrderType() == 1) {
  763. //是否有其他付款订单是否过期
  764. OrderDon otherOrder = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  765. .eq(OrderDon::getRelationId, orderDon.getRelationId())
  766. .eq(OrderDon::getUserId, orderDon.getUserId())
  767. .ne(OrderDon::getId, orderDon.getId())
  768. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  769. .eq(OrderDon::getOrderType, 2)
  770. .orderByDesc(OrderDon::getId)
  771. .last("limit 1"));
  772. if (otherOrder != null) {
  773. throw BusinessRuntimeException.getInstance("该笔订单存在续费订单,请先退掉续费订单");
  774. }
  775. }
  776. }
  777. BigDecimal refundMoney = refundReq.getRefundMoney();
  778. BigDecimal money = orderDon.getMoney();
  779. //余额退款
  780. if (OrderDon.Type.BALANCE.getType().equals(refundType)) {
  781. BigDecimal balance = orderDon.getBalance();
  782. refundMoney = orderDonRefundBalance.add(refundMoney);
  783. if (OrderDon.Type.BALANCE == orderDon.getType() && refundMoney.compareTo(balance) > 0) {
  784. throw BusinessRuntimeException.getInstance("退款余额大于订单支付余额");
  785. }
  786. if (OrderDon.Type.BALANCE != orderDon.getType() && refundMoney.compareTo(money) > 0) {
  787. throw BusinessRuntimeException.getInstance("退款余额大于订单支付金额");
  788. }
  789. orderDon.setRefundBalance(refundMoney);
  790. orderDon.setRefundMoney(BigDecimal.ZERO);
  791. } else {
  792. //退金额
  793. refundMoney = orderDonRefundMoney.add(refundMoney);
  794. if (refundMoney.compareTo(money) > 0) {
  795. throw BusinessRuntimeException.getInstance("退款金额大于订单支付金额");
  796. }
  797. orderDon.setRefundMoney(refundMoney);
  798. }
  799. //礼品卡是否已使用
  800. GiftCardUserRecord giftCardUserRecord = null;
  801. if (goodsDon.getSpecialType() != null && goodsDon.getSpecialType() == GoodsDon.SpecialType.giftCard) {
  802. giftCardUserRecord = giftCardUserRecordMapper.selectOne(Wrappers.lambdaQuery(GiftCardUserRecord.class)
  803. .eq(GiftCardUserRecord::getOrderId, orderDon.getId()).last("limit 1"));
  804. if (giftCardUserRecord != null && giftCardUserRecord.getIsUsed()) {
  805. throw BusinessRuntimeException.getInstance("该礼品卡已使用无法退款");
  806. }
  807. }
  808. if (!redisService.setNx(String.format("%s", refundReq.getOrderId()), refundReq.getOrderId(), 10l)) {
  809. throw BusinessRuntimeException.getInstance("请勿重复点击,正在退款中..");
  810. }
  811. //礼品卡购买状态
  812. if (giftCardUserRecord != null) {
  813. giftCardUserRecord.setIsPay(false);
  814. giftCardUserRecordMapper.updateById(giftCardUserRecord);
  815. }
  816. }
  817. /**
  818. * 退款后 处理关联
  819. */
  820. public void commonRefund(OrderDon orderDon, BigDecimal refundMoney, String operator, GoodsDon goodsDon, GoodsDonSku sku, String outNo, String refundType, Boolean isOnly, BigDecimal refundBalance, String chatImg, BigDecimal deductBalance) {
  821. TASK_POOL.execute(() -> {
  822. orderRefundService.refundRecord(orderDon, refundMoney, operator, goodsDon, sku, outNo, refundType, chatImg);
  823. //退款一次
  824. goodsDonStockService.upStockRelate(null, orderDon.getId(), "refund");
  825. try {
  826. //虚物订单退款,清出车队,车票变为已过期
  827. orderCommonService.clearUnrealGoodsDetail(orderDon, goodsDon.getType(), sku);
  828. } catch (Exception e) {
  829. log.error("清除车票错误:{}", StringUtil.getErrorText(e));
  830. }
  831. //若存在优惠券使用,退还优惠券
  832. if (orderDon.getCouponUserId() != 0) {
  833. couponFontService.updateOrderDonCouponStatus(orderDon);
  834. }
  835. //退等比例
  836. if (isOnly != null && isOnly) {
  837. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.refund, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  838. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  839. orderDon.setRefundBalance(orderDonRefundBalance.add(refundBalance));
  840. }
  841. //若存在余额支付,退还余额
  842. if (isOnly == null && orderDon.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  843. BigDecimal addBalance = orderDon.getBalance();
  844. //需额外扣除余额
  845. if (deductBalance != null && deductBalance.compareTo(BigDecimal.ZERO) > 0) {
  846. addBalance = addBalance.subtract(deductBalance);
  847. }
  848. userBenefitsService.addUserBalance(orderDon.getUserId(), addBalance, UserBalanceSourceRecord.Source.refund, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  849. }
  850. try {
  851. marketFrontService.subSpecificChanceNum(orderDon.getUserId(), orderDon.getId(), orderDon.getGoodsId(), orderDon.getUpdateTime());
  852. if (goodsDon.getType() == 2 && !orderDon.getIsDistribute()) {
  853. equipmentDistributeService.subDistributeBenefitsChance(orderDon.getUserId(), orderDon.getId());
  854. //扣除用户自身实物权益
  855. userRealOrderBenefitsService.deductUserRealGoodsBenefits(orderDon.getId());
  856. }
  857. } catch (Exception e) {
  858. log.error("wx减少抽奖机会错误,orderId:{},error:{}", orderDon.getId(), e);
  859. }
  860. if (OrderDon.Type.BALANCE.getType().equals(refundType)) {
  861. if (isOnly == null && orderDon.getMoney().compareTo(BigDecimal.ZERO) > 0) {
  862. userBenefitsService.addUserBalance(orderDon.getUserId(), orderDon.getRefundBalance(), UserBalanceSourceRecord.Source.refund, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  863. }
  864. } else {
  865. //余额退款不需要扣除积分
  866. //分销提成积分扣除
  867. deductDsPoints(orderDon);
  868. //店铺 分销提成金额扣除
  869. yhShopDistributeService.deductDsMoney(orderDon);
  870. }
  871. if (orderDon.getIsFixedDistribute()) {
  872. //商务提成 因订单退款去掉
  873. UserDistributeBusinessOrderDonRecord record = businessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(UserDistributeBusinessOrderDonRecord.class)
  874. .eq(UserDistributeBusinessOrderDonRecord::getOrderId, orderDon.getId())
  875. .eq(UserDistributeBusinessOrderDonRecord::getStatus, UserDistributeBusinessOrderDonRecord.Status.success)
  876. .last("limit 1"));
  877. if (record != null) {
  878. record.setStatus(UserDistributeBusinessOrderDonRecord.Status.refund);
  879. businessOrderDonRecordMapper.updateById(record);
  880. }
  881. }
  882. //店铺商务提成
  883. if (orderDon.getYhsId() != null && orderDon.getYhsId() > 0) {
  884. YhShopUserDistributeBusinessOrderDonRecord shop_record = yhShopBusinessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(YhShopUserDistributeBusinessOrderDonRecord.class)
  885. .eq(YhShopUserDistributeBusinessOrderDonRecord::getOrderId, orderDon.getId())
  886. .eq(YhShopUserDistributeBusinessOrderDonRecord::getStatus, YhShopUserDistributeBusinessOrderDonRecord.Status.success)
  887. .last("limit 1"));
  888. if (shop_record != null) {
  889. shop_record.setStatus(YhShopUserDistributeBusinessOrderDonRecord.Status.refund);
  890. yhShopBusinessOrderDonRecordMapper.updateById(shop_record);
  891. }
  892. }
  893. //是否是优惠加购关联订单
  894. if (orderDon.getIsDp()) {
  895. OrderDiscountPlusPurchaseSkuRelation discountPlusPurchaseSkuRelation = orderDiscountPlusPurchaseSkuRelationMapper.selectOne(Wrappers.lambdaQuery(OrderDiscountPlusPurchaseSkuRelation.class)
  896. .eq(OrderDiscountPlusPurchaseSkuRelation::getOrderId, orderDon.getId()).last("limit 1"));
  897. if (discountPlusPurchaseSkuRelation != null) {
  898. String relationIdsStr = discountPlusPurchaseSkuRelation.getRelationIds();
  899. if (StrUtil.isNotBlank(relationIdsStr)) {
  900. try {
  901. List<Long> relationIds = Jsons.parseList(relationIdsStr, Long.class);
  902. List<GroupsRelation> groupsRelations = relationMapper.selectList(Wrappers.lambdaQuery(GroupsRelation.class)
  903. .in(GroupsRelation::getId, relationIds));
  904. log.info("优惠加购订单orderId:{}退款,清除相关车票relation_ids:{}", orderDon.getId(), relationIds);
  905. groupsRelations.forEach(relation -> relationClearService.clearTicket(relation, UserTicketClearedRecord.Source.dp));
  906. } catch (Exception e) {
  907. }
  908. }
  909. String plusOrderIds = discountPlusPurchaseSkuRelation.getPlusOrderIds();
  910. if (StrUtil.isNotBlank(plusOrderIds)) {
  911. try {
  912. log.info("关闭优惠加购orderId:{}关联实物订单", orderDon.getId());
  913. List<Long> plusOrderIdList = Jsons.parseList(plusOrderIds, Long.class);
  914. List<OrderDon> relate_orderDons = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class)
  915. .in(OrderDon::getId, plusOrderIdList)
  916. .notIn(OrderDon::getStatus, Constant.noOrderStatus));
  917. relate_orderDons.forEach(relate_o -> {
  918. //扣除用户自身实物权益
  919. userRealOrderBenefitsService.deductUserRealGoodsBenefits(relate_o.getId());
  920. });
  921. orderDonMapper.update(null, Wrappers.lambdaUpdate(OrderDon.class)
  922. .set(OrderDon::getStatus, OrderDon.Status.refund)
  923. .in(OrderDon::getId, plusOrderIdList)
  924. .ne(OrderDon::getStatus, OrderDon.Status.refund));
  925. } catch (Exception e) {
  926. }
  927. }
  928. }
  929. }
  930. //同步车票退款 重购记录
  931. TASK_POOL.execute(() -> {
  932. GroupsRelationExpiryRecord groupsRelationExpiryRecord = groupsRelationExpiryRecordService.getOne(Wrappers.lambdaQuery(GroupsRelationExpiryRecord.class)
  933. .in(GroupsRelationExpiryRecord::getReBuyOrderId, orderDon.getId())
  934. .eq(GroupsRelationExpiryRecord::getRelationId, orderDon.getRelationId()).last("limit 1"));
  935. if (groupsRelationExpiryRecord == null) {
  936. log.info("订单orderId:{}退款,同步是否有重购记录不是直接续费车票", orderDon.getId());
  937. List<GroupsRelationExpiryRecord> groupsRelationExpiryRecords = groupsRelationExpiryRecordService.list(Wrappers.lambdaQuery(GroupsRelationExpiryRecord.class)
  938. .in(GroupsRelationExpiryRecord::getReBuyOrderId, orderDon.getId()));
  939. log.info("订单orderId:{}退款,重购记录不是直接续费车票大小:{}", groupsRelationExpiryRecords.size());
  940. if (CollUtil.isNotEmpty(groupsRelationExpiryRecords)) {
  941. groupsRelationExpiryRecords.forEach(data -> {
  942. data.setIsReBuy(false);
  943. });
  944. groupsRelationExpiryRecordService.saveOrUpdateBatch(groupsRelationExpiryRecords);
  945. }
  946. }
  947. if (groupsRelationExpiryRecord != null) {
  948. groupsRelationExpiryRecord.setIsReBuy(false);
  949. groupsRelationExpiryRecordService.saveOrUpdate(groupsRelationExpiryRecord);
  950. }
  951. });
  952. //是否是礼品卡 现金支付订单
  953. BigDecimal gcCash = orderDon.getGcCash();
  954. if (gcCash != null && gcCash.compareTo(BigDecimal.ZERO) > 0) {
  955. giftCardOrderUseRecordService.returnGiftCardCash(orderDon.getId());
  956. }
  957. //是否是GPT镜像规格
  958. if (orderDon.getOrderType() == 1) {
  959. mirrorUserCleatService.delMirrorUser(orderDon.getGoodsId(), orderDon.getRelationId());
  960. }
  961. //是否是分销订单
  962. //处理下级渠道分销提成
  963. handleSubRewards(orderDon);
  964. });
  965. }
  966. //处理下级渠道分销提成
  967. public void handleSubRewards(OrderDon orderDon) {
  968. //是否是分销订单
  969. //处理下级渠道分销提成
  970. if (orderDon.getIsDistribute()) {
  971. UserDistributeSub subRelate = userDistributeSubMapper.getSubRelate(orderDon.getUserId());
  972. if (subRelate != null) {
  973. List<UserDistributeSubWaiting> subWaitings = subWaitingMapper.selectList(Wrappers.lambdaQuery(UserDistributeSubWaiting.class)
  974. .eq(UserDistributeSubWaiting::getSubUserId, subRelate.getSubUserId())
  975. .eq(UserDistributeSubWaiting::getSendStatus, UserDistributeSubWaiting.Status.waiting));
  976. if (CollUtil.isNotEmpty(subWaitings)) {
  977. List<UserDistributeSubRewards> userDistributeSubRewards = userDistributeSubRewardsMapper.selectList(null);
  978. Map<Integer, List<UserDistributeSubRewards>> rewardLevelMap = userDistributeSubRewards.stream().collect(Collectors.groupingBy(UserDistributeSubRewards::getLevel));
  979. subWaitings.forEach(wait -> {
  980. List<UserDistributeSubRewards> thisLevelList = rewardLevelMap.get(wait.getLevel());
  981. if (thisLevelList == null) {
  982. return;
  983. }
  984. UserDistributeSubRewards thisLevel = thisLevelList.get(0);
  985. Integer months = thisLevel.getMonths();
  986. BigDecimal subOrderMoney = Optional.ofNullable(orderDonMapper.selectSubChannelOrderMoney(wait.getSubUserId(), subRelate.getCreatedTime(), DateUtil.offsetMonth(subRelate.getCreatedTime(), months))).orElse(BigDecimal.ZERO);
  987. if (subOrderMoney.compareTo(thisLevel.getTargetAmount()) < 0) {
  988. subWaitingMapper.update(null, Wrappers.lambdaUpdate(UserDistributeSubWaiting.class)
  989. .set(UserDistributeSubWaiting::getSendStatus, UserDistributeSubWaiting.Status.close)
  990. .eq(UserDistributeSubWaiting::getSendStatus, UserDistributeSubWaiting.Status.waiting)
  991. .eq(UserDistributeSubWaiting::getId, wait.getId()));
  992. }
  993. });
  994. }
  995. }
  996. }
  997. }
  998. /**
  999. * 退款 分销提成积分扣除
  1000. */
  1001. public void deductDsPoints(OrderDon orderDon) {
  1002. if (orderDon.getIsDistribute()) {
  1003. DistributeWaitingSendPoints distributeWaitingSendPoints = distributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(DistributeWaitingSendPoints.class).eq(DistributeWaitingSendPoints::getOrderId, orderDon.getId()).last("limit 1"));
  1004. if (distributeWaitingSendPoints != null) {
  1005. BigDecimal money = orderDon.getMoney();
  1006. BigDecimal refundMoney = orderDon.getRefundMoney();
  1007. //已发送 发送中 部分 全额退款
  1008. DistributeWaitingSendPoints.Status sendStatus = distributeWaitingSendPoints.getSendStatus();
  1009. BigDecimal points = distributeWaitingSendPoints.getPoints();
  1010. if (sendStatus == DistributeWaitingSendPoints.Status.waiting) {
  1011. //实物设备退款就清0
  1012. if (refundMoney.compareTo(money) == 0 || orderDon.getGoodsId() == 15) {
  1013. //待发送状态 全额退款
  1014. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  1015. distributeWaitingSendPoints.setRefundPoints(points);
  1016. distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
  1017. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1018. return;
  1019. }
  1020. Integer thisGoodsRate = distributeWaitingSendPoints.getRate();
  1021. if (thisGoodsRate == null || thisGoodsRate == 0) {
  1022. thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
  1023. }
  1024. if (thisGoodsRate > 0) {
  1025. BigDecimal refundRate = refundMoney.divide(money, 2, RoundingMode.DOWN);
  1026. //退掉比例的提成
  1027. BigDecimal needSubPoints = points.multiply(refundRate);
  1028. distributeWaitingSendPoints.setRefundPoints(needSubPoints);
  1029. //剩余积分
  1030. BigDecimal remainPoints = points.subtract(needSubPoints);
  1031. distributeWaitingSendPoints.setPoints(remainPoints);
  1032. //原先获取积分也扣除
  1033. if (distributeWaitingSendPoints.getOriPoints().compareTo(BigDecimal.ZERO) > 0) {
  1034. BigDecimal oriNeedSubPoints = distributeWaitingSendPoints.getOriPoints().multiply(refundRate);
  1035. distributeWaitingSendPoints.setOriPoints(distributeWaitingSendPoints.getOriPoints().subtract(oriNeedSubPoints));
  1036. }
  1037. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1038. }
  1039. } else if (sendStatus == DistributeWaitingSendPoints.Status.success) {
  1040. //已发送的提成 部分退款 全额退款 需要扣除用户积分
  1041. //扣除固定推广者积分
  1042. //实物设备退款就清0
  1043. if (refundMoney.compareTo(money) == 0 || orderDon.getGoodsId() == 15) {
  1044. userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), points);
  1045. distributeWaitingSendPoints.setRefundPoints(points);
  1046. distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
  1047. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  1048. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1049. return;
  1050. }
  1051. Integer thisGoodsRate = distributeWaitingSendPoints.getRate();
  1052. if (thisGoodsRate == null || thisGoodsRate == 0) {
  1053. thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
  1054. }
  1055. if (thisGoodsRate > 0) {
  1056. BigDecimal refundRate = refundMoney.divide(money, 2, RoundingMode.DOWN);
  1057. //退掉比例的提成
  1058. BigDecimal needSubPoints = points.multiply(refundRate);
  1059. userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), needSubPoints);
  1060. //部分退款
  1061. distributeWaitingSendPoints.setRefundPoints(needSubPoints);
  1062. distributeWaitingSendPoints.setPoints(points.subtract(needSubPoints));
  1063. //原先获取积分也扣除
  1064. if (distributeWaitingSendPoints.getOriPoints().compareTo(BigDecimal.ZERO) > 0) {
  1065. BigDecimal oriNeedSubPoints = distributeWaitingSendPoints.getOriPoints().multiply(refundRate);
  1066. distributeWaitingSendPoints.setOriPoints(distributeWaitingSendPoints.getOriPoints().subtract(oriNeedSubPoints));
  1067. }
  1068. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1069. }
  1070. }
  1071. }
  1072. }
  1073. }
  1074. @Override
  1075. public void refundPriceDiffer(OrderRefundReq orderRefundReq) throws Exception {
  1076. Long orderId = orderRefundReq.getOrderId();
  1077. OrderDon orderDon = orderDonMapper.selectById(orderId);
  1078. if (orderDon == null) {
  1079. throw BusinessRuntimeException.getInstance("订单不存在");
  1080. }
  1081. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  1082. throw BusinessRuntimeException.getInstance("该订单是0元订单,无法补差价");
  1083. }
  1084. if (Constant.noOrderAllStatus.contains(orderDon.getStatus().name())) {
  1085. throw BusinessRuntimeException.getInstance("订单不是已支付状态");
  1086. }
  1087. //默认补差价余额
  1088. String refundType = Optional.ofNullable(orderRefundReq.getRefundType()).orElse("balance");
  1089. BigDecimal refundMoney = orderRefundReq.getRefundMoney();
  1090. BigDecimal orderRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  1091. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  1092. if (refundMoney.add(orderRefundMoney).add(orderDonRefundBalance).compareTo(orderDon.getRealMoney()) >= 0) {
  1093. throw BusinessRuntimeException.getInstance("补差价已达到该订单付款金额");
  1094. }
  1095. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  1096. GoodsDonSku sku = null;
  1097. if (orderDon.getSkuId() != null) {
  1098. sku = skuMapper.selectById(orderDon.getSkuId());
  1099. }
  1100. orderDon.setRefundDesc("补差价");
  1101. String outNo = StrUtil.EMPTY;
  1102. if ("money".equals(refundType)) {
  1103. if (refundMoney == null || refundMoney.compareTo(BigDecimal.ZERO) <= 0) {
  1104. throw BusinessRuntimeException.getInstance("请输入正确的差价金额");
  1105. }
  1106. if (refundMoney.compareTo(orderDon.getMoney()) >= 0) {
  1107. throw BusinessRuntimeException.getInstance("补差价金额应不大于订单金额");
  1108. }
  1109. //退款
  1110. outNo = orderRefundService.centerRefund(orderRefundReq, orderDon);
  1111. orderDon.setRefundMoney(orderRefundMoney.add(refundMoney));
  1112. orderDonMapper.updateById(orderDon);
  1113. //补差价金额 扣除对应分销提成金额
  1114. orderDon.setRefundMoney(refundMoney);
  1115. deductDsPoints(orderDon);
  1116. //店铺分销提成金额扣除
  1117. yhShopDistributeService.deductDsMoney(orderDon);
  1118. } else {
  1119. BigDecimal refundBalance = refundMoney;
  1120. if (refundBalance == null || refundBalance.compareTo(BigDecimal.ZERO) <= 0 || refundBalance.compareTo(orderDon.getMoney()) > 0) {
  1121. throw BusinessRuntimeException.getInstance("请输入正确的差价金额");
  1122. }
  1123. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.price_differ, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.price_differ.getDesc(), true);
  1124. orderDon.setRefundBalance(orderDonRefundBalance.add(refundBalance));
  1125. orderDonMapper.updateById(orderDon);
  1126. }
  1127. orderRefundService.refundRecord(orderDon, refundMoney, orderRefundReq.getOperator(), goodsDon, sku, outNo, refundType, null);
  1128. }
  1129. @Override
  1130. @Transactional(rollbackFor = Throwable.class)
  1131. public void clearBalanceToRefundMoney(OrderBalanceRefundReq refundReq) throws Exception {
  1132. Long refundOrderId = refundReq.getRefundOrderId();
  1133. BigDecimal refundMoney = refundReq.getRefundMoney();
  1134. RefundOrderDon refundOrderDon = refundOrderDonMapper.selectById(refundOrderId);
  1135. if (!"balance".equals(refundOrderDon.getRefundMethod())) {
  1136. throw BusinessRuntimeException.getInstance("该记录不是余额退款类型");
  1137. }
  1138. Long orderId = refundOrderDon.getOrderId();
  1139. OrderDon orderDon = orderDonMapper.selectById(orderId);
  1140. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  1141. throw BusinessRuntimeException.getInstance("该记录对应的订单无实际支付金额");
  1142. }
  1143. if (refundOrderDon.getIsClearBalance()) {
  1144. throw BusinessRuntimeException.getInstance("该笔退款余额记录已退款");
  1145. }
  1146. BigDecimal refundFee = refundOrderDon.getRefundFee();
  1147. //默认退全部余额
  1148. if (refundMoney != null) {
  1149. refundFee = refundMoney;
  1150. }
  1151. BigDecimal money = orderDon.getMoney();
  1152. //若退款余额 大于退款金额 将退款余额至为 退款金额
  1153. if (refundFee.compareTo(money) > 0) {
  1154. refundFee = money;
  1155. }
  1156. User user = userMapper.selectById(orderDon.getUserId());
  1157. if (user.getBalance().compareTo(refundFee) < 0) {
  1158. throw BusinessRuntimeException.getInstance("用户余额不足,无法扣除对应退款余额");
  1159. }
  1160. int update = userMapper.update(null, Wrappers.lambdaUpdate(User.class)
  1161. .set(User::getBalance, user.getBalance().subtract(refundFee))
  1162. .eq(User::getId, user.getId())
  1163. .eq(User::getBalance, user.getBalance()));
  1164. if (update == 0) {
  1165. throw BusinessRuntimeException.getInstance("扣除用户退款余额失败,请重试...");
  1166. }
  1167. OrderRefundReq orderRefundReq = new OrderRefundReq();
  1168. orderRefundReq.setOrderId(orderId);
  1169. orderRefundReq.setRefundMoney(refundFee);
  1170. orderRefundReq.setRefundType("money");
  1171. String outNo = orderRefundService.centerRefund(orderRefundReq, orderDon);
  1172. orderDon.setRefundBalance(orderDon.getRefundBalance().subtract(refundFee));
  1173. BigDecimal orderRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  1174. orderDon.setRefundMoney(orderRefundMoney.add(refundFee));
  1175. orderDonMapper.updateById(orderDon);
  1176. refundOrderDon.setOutRefundNo(outNo);
  1177. refundOrderDon.setIsClearBalance(true);
  1178. refundOrderDonMapper.updateById(refundOrderDon);
  1179. }
  1180. /**
  1181. * 寻找该车队空余车位
  1182. */
  1183. public GroupsRelation getRelationThisTrips(Long userId, Long groupsId, Integer retryNum) {
  1184. //寻找快满编车队进行占座
  1185. GroupsRelation relation = relationMapper.selectRandomOneRelationByGroupsId(groupsId);
  1186. if (relation == null) {
  1187. throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  1188. }
  1189. Long relationId = relation.getId();
  1190. if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
  1191. if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  1192. retryNum++;
  1193. return getRelationThisTrips(userId, groupsId, retryNum);
  1194. }
  1195. int count = groupsMapper.decrAvailableNum(relation.getGroupsId());
  1196. if (count == 0) {
  1197. log.error("车位异常 groupId:{}", groupsId);
  1198. groupsMapper.updateAvailableNum(groupsId);
  1199. throw new BusinessRuntimeException("车位异常");
  1200. }
  1201. return relation;
  1202. }
  1203. private GroupsRelation getChatGPTOutsideRelation(Long userId, Long groupsId, Integer relationNum, Integer retryNum) {
  1204. //寻找快满编车队额外座位
  1205. GroupsRelation relation = relationMapper.selectOutsideRelationByGroupsId(groupsId, relationNum);
  1206. if (relation == null) {
  1207. relation = new GroupsRelation();
  1208. relation.setStatus(GroupsRelation.Status.outside);
  1209. relation.setUserId(userId);
  1210. relation.setGroupsId(groupsId);
  1211. GroupsRelation maxNumRelation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getGroupsId, groupsId).orderByDesc(GroupsRelation::getNum).last("limit 1"));
  1212. relation.setNum(maxNumRelation.getNum() + 1);
  1213. relationMapper.insert(relation);
  1214. return relation;
  1215. }
  1216. Long relationId = relation.getId();
  1217. if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
  1218. if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  1219. retryNum++;
  1220. return getChatGPTOutsideRelation(userId, groupsId, relationNum, retryNum);
  1221. }
  1222. return relation;
  1223. }
  1224. }