CmsOrderDonServiceImpl.java 74 KB

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