CmsOrderDonServiceImpl.java 75 KB

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