CmsOrderDonServiceImpl.java 100 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795
  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.ObjectUtil;
  8. import cn.hutool.core.util.StrUtil;
  9. import com.alipay.api.AlipayClient;
  10. import com.alipay.api.domain.AlipayTradeRefundModel;
  11. import com.alipay.api.request.AlipayTradeRefundRequest;
  12. import com.alipay.api.response.AlipayTradeRefundResponse;
  13. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  14. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  15. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  16. import com.cyksj.common.constant.Constant;
  17. import com.cyksj.common.exception.BusinessRuntimeException;
  18. import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
  19. import com.cyksj.common.util.Codec;
  20. import com.cyksj.common.util.Jsons;
  21. import com.cyksj.common.util.StringUtil;
  22. import com.cyksj.common.util.Xmls;
  23. import com.cyksj.config.WeChatConfig;
  24. import com.cyksj.config.zfb.AliPayClientFactory;
  25. import com.cyksj.dto.RedisKey;
  26. import com.cyksj.mapper.*;
  27. import com.cyksj.mapper.channel.ShopConfigMapper;
  28. import com.cyksj.mapper.channel.UserPayEquipmentAvailableBenefitsMapper;
  29. import com.cyksj.mapper.channel.UserPayEquipmentReceiveBenefitsRecordMapper;
  30. import com.cyksj.mapper.manage.cms.CmsUserMapper;
  31. import com.cyksj.mapper.manage.distribute.DistributeWaitingSendPointsMapper;
  32. import com.cyksj.mapper.manage.distribute.UserDistributeBusinessOrderDonRecordMapper;
  33. import com.cyksj.mapper.manage.distribute.UserDistributeMapper;
  34. import com.cyksj.mapper.manage.distribute.equipment.EquipmentUserDistributeTransportBenefitsMapper;
  35. import com.cyksj.mapper.manage.distribute.sub.UserDistributeSubMapper;
  36. import com.cyksj.mapper.manage.distribute.sub.UserDistributeSubRewardsMapper;
  37. import com.cyksj.mapper.manage.distribute.sub.UserDistributeSubWaitingMapper;
  38. import com.cyksj.mapper.manage.sys.WorkOrderMapper;
  39. import com.cyksj.mapper.mirrorshop.UserMirrorShopDistributeWaitingSendPointsMapper;
  40. import com.cyksj.mapper.mirrorshop.UserMirrorShopMapper;
  41. import com.cyksj.mapper.shop.YhShopUserDistributeBusinessOrderDonRecordMapper;
  42. import com.cyksj.mapper.stock.GoodsSkuStockRelateMapper;
  43. import com.cyksj.model.entity.*;
  44. import com.cyksj.model.excel.ExcelOrderDonInfo;
  45. import com.cyksj.model.manage.request.ReqSetLogisticsPost;
  46. import com.cyksj.model.manage.views.GroupsRelationView;
  47. import com.cyksj.model.request.ChangeRelationReq;
  48. import com.cyksj.model.request.ClickOutReq;
  49. import com.cyksj.model.request.OrderBalanceRefundReq;
  50. import com.cyksj.model.request.OrderRefundReq;
  51. import com.cyksj.redis.RedisService;
  52. import com.cyksj.service.chatgpt.GptUserRechargeRecordService;
  53. import com.cyksj.service.coin.UserGalaxyCoinService;
  54. import com.cyksj.service.coupon.CouponFontService;
  55. import com.cyksj.service.distribute.equipment.EquipmentDistributeService;
  56. import com.cyksj.service.giftcard.GiftCardOrderUseRecordService;
  57. import com.cyksj.service.mange.CmsOrderDonService;
  58. import com.cyksj.service.mange.MirrorUserCleatService;
  59. import com.cyksj.service.mange.stock.GoodsDonStockService;
  60. import com.cyksj.service.market.MarketFrontService;
  61. import com.cyksj.service.order.OrderCommonService;
  62. import com.cyksj.service.order.OrderRefundService;
  63. import com.cyksj.service.order.UserRealOrderBenefitsService;
  64. import com.cyksj.service.relation.GroupRelationClearService;
  65. import com.cyksj.service.relation.GroupRelationFrontService;
  66. import com.cyksj.service.relation.GroupsRelationExpiryRecordService;
  67. import com.cyksj.service.relation.GroupsRelationNetflixService;
  68. import com.cyksj.service.shop.YhShopDistributeService;
  69. import com.cyksj.service.user.UserBenefitsService;
  70. import com.cyksj.service.user.UserBindRelationService;
  71. import com.cyksj.service.wechat.WeChatService;
  72. import com.ejlchina.searcher.BeanSearcher;
  73. import com.ejlchina.searcher.util.MapUtils;
  74. import lombok.RequiredArgsConstructor;
  75. import lombok.extern.slf4j.Slf4j;
  76. import org.springframework.dao.DuplicateKeyException;
  77. import org.springframework.stereotype.Service;
  78. import org.springframework.transaction.annotation.Transactional;
  79. import java.math.BigDecimal;
  80. import java.math.RoundingMode;
  81. import java.util.Date;
  82. import java.util.List;
  83. import java.util.Map;
  84. import java.util.Optional;
  85. import java.util.concurrent.atomic.AtomicInteger;
  86. import java.util.stream.Collectors;
  87. /**
  88. * @author chan
  89. * @date 2021/10/25 下午10:14
  90. */
  91. @Service
  92. @Slf4j
  93. @RequiredArgsConstructor
  94. public class CmsOrderDonServiceImpl extends ServiceImpl<OrderDonMapper,OrderDon> implements CmsOrderDonService {
  95. private final OrderDonTransportMapper transportMapper;
  96. private final OrderDonWaybillMapper orderDonWaybillMapper;
  97. private final GoodsSkuStockRelateMapper skuStockRelateMapper;
  98. private final GoodsDonStockService goodsDonStockService;
  99. private final GoodsDonSkuMapper goodsDonSkuMapper;
  100. private final UserRealOrderBenefitsService userRealOrderBenefitsService;
  101. private final UserRelationKickOutRecordMapper kickOutRecordMapper;
  102. private final CmsUserMapper cmsUserMapper;
  103. private final OrderCommonService orderCommonService;
  104. private final GoodsDonMapper goodsDonMapper;
  105. private final RedisService redisService;
  106. private final UserBenefitsService userBenefitsService;
  107. private final DistributeWaitingSendPointsMapper distributeWaitingSendPointsMapper;
  108. private final RefundOrderDonMapper refundOrderDonMapper;
  109. private final UserDistributeMapper userDistributeMapper;
  110. private final OrderDonMapper orderDonMapper;
  111. private final MarketFrontService marketFrontService;
  112. private final EquipmentDistributeService equipmentDistributeService;
  113. private final CouponFontService couponFontService;
  114. private final WeChatService weChatService;
  115. private final WeChatConfig weChatConfig;
  116. private final ShopConfigMapper shopConfigMapper;
  117. private final GroupRelationClearService relationClearService;
  118. private final GroupsRelationMapper relationMapper;
  119. private final GroupsMapper groupsMapper;
  120. private final GoodsDonSkuMapper skuMapper;
  121. private final UserDistributeBusinessOrderDonRecordMapper businessOrderDonRecordMapper;
  122. private final WorkOrderMapper workOrderMapper;
  123. private final OrderRefundService orderRefundService;
  124. private final OrderDiscountPlusPurchaseSkuRelationMapper orderDiscountPlusPurchaseSkuRelationMapper;
  125. private final EquipmentUserDistributeTransportBenefitsMapper transportBenefitsMapper;
  126. private final BeanSearcher beanSearcher;
  127. private final UserPayEquipmentReceiveBenefitsRecordMapper receiveBenefitsRecordMapper;
  128. private final GroupsRelationExpiryRecordService groupsRelationExpiryRecordService;
  129. private final GiftCardOrderUseRecordService giftCardOrderUseRecordService;
  130. private final GiftCardUserRecordMapper giftCardUserRecordMapper;
  131. private final YhShopDistributeService yhShopDistributeService;
  132. private final YhShopUserDistributeBusinessOrderDonRecordMapper yhShopBusinessOrderDonRecordMapper;
  133. private final UserPayEquipmentAvailableBenefitsMapper availableBenefitsMapper;
  134. private final GroupRelationFrontService groupRelationFrontService;
  135. private final UserMapper userMapper;
  136. private final ChatgptUserMapper chatgptUserMapper;
  137. private final UserDistributeSubMapper userDistributeSubMapper;
  138. private final UserDistributeSubWaitingMapper subWaitingMapper;
  139. private final UserDistributeSubRewardsMapper userDistributeSubRewardsMapper;
  140. private final UpgradeOrderDonMapper upgradeOrderDonMapper;
  141. private final UpgradePackageMapper upgradePackageMapper;
  142. private final MidjourneyUserMapper midjourneyUserMapper;
  143. private final GroupsRelationMapper groupsRelationMapper;
  144. private final UserBindRelationService userBindRelationService;
  145. private final GroupsRelationNetflixService groupsRelationNetflixService;
  146. private final AccountMapper accountMapper;
  147. private final MirrorUserCleatService mirrorUserCleatService;
  148. private final OrderDonRenewRecordMapper orderDonRenewRecordMapper;
  149. private final OrderDonUpgradeRenewRecordMapper orderDonUpgradeRenewRecordMapper;
  150. private final LumaUserMapper lumaUserMapper;
  151. private final UserBenefitsOrderRecordMapper userBenefitsOrderRecordMapper;
  152. private final UserBenefitsComboRelationRecordMapper userBenefitsComboRelationRecordMapper;
  153. private final UserMirrorShopMapper userMirrorShopMapper;
  154. private final UserMirrorShopDistributeWaitingSendPointsMapper userMirrorShopDistributeWaitingSendPointsMapper;
  155. private final ClaudeUserMapper claudeUserMapper;
  156. private final UserTicketClearedRecordMapper userTicketClearedRecordMapper;
  157. private final NetflixUserAccountSubmitRecoverRecordMapper netflixUserAccountSubmitRecoverRecordMapper;
  158. private final NetflixUserChangeOtherTicketRecordMapper netflixUserChangeOtherTicketRecordMapper;
  159. private final OrderDonGalaxyCoinRecordMapper orderDonGalaxyCoinRecordMapper;
  160. private final UserGalaxyCoinService userGalaxyCoinService;
  161. private final GptUserRechargeRecordService gptUserRechargeRecordService;
  162. private static final GlobalThreadPoolTaskExecutor TASK_POOL = GlobalThreadPoolTaskExecutor.getInstance();
  163. @Override
  164. public List<ExcelOrderDonInfo> exportOrderInfo(Long promotionId, String start, String end) {
  165. return this.getBaseMapper().exportOrderInfo(promotionId,start,end);
  166. }
  167. @Override
  168. public OrderDonTransport getTransport(Long orderId) {
  169. return transportMapper.selectOne(Wrappers.lambdaQuery(OrderDonTransport.class).eq(OrderDonTransport::getOrderId, orderId));
  170. }
  171. @Transactional(rollbackFor = Throwable.class)
  172. @Override
  173. public OrderDonWaybill setWaybill(ReqSetLogisticsPost reqSetLogisticsPost) {
  174. OrderDonWaybill orderDonWaybill = Optional.ofNullable(orderDonWaybillMapper.selectOne(Wrappers.lambdaQuery(OrderDonWaybill.class).eq(OrderDonWaybill::getOrderId, reqSetLogisticsPost.getOrderId()))).orElse(new OrderDonWaybill());
  175. orderDonWaybill.setCodeCn(reqSetLogisticsPost.getCodeCn());
  176. orderDonWaybill.setTrackingNumber(reqSetLogisticsPost.getTrackingNumber());
  177. orderDonWaybill.setOrderId(reqSetLogisticsPost.getOrderId());
  178. orderDonWaybill.setRemark(reqSetLogisticsPost.getRemark());
  179. OrderDon orderDon = getById(orderDonWaybill.getOrderId());
  180. Integer type = Optional.ofNullable(reqSetLogisticsPost.getType()).orElse(0);
  181. //实物发货
  182. if (type == 0 || type == 1) {
  183. if (orderDonWaybill.getId() == null) {
  184. try {
  185. orderDonWaybillMapper.insert(orderDonWaybill);
  186. } catch (DuplicateKeyException e) {
  187. return orderDonWaybill;
  188. }
  189. orderDon.setStatus(OrderDon.Status.transport);
  190. updateById(orderDon);
  191. //库存扣减逻辑
  192. List<GoodsSkuStockRelate> relateList = skuStockRelateMapper.selectList(Wrappers.lambdaQuery(GoodsSkuStockRelate.class).eq(GoodsSkuStockRelate::getSkuId, orderDon.getSkuId()));
  193. if (!relateList.isEmpty()) {
  194. relateList.forEach((relate) -> {
  195. goodsDonStockService.upStockRelate(relate.getStockId(), orderDon.getId(), "transport");
  196. });
  197. }
  198. } else {
  199. if (orderDon.getStatus() == OrderDon.Status.hasPayment) {
  200. orderDon.setStatus(OrderDon.Status.transport);
  201. updateById(orderDon);
  202. }
  203. orderDonWaybillMapper.updateById(orderDonWaybill);
  204. }
  205. //实物分销订单是否存在
  206. DistributeWaitingSendPoints waitingSendPoints = distributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(DistributeWaitingSendPoints.class)
  207. .eq(DistributeWaitingSendPoints::getOrderId, orderDon.getId())
  208. .eq(DistributeWaitingSendPoints::getIsDelivery, false)
  209. .last("limit 1"));
  210. if (waitingSendPoints != null) {
  211. //实物分销订单发货后再 进行提成结算期
  212. waitingSendPoints.setIsDelivery(true);
  213. distributeWaitingSendPointsMapper.updateById(waitingSendPoints);
  214. }
  215. //分销有礼 分销实物是否有发货后用户权益
  216. EquipmentUserDistributeTransportBenefits transportBenefits = transportBenefitsMapper.selectOne(Wrappers.lambdaQuery(EquipmentUserDistributeTransportBenefits.class)
  217. .eq(EquipmentUserDistributeTransportBenefits::getOrderId, orderDon.getId())
  218. .eq(EquipmentUserDistributeTransportBenefits::getStatus, EquipmentUserDistributeTransportBenefits.Status.hasPayment).last("limit 1"));
  219. if (transportBenefits != null) {
  220. if (transportBenefits.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  221. //7天后余额到账
  222. transportBenefitsMapper.update(null, Wrappers.lambdaUpdate(EquipmentUserDistributeTransportBenefits.class)
  223. .set(EquipmentUserDistributeTransportBenefits::getStatus, EquipmentUserDistributeTransportBenefits.Status.transport)
  224. .set(EquipmentUserDistributeTransportBenefits::getSendTime, DateUtil.offsetDay(DateTime.now(), 7))
  225. .eq(EquipmentUserDistributeTransportBenefits::getOrderId, orderDon.getId())
  226. .eq(EquipmentUserDistributeTransportBenefits::getStatus, EquipmentUserDistributeTransportBenefits.Status.hasPayment));
  227. }
  228. }
  229. }
  230. //权益发货
  231. if (type == 0 || type == 2) {
  232. GoodsDonSku sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  233. if (sku != null && sku.getIsBenefits()) {
  234. //是否实物权益已发放
  235. Integer count = receiveBenefitsRecordMapper.selectCount(Wrappers.lambdaQuery(UserPayEquipmentReceiveBenefitsRecord.class)
  236. .eq(UserPayEquipmentReceiveBenefitsRecord::getRealOrderId, orderDon.getId()));
  237. if (count == 0) {
  238. count = availableBenefitsMapper.selectCount(Wrappers.lambdaQuery(UserPayEquipmentAvailableBenefits.class)
  239. .eq(UserPayEquipmentAvailableBenefits::getRealOrderId, orderDon.getId()));
  240. }
  241. if (count == 0) {
  242. //实物权益未发
  243. String benefitsKey = RedisService.key.REAL_GOODS_BENEFITS_KEY.getNameFormat(orderDon.getId());
  244. if (redisService.setNx(benefitsKey, orderDon.getId(), RedisService.key.REAL_GOODS_BENEFITS_KEY.getTimeout())) {
  245. //发放实物购买权益
  246. if (StrUtil.isNotEmpty(sku.getBenefitsList())) {
  247. try {
  248. List<GoodsDonSku> goodsDonSkus = Jsons.parseList(sku.getBenefitsList(), GoodsDonSku.class);
  249. //自购实物 获取权益
  250. userRealOrderBenefitsService.getPayRealGoodsBenefits(orderDon.getUserId(), orderDon.getId(), orderDon.getYhsId(), goodsDonSkus);
  251. //清除多余的车票
  252. clearExtraRelation(orderDon);
  253. } catch (Exception e) {
  254. redisService.del(benefitsKey);
  255. }
  256. }
  257. }
  258. }
  259. }
  260. }
  261. return orderDonWaybill;
  262. }
  263. @Override
  264. public void kickOutRelationId(long adminId, ClickOutReq req) {
  265. Long orderId = req.getOrderId();
  266. OrderDon orderDon = getById(orderId);
  267. if (orderDon != null && !orderDon.getIsKickOut()) {
  268. try {
  269. UserRelationKickOutRecord kickOutRecord = new UserRelationKickOutRecord();
  270. kickOutRecord.setUserId(orderDon.getUserId());
  271. kickOutRecord.setRelationId(orderDon.getRelationId());
  272. kickOutRecord.setGoodsId(orderDon.getGoodsId());
  273. kickOutRecord.setSkuId(orderDon.getSkuId());
  274. kickOutRecord.setReason(req.getReason());
  275. kickOutRecord.setImg(req.getImg());
  276. kickOutRecord.setRemark(req.getRemark());
  277. kickOutRecord.setOrderId(orderDon.getId());
  278. kickOutRecord.setOrderNo(orderDon.getOrderNo());
  279. Optional.ofNullable(cmsUserMapper.selectById(adminId)).ifPresent(cmsUser -> kickOutRecord.setOperator(cmsUser.getNickname()));
  280. kickOutRecordMapper.insert(kickOutRecord);
  281. orderDon.setIsKickOut(true);
  282. updateById(orderDon);
  283. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  284. GoodsDonSku goodsDonSku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  285. //清除车票
  286. orderCommonService.clearUnrealGoodsDetail(orderDon, goodsDon.getType(), goodsDonSku);
  287. } catch (DuplicateKeyException e) {
  288. }
  289. }
  290. }
  291. @Override
  292. @Transactional(rollbackFor = Throwable.class)
  293. public void unifiedRefund(OrderRefundReq refundReq) throws Exception {
  294. OrderDon orderDon = orderDonMapper.selectById(refundReq.getOrderId());
  295. GoodsDonSku sku = null;
  296. if (orderDon.getSkuId() != null) {
  297. sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  298. }
  299. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  300. if (StrUtil.isEmpty(refundReq.getRefundType())) {
  301. refundReq.setRefundType("money");
  302. }
  303. String refundType = refundReq.getRefundType();
  304. //校验订单是否符合退款
  305. checkOrderRefund(orderDon, goodsDon, sku, refundReq);
  306. //空订单关闭
  307. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0 && orderDon.getBalance().compareTo(BigDecimal.ZERO) == 0
  308. && orderDon.getRelationId() == 0) {
  309. orderDon.setStatus(OrderDon.Status.refund);
  310. orderDonMapper.updateById(orderDon);
  311. if (goodsDon.getType() == 2) {
  312. //扣除用户自身实物权益
  313. userRealOrderBenefitsService.deductUserRealGoodsBenefits(orderDon.getId());
  314. }
  315. return;
  316. }
  317. //调用第三方接口退款
  318. String outNo = StrUtil.EMPTY;
  319. if (refundReq.getRefundMoney() != null && refundReq.getRefundMoney().compareTo(BigDecimal.ZERO) > 0) {
  320. outNo = orderRefundService.centerRefund(refundReq, orderDon);
  321. }
  322. orderDon.setRefundDesc(refundReq.getRefundDesc());
  323. //记录退款信息
  324. commonRefund(orderDon, refundReq.getRefundMoney(), refundReq.getOperator(), goodsDon, sku, outNo, refundType, refundReq.getIsOnly(), refundReq.getRefundBalance(), refundReq.getChatImg(), refundReq.getDeductBalance(), refundReq.getDpRelationIds());
  325. //修改订单状态
  326. orderDon.setStatus(OrderDon.Status.refund);
  327. orderDonMapper.updateById(orderDon);
  328. //续费升级订单
  329. if (orderDon.getOrderType() == 2 && sku.getIsMirror()) {
  330. mirrorUserCleatService.handleRenewUpgradeOrders(orderDon, sku);
  331. }
  332. //提交过工单的订单
  333. //将用户异常订单关闭
  334. workOrderMapper.update(null, Wrappers.lambdaUpdate(WorkOrder.class)
  335. .set(WorkOrder::getStatus, WorkOrder.Status.close)
  336. .eq(WorkOrder::getStatus, WorkOrder.Status.waiting)
  337. .eq(WorkOrder::getUserId, orderDon.getUserId())
  338. .eq(WorkOrder::getRelationId, orderDon.getRelationId()));
  339. //将GPT规格的车队 下次可停车时间置空
  340. groupRelationFrontService.setGroupsTripsParkingTimeEmpty(sku, orderDon.getRelationId());
  341. }
  342. @Override
  343. @Transactional(rollbackFor = Throwable.class)
  344. public void unifiedUpgradeRefund(OrderRefundReq refundReq) throws Exception {
  345. UpgradeOrderDon orderDon = upgradeOrderDonMapper.selectById(refundReq.getOrderId());
  346. UpgradePackage upgradePackage = upgradePackageMapper.selectById(orderDon.getPackageId());
  347. if (StrUtil.isEmpty(refundReq.getRefundType())) {
  348. refundReq.setRefundType("money");
  349. }
  350. String refundType = refundReq.getRefundType();
  351. //校验订单是否符合退款
  352. checkUpgradeOrderRefund(orderDon, refundReq);
  353. //空订单关闭
  354. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0 && orderDon.getBalance().compareTo(BigDecimal.ZERO) == 0) {
  355. orderDon.setStatus(UpgradeOrderDon.Status.refund);
  356. upgradeOrderDonMapper.updateById(orderDon);
  357. return;
  358. }
  359. Long userId = orderDon.getUserId();
  360. List<Long> userIdList = null;
  361. //检验gpt套餐
  362. if (upgradePackage.getGoodsId() == 18) {
  363. userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  364. //是否有更高级的套餐
  365. UpgradeOrderDon more = upgradeOrderDonMapper.selectOne(Wrappers.lambdaQuery(UpgradeOrderDon.class)
  366. .in(UpgradeOrderDon::getUserId, userIdList)
  367. .eq(UpgradeOrderDon::getRelationId, orderDon.getRelationId())
  368. .gt(UpgradeOrderDon::getNum, orderDon.getNum())
  369. .eq(UpgradeOrderDon::getStatus, UpgradeOrderDon.Status.complete)
  370. .last("limit 1"));
  371. if (more != null) {
  372. throw BusinessRuntimeException.getInstance("请先退掉其更高级套餐");
  373. }
  374. }
  375. //调用第三方接口退款
  376. String outNo = orderRefundService.centerUpgradeRefund(refundReq, orderDon);
  377. orderDon.setRefundDesc(refundReq.getRefundDesc());
  378. //记录退款信息
  379. commonUpgradeRefund(orderDon, refundReq.getRefundMoney(), refundReq.getOperator(), upgradePackage, outNo, refundType, refundReq.getIsOnly(), refundReq.getRefundBalance(), refundReq.getChatImg());
  380. //修改订单状态
  381. orderDon.setStatus(UpgradeOrderDon.Status.refund);
  382. upgradeOrderDonMapper.updateById(orderDon);
  383. //扣除套餐次数
  384. if (upgradePackage.getGoodsId() == 26) {
  385. MidjourneyUser midjourneyUser = midjourneyUserMapper.selectOne(Wrappers.lambdaQuery(MidjourneyUser.class).eq(MidjourneyUser::getRelationId, orderDon.getRelationId()));
  386. if (midjourneyUser != null) {
  387. int update = midjourneyUserMapper.update(null, Wrappers.lambdaUpdate(MidjourneyUser.class)
  388. .set(MidjourneyUser::getMjUpgradeNum, midjourneyUser.getMjUpgradeNum() < upgradePackage.getNum() ? 0 : midjourneyUser.getMjUpgradeNum() - upgradePackage.getNum())
  389. .eq(MidjourneyUser::getId, midjourneyUser.getId()));
  390. if (update == 0) {
  391. log.info("midjourneyUser 套餐包增值失败 id:{},orderId:{}", midjourneyUser.getId(), orderDon.getId());
  392. }
  393. Long decr = redisService.decr(RedisService.key.MIDJOURNEY_UPGRADE_LIMIT.getName() + midjourneyUser.getId(), upgradePackage.getNum().longValue());
  394. if (decr < 0) {
  395. redisService.set(RedisService.key.MIDJOURNEY_UPGRADE_LIMIT.getName() + midjourneyUser.getId(), 0L);
  396. }
  397. }
  398. }
  399. //扣除gpt套餐升级
  400. if (upgradePackage.getGoodsId() == 18) {
  401. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class).eq(ChatgptUser::getRelationId, orderDon.getRelationId()));
  402. if (chatgptUser != null) {
  403. GroupsRelation relation = groupsRelationMapper.selectById(chatgptUser.getRelationId());
  404. GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
  405. GoodsDonSku sku = skuMapper.selectById(groupsTrips.getSkuId());
  406. //原先sku的套餐
  407. Long gptLimitTime = sku.getGptLimitTime();
  408. Integer gptLimitNum = sku.getGptLimitNum();
  409. //次等套餐的规格
  410. UpgradeOrderDon secondUpgrade = upgradeOrderDonMapper.selectOne(Wrappers.lambdaQuery(UpgradeOrderDon.class)
  411. .in(UpgradeOrderDon::getUserId, userIdList)
  412. .eq(UpgradeOrderDon::getRelationId, orderDon.getRelationId())
  413. .lt(UpgradeOrderDon::getNum, orderDon.getNum())
  414. .eq(UpgradeOrderDon::getStatus, UpgradeOrderDon.Status.complete)
  415. .last("limit 1"));
  416. Long renewSkuId = chatgptUser.getRenewSkuId();
  417. //续费升级
  418. GoodsDonSku renewSku = null;
  419. if (renewSkuId != null) {
  420. renewSku = goodsDonSkuMapper.selectById(renewSkuId);
  421. gptLimitTime = renewSku.getGptLimitTime();
  422. gptLimitNum = renewSku.getGptLimitNum();
  423. }
  424. if (secondUpgrade != null) {
  425. gptLimitTime = secondUpgrade.getTime();
  426. gptLimitNum = secondUpgrade.getNum();
  427. if (renewSku != null) {
  428. //低级套餐
  429. GoodsDonSku secondSkuUpGrade = goodsDonSkuMapper.selectById(secondUpgrade.getSkuId());
  430. //续费升级套餐更高
  431. if (renewSku.getMonths() >= secondSkuUpGrade.getMonths() && renewSku.getGptLimitNum() >= secondSkuUpGrade.getGptLimitNum() && renewSku.getGptLimitTime() <= secondSkuUpGrade.getGptLimitTime()) {
  432. gptLimitTime = renewSku.getGptLimitTime();
  433. gptLimitNum = renewSku.getGptLimitNum();
  434. }
  435. }
  436. }
  437. Long packageId = 0l;
  438. //降级套餐
  439. if (secondUpgrade != null) {
  440. packageId = secondUpgrade.getPackageId();
  441. }
  442. int update = chatgptUserMapper.update(null, Wrappers.lambdaUpdate(ChatgptUser.class)
  443. .set(ChatgptUser::getLimitTime, gptLimitTime)
  444. .set(ChatgptUser::getLimitNum, gptLimitNum)
  445. .set(ChatgptUser::getPackageId, packageId)
  446. //无次等套餐 不需要清除套餐时间
  447. .set(secondUpgrade == null, ChatgptUser::getClearPackageTime, null)
  448. .eq(ChatgptUser::getId, chatgptUser.getId()));
  449. if (update == 0) {
  450. log.info("chatgptUser 升级套餐包增值失败 id:{},orderId:{}", chatgptUser.getId(), orderDon.getId());
  451. }
  452. }
  453. }
  454. //扣除luma套餐次数
  455. if (upgradePackage.getGoodsId() == Constant.LUMA_GOODS_ID) {
  456. LumaUser lumaUser = lumaUserMapper.selectOne(Wrappers.lambdaQuery(LumaUser.class).eq(LumaUser::getRelationId, orderDon.getRelationId()));
  457. if (lumaUser != null) {
  458. int update = lumaUserMapper.update(null, Wrappers.lambdaUpdate(LumaUser.class)
  459. .set(LumaUser::getNum, lumaUser.getNum() < upgradePackage.getNum() ? 0 : lumaUser.getNum() - upgradePackage.getNum())
  460. .eq(LumaUser::getId, lumaUser.getId()));
  461. if (update == 0) {
  462. log.info("lumaUser 套餐包增值失败 id:{},orderId:{}", lumaUser.getId(), orderDon.getId());
  463. }
  464. Long decr = redisService.decr(RedisService.key.LUMA_NUM_LIMIT.getName() + lumaUser.getId(), upgradePackage.getNum().longValue());
  465. if (decr < 0) {
  466. redisService.set(RedisService.key.LUMA_NUM_LIMIT.getName() + lumaUser.getId(), 0L);
  467. }
  468. }
  469. }
  470. }
  471. /**
  472. * 退款后 处理关联
  473. */
  474. public void commonUpgradeRefund(UpgradeOrderDon orderDon, BigDecimal refundMoney, String operator, UpgradePackage upgradePackage, String outNo, String refundType, Boolean isOnly, BigDecimal refundBalance, String chatImg) {
  475. TASK_POOL.execute(() -> {
  476. orderRefundService.refundUpgradeRecord(orderDon, refundMoney, refundBalance, upgradePackage, operator, outNo, refundType, chatImg);
  477. //退等比例
  478. if (isOnly != null && isOnly) {
  479. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.refund, 0L, orderDon.getId(), upgradePackage.getName()+ UserBalanceSourceRecord.Source.refund.getDesc(), true);
  480. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  481. orderDon.setRefundBalance(orderDonRefundBalance.add(refundBalance));
  482. }
  483. // //若存在余额支付,退还余额
  484. // if (isOnly == null && orderDon.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  485. // userBenefitsService.addUserBalance(orderDon.getUserId(), orderDon.getBalance(), UserBalanceSourceRecord.Source.refund, 0L, orderDon.getId(), upgradePackage.getName() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  486. // }
  487. //是否全额退款
  488. // BigDecimal orderDonRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  489. // BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  490. // if (orderDonRefundMoney.add(orderDonRefundBalance).compareTo(orderDon.getMoney().add(Optional.ofNullable(orderDon.getBalance()).orElse(BigDecimal.ZERO))) == 0) {
  491. // //是否使用银河币支付
  492. // OrderDonGalaxyCoinRecord orderDonGalaxyCoinRecord = orderDonGalaxyCoinRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonGalaxyCoinRecord.class)
  493. // .eq(OrderDonGalaxyCoinRecord::getOrderId, orderDon.getId())
  494. // .eq(OrderDonGalaxyCoinRecord::getSource, OrderDonGalaxyCoinRecord.Source.upgrade.ordinal())
  495. // .last("limit 1"));
  496. // if (orderDonGalaxyCoinRecord != null) {
  497. // //有效时,返还银河币 并记录
  498. // userGalaxyCoinService.recordOrderRefundGalaxyCoinIfValid(orderDon.getId(), orderDonGalaxyCoinRecord.getUserId(), orderDonGalaxyCoinRecord.getGalaxyCoin().abs(), OrderDonGalaxyCoinRecord.Source.upgrade);
  499. // }
  500. // }
  501. //扣除 该笔订单产生的返现银河币
  502. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) > 0) {
  503. userGalaxyCoinService.subOrderGenerateGalaxyCoin(orderDon.getId(), OrderDonGalaxyCoinRecord.Source.upgrade);
  504. }
  505. //余额现金混合退款
  506. if (OrderRefundReq.RefundType.bxj.name().equals(refundType)) {
  507. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.refund, 0L, orderDon.getId(), upgradePackage.getName() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  508. }
  509. if (UpgradeOrderDon.Type.BALANCE.getType().equals(refundType)) {
  510. if (isOnly == null && orderDon.getMoney().compareTo(BigDecimal.ZERO) > 0) {
  511. userBenefitsService.addUserBalance(orderDon.getUserId(), refundMoney, UserBalanceSourceRecord.Source.refund, 0L, orderDon.getId(), upgradePackage.getName() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  512. }
  513. }
  514. });
  515. }
  516. /**
  517. * 校验订单是否符合退款操作
  518. */
  519. private void checkUpgradeOrderRefund(UpgradeOrderDon orderDon, OrderRefundReq refundReq) {
  520. if (orderDon == null) {
  521. throw BusinessRuntimeException.getInstance("订单不存在");
  522. }
  523. BigDecimal orderDonRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  524. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  525. String refundType = refundReq.getRefundType();
  526. // if (orderDon.getType() == UpgradeOrderDon.Type.BALANCE && !UpgradeOrderDon.Type.BALANCE.getType().equals(refundType)) {
  527. // throw BusinessRuntimeException.getInstance("余额支付的订单不支持金额退款");
  528. // }
  529. if (UpgradeOrderDon.Status.refund == orderDon.getStatus()) {
  530. throw BusinessRuntimeException.getInstance("该订单已退款");
  531. }
  532. if (UpgradeOrderDon.Status.noPayment == orderDon.getStatus() || UpgradeOrderDon.Status.close == orderDon.getStatus()) {
  533. throw BusinessRuntimeException.getInstance("订单{0}状态不支持退款", orderDon.getStatus());
  534. }
  535. BigDecimal refundMoney = refundReq.getRefundMoney();
  536. BigDecimal money = orderDon.getMoney();
  537. BigDecimal balance = orderDon.getBalance();
  538. BigDecimal refundBalance = refundReq.getRefundBalance();
  539. //余额退款
  540. if (UpgradeOrderDon.Type.BALANCE.getType().equals(refundType)) {
  541. refundMoney = orderDonRefundBalance.add(refundMoney);
  542. if (UpgradeOrderDon.Type.BALANCE != orderDon.getType() && refundMoney.compareTo(money) > 0) {
  543. throw BusinessRuntimeException.getInstance("退款余额大于订单支付金额");
  544. }
  545. orderDon.setRefundBalance(refundMoney);
  546. orderDon.setRefundMoney(BigDecimal.ZERO);
  547. } else if (OrderRefundReq.RefundType.bxj.name().equals(refundType)) {
  548. balance = balance.add(money);
  549. if (refundBalance.compareTo(balance) > 0) {
  550. throw BusinessRuntimeException.getInstance("退款余额大于订单支付余额");
  551. }
  552. refundBalance = refundBalance.add(orderDonRefundBalance);
  553. orderDon.setRefundBalance(refundBalance);
  554. refundMoney = orderDonRefundMoney.add(refundMoney);
  555. if (refundMoney.compareTo(money) > 0) {
  556. throw BusinessRuntimeException.getInstance("退款金额大于订单支付金额");
  557. }
  558. orderDon.setRefundMoney(refundMoney);
  559. } else {
  560. //退金额
  561. refundMoney = orderDonRefundMoney.add(refundMoney);
  562. if (refundMoney.compareTo(money) > 0) {
  563. throw BusinessRuntimeException.getInstance("退款金额大于订单支付金额");
  564. }
  565. orderDon.setRefundMoney(refundMoney);
  566. }
  567. if (!redisService.setNx(String.format("%s", refundReq.getOrderId()), refundReq.getOrderId(), 10l)) {
  568. throw BusinessRuntimeException.getInstance("请勿重复点击,正在退款中..");
  569. }
  570. }
  571. public String wxRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
  572. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) <=0){
  573. return StrUtil.EMPTY;
  574. }
  575. long time = System.currentTimeMillis();
  576. //退款订单号
  577. String outRefundNo = Codec.DoDigest.custom()
  578. .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
  579. .setStringData(time + String.valueOf(orderDon.getId()))
  580. .toHexString();
  581. weChatService.refundWxOrder(weChatConfig.getAppid(),
  582. Optional.ofNullable(orderDon.getShopId()).orElse(ShopConfig.WX_DEFAULT_APP_ID),
  583. orderDon.getTransactionId(),
  584. outRefundNo,
  585. orderDon.getMoney(),
  586. refundReq.getRefundMoney(),
  587. weChatConfig.getNotifyDomain() + "manage/order/wx/refund/notify");
  588. //记录退款信息
  589. return outRefundNo;
  590. }
  591. @Override
  592. public void wxRefundNotify(Map<String, String> map) throws Exception {
  593. // 对退款数据 解密
  594. String md5Key = Codec.DoDigest.custom().setAlgorithm(Codec.DoDigest.Algorithm.MD5).setStringData(shopConfigMapper.getByAppId(map.get("mch_id")).getSecret()).toHexString();
  595. String reqInfoXml = Codec.DoCipher.custom().setAlgorithm(Codec.DoCipher.Trans.AES_ECB_PKCS7Padding).setBase64Data(map.get("req_info")).setStringKey(md5Key).ofDecrypt().toText();
  596. log.info("=== 退款数据解密: \n {}", reqInfoXml);
  597. Map<String, String> reqInfoMap = Xmls.toMap(reqInfoXml);
  598. // 退款失败
  599. if (StrUtil.equals("CHANGE", reqInfoMap.get("refund_status"))) {
  600. throw BusinessRuntimeException.getInstance("退款异常.");
  601. } else if (StrUtil.equals("REFUNDCLOSE", reqInfoMap.get("refund_status"))) {
  602. throw BusinessRuntimeException.getInstance("退款关闭.");
  603. }
  604. /* 此处处理业务逻辑 */
  605. String outRefundNo = reqInfoMap.get("out_refund_no");
  606. String transactionId = reqInfoMap.get("transaction_id");
  607. String refundFee = reqInfoMap.get("refund_fee");
  608. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getTransactionId, transactionId).last("limit 1"));
  609. if (orderDon == null) {
  610. log.error("退款回调,transactionId:{}订单不存在", transactionId);
  611. return;
  612. }
  613. log.info("微信退款: 退款单号[{}] 退款成功.", outRefundNo);
  614. }
  615. @Override
  616. @Transactional(rollbackFor = Throwable.class)
  617. public void changeRelation(ChangeRelationReq req) throws Exception {
  618. Long relationId = req.getRelationId();
  619. Long groupId = req.getGroupsId();
  620. UserTicketClearedRecord.Source source = req.getSource();
  621. if (source == null) source = UserTicketClearedRecord.Source.change_ticket;
  622. GroupsRelation relation = relationMapper.selectById(relationId);
  623. Long yhsId = relation.getYhsId();
  624. Assert.notNull(relation, "车票已不存在");
  625. if (relation.getRechargeStatus() != null) {
  626. throw BusinessRuntimeException.getInstance("代充账号车票无法更换车票");
  627. }
  628. String key = RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getName() + relationId;
  629. if (!redisService.setNx(key, relationId, RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getTimeout())) {
  630. throw BusinessRuntimeException.getInstance("正在更换车票中..");
  631. }
  632. Long userId = relation.getUserId();
  633. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  634. try {
  635. log.info("用户userId:{}更换车票relationId:{}", userId, relationId);
  636. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  637. .in(OrderDon::getUserId, userIdList)
  638. .eq(OrderDon::getRelationId, relationId)
  639. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  640. .orderByDesc(OrderDon::getId)
  641. .last("limit 1"));
  642. OrderDiscountPlusPurchaseSkuRelation plusPurchaseSkuRelation = null;
  643. List<Long> plus_relationList = null;
  644. if (orderDon == null) {
  645. List<OrderDiscountPlusPurchaseSkuRelation> plusPurchaseSkuRelations = orderDiscountPlusPurchaseSkuRelationMapper.selectPlusRelationByIdAndUserId(relation.getId(), relation.getUserId());
  646. for (OrderDiscountPlusPurchaseSkuRelation data : plusPurchaseSkuRelations) {
  647. String relationIds = data.getRelationIds();
  648. if (StrUtil.isEmpty(relationIds)) {
  649. return;
  650. }
  651. List<Long> relationList = Jsons.parseList(relationIds, Long.class);
  652. if (relationList.contains(relationId)) {
  653. plusPurchaseSkuRelation = data;
  654. break;
  655. }
  656. }
  657. if (plusPurchaseSkuRelation != null) {
  658. String relationIds = plusPurchaseSkuRelation.getRelationIds();
  659. if (StrUtil.isNotEmpty(relationIds)) {
  660. plus_relationList = Jsons.parseList(relationIds, Long.class);
  661. if (plus_relationList.contains(relationId)) {
  662. orderDon = new OrderDon();
  663. GroupsRelationView groupsRelationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder().field(GroupsRelationView::getId, relationId).build());
  664. Assert.notNull(groupsRelationView, "车票已不存在");
  665. orderDon.setUserId(groupsRelationView.getUserId());
  666. orderDon.setSkuId(groupsRelationView.getSkuId());
  667. orderDon.setGoodsId(groupsRelationView.getGoodsId());
  668. orderDon.setStatus(OrderDon.Status.complete);
  669. orderDon.setOrderType(1);
  670. }
  671. }
  672. }
  673. }
  674. Assert.notNull(orderDon, "订单不存在");
  675. if (orderDon.getStatus() == OrderDon.Status.refund) {
  676. throw BusinessRuntimeException.getInstance("订单已退款");
  677. }
  678. //获取新车队
  679. LambdaQueryWrapper<GroupsTrips> queryWrapper = Wrappers.lambdaQuery(GroupsTrips.class)
  680. .eq(GroupsTrips::getSkuId, orderDon.getSkuId())
  681. .eq(GroupsTrips::getId, groupId)
  682. .ne(GroupsTrips::getId, relation.getGroupsId())
  683. .ne(GroupsTrips::getStatus, GroupsTrips.Status.down)
  684. .last("limit 1");
  685. GroupsTrips groups = groupsMapper.selectOne(queryWrapper);
  686. if (groups == null) throw BusinessRuntimeException.getInstance("车队不存在或已下架");
  687. if (!Constant.AI_goodsIds.contains(orderDon.getGoodsId()) && groups.getAvailableNum() <= 0) {
  688. throw BusinessRuntimeException.getInstance("该新车位人员已满");
  689. }
  690. Integer relationNum = groups.getNum();
  691. //获取新车队车位
  692. GroupsRelation newRelation;
  693. Boolean isOutside = req.getIsOutside();
  694. if (Constant.AI_goodsIds.contains(orderDon.getGoodsId()) && ((isOutside != null && isOutside) || groups.getAvailableNum() == 0) && groups.getNum() > 1) {
  695. //Ai车队 额外增加车位 并不让上车
  696. newRelation = getChatGPTOutsideRelation(orderDon.getUserId(), groupId, relationNum, 1);
  697. } else {
  698. newRelation = getRelationThisTrips(orderDon.getUserId(), groupId, 1);
  699. }
  700. //校验座位
  701. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  702. .set(GroupsRelation::getUserId, userId)
  703. .eq(GroupsRelation::getUserId, 0)
  704. .eq(GroupsRelation::getId, newRelation.getId()));
  705. if (update == 0) {
  706. throw BusinessRuntimeException.getInstance("系统繁忙,请重新操作");
  707. }
  708. newRelation.setUserId(userId);
  709. newRelation.setStartTime(relation.getStartTime());
  710. newRelation.setExpiryTime(relation.getExpiryTime());
  711. newRelation.setYhsId(yhsId);
  712. newRelation.setCmt(relation.getCmt());
  713. newRelation.setCustomerService(relation.getCustomerService());
  714. if (newRelation.getStatus() != GroupsRelation.Status.outside) {
  715. newRelation.setStatus(GroupsRelation.Status.validity);
  716. }
  717. //代充信息
  718. newRelation.setRechargeStatus(relation.getRechargeStatus());
  719. newRelation.setRechargeNum(relation.getRechargeNum());
  720. newRelation.setRechargeRemainNum(relation.getRechargeRemainNum());
  721. newRelation.setSubmitTime(relation.getSubmitTime());
  722. newRelation.setSendTime(relation.getSendTime());
  723. newRelation.setAccount(relation.getAccount());
  724. newRelation.setPassword(relation.getPassword());
  725. newRelation.setGptTaskId(relation.getGptTaskId());
  726. newRelation.setCardKey(relation.getCardKey());
  727. //清除原先车票
  728. relation.setNewRelationId(newRelation.getId());
  729. relationClearService.clearTicket(relation, source);
  730. //兜底处理 多余车票
  731. clearOtherChangeTicket(userId, relationId, newRelation, orderDon.getSkuId());
  732. //奈飞车票
  733. if (orderDon.getGoodsId() == 1) {
  734. User user = userMapper.selectById(newRelation.getUserId());
  735. GroupsTrips groupsTrips = groupsMapper.selectById(newRelation.getGroupsId());
  736. Account account = accountMapper.selectById(groupsTrips.getAccountId());
  737. AtomicInteger start = new AtomicInteger(1);
  738. groupsRelationNetflixService.timingSetNetflix(newRelation.getNum(), user.getNickname(), account.getAccount(), account.getPassword(), newRelation.getExpiryTime(), start);
  739. }
  740. if (plusPurchaseSkuRelation != null && plus_relationList != null) {
  741. plus_relationList.remove(relationId);
  742. plus_relationList.add(newRelation.getId());
  743. plusPurchaseSkuRelation.setRelationIds(plus_relationList.toString());
  744. orderDiscountPlusPurchaseSkuRelationMapper.updateById(plusPurchaseSkuRelation);
  745. }
  746. if (source != null && source == UserTicketClearedRecord.Source.abnormal) {
  747. //将用户异常订单关闭
  748. workOrderMapper.update(null, Wrappers.lambdaUpdate(WorkOrder.class)
  749. .set(WorkOrder::getStatus, WorkOrder.Status.close)
  750. .eq(WorkOrder::getStatus, WorkOrder.Status.waiting)
  751. .eq(WorkOrder::getUserId, userId)
  752. .eq(WorkOrder::getRelationId, relationId));
  753. }
  754. if (orderDon.getMoney() != null && orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  755. //是否是实物权益车票
  756. UserPayEquipmentReceiveBenefitsRecord receiveBenefitsRecord = receiveBenefitsRecordMapper.selectOne(Wrappers.lambdaQuery(UserPayEquipmentReceiveBenefitsRecord.class)
  757. .eq(UserPayEquipmentReceiveBenefitsRecord::getTicketOrderId, orderDon.getId())
  758. .eq(UserPayEquipmentReceiveBenefitsRecord::getRelationId, relationId).last("limit 1"));
  759. if (receiveBenefitsRecord != null) {
  760. receiveBenefitsRecord.setRelationId(newRelation.getId());
  761. receiveBenefitsRecordMapper.updateById(receiveBenefitsRecord);
  762. }
  763. }
  764. if ((newRelation.getStartTime() == null || newRelation.getExpiryTime() == null)) {
  765. List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.hasPayment));
  766. if (orderDonList.isEmpty()) {
  767. orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class)
  768. .eq(OrderDon::getUserId, userId)
  769. .eq(OrderDon::getRelationId, relationId)
  770. .eq(OrderDon::getStatus, OrderDon.Status.complete)
  771. .orderByDesc(OrderDon::getId)
  772. .last("limit 1"));
  773. }
  774. if (groups.getStatus() == GroupsTrips.Status.waiting) {
  775. orderDonList.forEach(hasPaymentOrder -> {
  776. hasPaymentOrder.setRelationId(newRelation.getId());
  777. orderDonMapper.updateById(hasPaymentOrder);
  778. });
  779. relationMapper.updateById(newRelation);
  780. return;
  781. }
  782. orderDonList.forEach((hasPaymentOrder) -> {
  783. //如果续费增加时间,如果首次则设置当前时间为初始时间
  784. Date expiryTime = Optional.ofNullable(newRelation.getExpiryTime()).orElse(new Date());
  785. GoodsDonSku donSku = skuMapper.selectById(hasPaymentOrder.getSkuId());
  786. Date newDate;
  787. if (donSku.getDays() != null && donSku.getDays() > 0) {
  788. newDate = DateUtil.offsetDay(expiryTime, donSku.getDays() * hasPaymentOrder.getNum());
  789. } else {
  790. newDate = DateUtil.offset(expiryTime, DateField.MONTH, donSku.getMonths() * hasPaymentOrder.getNum());
  791. }
  792. newRelation.setExpiryTime(newDate);
  793. newRelation.setStartTime(newRelation.getStartTime() == null ? new Date() : null);
  794. relationMapper.updateById(newRelation);
  795. hasPaymentOrder.setStatus(OrderDon.Status.complete);
  796. hasPaymentOrder.setRelationId(newRelation.getId());
  797. orderDonMapper.updateById(hasPaymentOrder);
  798. });
  799. return;
  800. }
  801. List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.complete));
  802. orderDonList.forEach(completeOrder->{
  803. completeOrder.setRelationId(newRelation.getId());
  804. orderDonMapper.updateById(completeOrder);
  805. });
  806. log.info("userId:{}更换车票,原座位号relationId:{}======>新座位号newRelationId:{}", newRelation.getUserId(), relationId, newRelation.getId());
  807. relationMapper.updateById(newRelation);
  808. //更换车票 调整GPT相关规格新车队 上车数
  809. GoodsDonSku sku = goodsDonSkuMapper.selectById(groups.getSkuId());
  810. groupRelationFrontService.adjustGroupsParkingTime(newRelation.getId(), sku);
  811. //关闭正在恢复的车票
  812. if (orderDon.getGoodsId() == Constant.NETFLIX_GID) {
  813. NetflixUserAccountSubmitRecoverRecord recoverRecord = netflixUserAccountSubmitRecoverRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  814. .eq(NetflixUserAccountSubmitRecoverRecord::getRelationId, orderDon.getRelationId())
  815. .in(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList)
  816. .eq(NetflixUserAccountSubmitRecoverRecord::getStatus, 0)
  817. .last("limit 1"));
  818. if (recoverRecord != null) {
  819. recoverRecord.setStatus(3);
  820. netflixUserAccountSubmitRecoverRecordMapper.updateById(recoverRecord);
  821. }
  822. }
  823. } finally {
  824. if (redisService.hasKey(key)) {
  825. redisService.del(key);
  826. }
  827. }
  828. }
  829. public String zfbRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
  830. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) <=0){
  831. return StrUtil.EMPTY;
  832. }
  833. AlipayTradeRefundResponse response;
  834. //支付宝退款
  835. AlipayClient alipayClient = AliPayClientFactory.getAlipayClient(Optional.ofNullable(orderDon.getShopId()).orElse(ShopConfig.ZFB_DEFAULT_APP_ID));
  836. AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
  837. AlipayTradeRefundModel model = new AlipayTradeRefundModel();
  838. //支付宝交易号
  839. model.setTradeNo(orderDon.getTransactionId());
  840. model.setRefundAmount(refundReq.getRefundMoney().divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_EVEN).toString());
  841. model.setQueryOptions(List.of("gmt_refund_pay"));
  842. long time = System.currentTimeMillis();
  843. //退款订单号
  844. String outRefundNo = Codec.DoDigest.custom()
  845. .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
  846. .setStringData(time + String.valueOf(orderDon.getId()))
  847. .toHexString();
  848. //退款请求号
  849. model.setOutRequestNo(outRefundNo);
  850. request.setBizModel(model);
  851. String shopId = orderDon.getShopId();
  852. ShopConfig shopConfig = shopConfigMapper.selectOne(Wrappers.lambdaQuery(ShopConfig.class).eq(ShopConfig::getAppId, orderDon.getShopId()));
  853. if (shopId != null && shopConfig != null && shopConfig.getIsCert()) {
  854. response = alipayClient.certificateExecute(request);
  855. } else {
  856. response = alipayClient.execute(request);
  857. }
  858. if (!response.isSuccess()) throw BusinessRuntimeException.getInstance("退款失败,e:{0}", response.getSubMsg());
  859. // AliPayRefundRep aliPayRefundRep = Jsons.parseObject(response.getBody(), AliPayRefundRep.class);
  860. // AliPayRefundRep.AlipayTradeRefundResponse res = aliPayRefundRep.getResponse();
  861. // orderDon.setRefundMoney(res.getRefundFee().multiply(BigDecimal.valueOf(100)));
  862. return outRefundNo;
  863. }
  864. /**
  865. * 校验订单是否符合退款操作
  866. */
  867. private void checkOrderRefund(OrderDon orderDon, GoodsDon goodsDon, GoodsDonSku sku, OrderRefundReq refundReq) {
  868. if (orderDon == null) {
  869. throw BusinessRuntimeException.getInstance("订单不存在");
  870. }
  871. BigDecimal orderDonRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  872. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  873. String refundType = refundReq.getRefundType();
  874. // if (orderDon.getType() == OrderDon.Type.BALANCE && !OrderDon.Type.BALANCE.getType().equals(refundType)) {
  875. // throw BusinessRuntimeException.getInstance("余额支付的订单不支持金额退款");
  876. // }
  877. if (OrderDon.Status.refund == orderDon.getStatus()) {
  878. throw BusinessRuntimeException.getInstance("该订单已退款");
  879. }
  880. if (OrderDon.Status.noPayment == orderDon.getStatus() || OrderDon.Status.close == orderDon.getStatus()) {
  881. throw BusinessRuntimeException.getInstance("订单{0}状态不支持退款", orderDon.getStatus());
  882. }
  883. if (goodsDon.getId() == Constant.NETFLIX_GID) {
  884. Integer selectCount = netflixUserChangeOtherTicketRecordMapper.selectCount(Wrappers.lambdaQuery(NetflixUserChangeOtherTicketRecord.class)
  885. .eq(NetflixUserChangeOtherTicketRecord::getOrderId, orderDon.getId()));
  886. if (selectCount > 0) {
  887. throw BusinessRuntimeException.getInstance("该奈飞车票已替换其他车票,无法退款");
  888. }
  889. }
  890. if (goodsDon.getType() == 1 && sku != null) {
  891. //虚拟原订单是否已过期
  892. Integer months = sku.getMonths();
  893. Integer days = sku.getDays();
  894. Integer num = orderDon.getNum();
  895. DateTime now = DateTime.now();
  896. DateTime endTime;
  897. if (days != null && days > 0) {
  898. endTime = DateUtil.offsetDay(orderDon.getCreatedTime(), days * num);
  899. } else {
  900. endTime = DateUtil.offsetMonth(orderDon.getCreatedTime(), months * num);
  901. }
  902. if (now.isAfter(endTime)) {
  903. throw BusinessRuntimeException.getInstance("该订单车票已过期");
  904. }
  905. if (orderDon.getOrderType() == 1) {
  906. //是否有其他付款订单是否过期
  907. OrderDon otherOrder = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  908. .eq(OrderDon::getRelationId, orderDon.getRelationId())
  909. .eq(OrderDon::getUserId, orderDon.getUserId())
  910. .ne(OrderDon::getId, orderDon.getId())
  911. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  912. .eq(OrderDon::getOrderType, 2)
  913. .orderByDesc(OrderDon::getId)
  914. .last("limit 1"));
  915. if (otherOrder != null) {
  916. throw BusinessRuntimeException.getInstance("该笔订单存在续费订单,请先退掉续费订单");
  917. }
  918. }
  919. }
  920. BigDecimal refundMoney = refundReq.getRefundMoney();
  921. BigDecimal refundBalance = refundReq.getRefundBalance();
  922. BigDecimal money = orderDon.getMoney();
  923. BigDecimal balance = orderDon.getBalance();
  924. //余额退款
  925. if (OrderDon.Type.BALANCE.getType().equals(refundType)) {
  926. refundMoney = orderDonRefundBalance.add(refundMoney);
  927. if (OrderDon.Type.BALANCE != orderDon.getType() && refundMoney.compareTo(money) > 0) {
  928. throw BusinessRuntimeException.getInstance("退款余额大于订单支付金额");
  929. }
  930. orderDon.setRefundBalance(refundMoney);
  931. } else if (OrderRefundReq.RefundType.bxj.name().equals(refundType)) {
  932. balance = balance.add(money);
  933. if (refundBalance.compareTo(balance) > 0) {
  934. throw BusinessRuntimeException.getInstance("退款余额大于订单总金额");
  935. }
  936. refundBalance = refundBalance.add(orderDonRefundBalance);
  937. orderDon.setRefundBalance(refundBalance);
  938. refundMoney = orderDonRefundMoney.add(refundMoney);
  939. if (refundMoney.compareTo(money) > 0) {
  940. throw BusinessRuntimeException.getInstance("退款金额大于订单支付金额");
  941. }
  942. orderDon.setRefundMoney(refundMoney);
  943. } else {
  944. //退金额
  945. refundMoney = orderDonRefundMoney.add(refundMoney);
  946. if (refundMoney.compareTo(money) > 0) {
  947. throw BusinessRuntimeException.getInstance("退款金额大于订单支付金额");
  948. }
  949. orderDon.setRefundMoney(refundMoney);
  950. }
  951. //礼品卡是否已使用
  952. GiftCardUserRecord giftCardUserRecord = null;
  953. if (goodsDon.getSpecialType() != null && goodsDon.getSpecialType() == GoodsDon.SpecialType.giftCard) {
  954. Integer count = giftCardUserRecordMapper.selectCount(Wrappers.lambdaQuery(GiftCardUserRecord.class)
  955. .eq(GiftCardUserRecord::getIsUsed, 1)
  956. .eq(GiftCardUserRecord::getOrderId, orderDon.getId()));
  957. if (count > 0) {
  958. throw BusinessRuntimeException.getInstance("该礼品卡已使用无法退款");
  959. }
  960. }
  961. if (!redisService.setNx(String.format("%s", refundReq.getOrderId()), refundReq.getOrderId(), 10l)) {
  962. throw BusinessRuntimeException.getInstance("请勿重复点击,正在退款中..");
  963. }
  964. //礼品卡购买状态
  965. if (giftCardUserRecord != null) {
  966. giftCardUserRecord.setIsPay(false);
  967. giftCardUserRecordMapper.updateById(giftCardUserRecord);
  968. }
  969. //校验续费升级规格
  970. checkMirrorRenewSku(orderDon);
  971. }
  972. /**
  973. * 退款后 处理关联
  974. */
  975. 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, List<Long> dpRelationIds) {
  976. orderRefundService.refundRecord(orderDon, refundMoney, refundBalance, operator, goodsDon, sku, outNo, refundType, chatImg);
  977. //退款一次
  978. goodsDonStockService.upStockRelate(null, orderDon.getId(), "refund");
  979. try {
  980. if (!orderDon.getIsDp()) {
  981. //虚物订单退款,清出车队,车票变为已过期
  982. orderCommonService.clearUnrealGoodsDetail(orderDon, goodsDon.getType(), sku);
  983. }
  984. } catch (Exception e) {
  985. log.error("清除车票错误:{}", StringUtil.getErrorText(e));
  986. }
  987. //若存在优惠券使用,退还优惠券
  988. if (orderDon.getCouponUserId() != 0) {
  989. couponFontService.updateOrderDonCouponStatus(orderDon);
  990. }
  991. //退等比例
  992. if (isOnly != null && isOnly) {
  993. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.refund, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  994. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  995. orderDon.setRefundBalance(orderDonRefundBalance.add(refundBalance));
  996. }
  997. //若存在余额支付,退还余额
  998. // if (isOnly == null && orderDon.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  999. // BigDecimal addBalance = orderDon.getBalance();
  1000. // //需额外扣除余额
  1001. // if (deductBalance != null && deductBalance.compareTo(BigDecimal.ZERO) > 0) {
  1002. // addBalance = addBalance.subtract(deductBalance);
  1003. // }
  1004. // userBenefitsService.addUserBalance(orderDon.getUserId(), addBalance, UserBalanceSourceRecord.Source.refund, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  1005. // }
  1006. //是否全额退款
  1007. // BigDecimal orderDonRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  1008. // BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  1009. // if (orderDonRefundMoney.add(orderDonRefundBalance).compareTo(orderDon.getMoney().add(Optional.ofNullable(orderDon.getBalance()).orElse(BigDecimal.ZERO))) == 0) {
  1010. // //是否使用银河币支付
  1011. // OrderDonGalaxyCoinRecord orderDonGalaxyCoinRecord = orderDonGalaxyCoinRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonGalaxyCoinRecord.class)
  1012. // .eq(OrderDonGalaxyCoinRecord::getSource, OrderDonGalaxyCoinRecord.Source.ordinary.ordinal())
  1013. // .eq(OrderDonGalaxyCoinRecord::getOrderId, orderDon.getId())
  1014. // .last("limit 1"));
  1015. // if (orderDonGalaxyCoinRecord != null) {
  1016. // //有效时,返还银河币 并记录
  1017. // userGalaxyCoinService.recordOrderRefundGalaxyCoinIfValid(orderDon.getId(), orderDonGalaxyCoinRecord.getUserId(), orderDonGalaxyCoinRecord.getGalaxyCoin().abs(), OrderDonGalaxyCoinRecord.Source.ordinary);
  1018. // }
  1019. // }
  1020. //扣除 该笔订单产生的返现银河币
  1021. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) > 0) {
  1022. userGalaxyCoinService.subOrderGenerateGalaxyCoin(orderDon.getId(), OrderDonGalaxyCoinRecord.Source.ordinary);
  1023. }
  1024. //余额现金混合退款
  1025. if (OrderRefundReq.RefundType.bxj.name().equals(refundType)) {
  1026. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.refund, null, orderDon.getId(), orderDon.getPayTitle() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  1027. }
  1028. try {
  1029. marketFrontService.subSpecificChanceNum(orderDon.getUserId(), orderDon.getId(), orderDon.getGoodsId(), orderDon.getUpdateTime());
  1030. if (goodsDon.getType() == 2 && !orderDon.getIsDistribute()) {
  1031. equipmentDistributeService.subDistributeBenefitsChance(orderDon.getUserId(), orderDon.getId());
  1032. //扣除用户自身实物权益
  1033. userRealOrderBenefitsService.deductUserRealGoodsBenefits(orderDon.getId());
  1034. }
  1035. } catch (Exception e) {
  1036. log.error("wx减少抽奖机会错误,orderId:{},error:{}", orderDon.getId(), e);
  1037. }
  1038. if (OrderDon.Type.BALANCE.getType().equals(refundType)) {
  1039. if (isOnly == null && orderDon.getMoney().compareTo(BigDecimal.ZERO) > 0) {
  1040. userBenefitsService.addUserBalance(orderDon.getUserId(), refundMoney, UserBalanceSourceRecord.Source.refund, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  1041. }
  1042. } else {
  1043. //余额退款不需要扣除积分
  1044. //分销提成积分扣除
  1045. deductDsPoints(orderDon);
  1046. //店铺 分销提成金额扣除
  1047. yhShopDistributeService.deductDsMoney(orderDon);
  1048. //镜像店铺 分销提成金额扣除
  1049. deductUserMirrorShopMoney(orderDon);
  1050. }
  1051. if (orderDon.getIsFixedDistribute()) {
  1052. //商务提成 因订单退款去掉
  1053. UserDistributeBusinessOrderDonRecord record = businessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(UserDistributeBusinessOrderDonRecord.class)
  1054. .eq(UserDistributeBusinessOrderDonRecord::getOrderId, orderDon.getId())
  1055. .eq(UserDistributeBusinessOrderDonRecord::getStatus, UserDistributeBusinessOrderDonRecord.Status.success)
  1056. .last("limit 1"));
  1057. if (record != null) {
  1058. record.setStatus(UserDistributeBusinessOrderDonRecord.Status.refund);
  1059. businessOrderDonRecordMapper.updateById(record);
  1060. }
  1061. }
  1062. //店铺商务提成
  1063. if (orderDon.getYhsId() != null && orderDon.getYhsId() > 0) {
  1064. YhShopUserDistributeBusinessOrderDonRecord shop_record = yhShopBusinessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(YhShopUserDistributeBusinessOrderDonRecord.class)
  1065. .eq(YhShopUserDistributeBusinessOrderDonRecord::getOrderId, orderDon.getId())
  1066. .eq(YhShopUserDistributeBusinessOrderDonRecord::getStatus, YhShopUserDistributeBusinessOrderDonRecord.Status.success)
  1067. .last("limit 1"));
  1068. if (shop_record != null) {
  1069. shop_record.setStatus(YhShopUserDistributeBusinessOrderDonRecord.Status.refund);
  1070. yhShopBusinessOrderDonRecordMapper.updateById(shop_record);
  1071. }
  1072. }
  1073. //是否是优惠加购关联订单
  1074. if (orderDon.getIsDp()) {
  1075. OrderDiscountPlusPurchaseSkuRelation discountPlusPurchaseSkuRelation = orderDiscountPlusPurchaseSkuRelationMapper.selectOne(Wrappers.lambdaQuery(OrderDiscountPlusPurchaseSkuRelation.class)
  1076. .eq(OrderDiscountPlusPurchaseSkuRelation::getOrderId, orderDon.getId()).last("limit 1"));
  1077. if (discountPlusPurchaseSkuRelation != null) {
  1078. //选择清除加购车票
  1079. if (CollUtil.isNotEmpty(dpRelationIds)) {
  1080. try {
  1081. List<GroupsRelation> groupsRelations = relationMapper.selectList(Wrappers.lambdaQuery(GroupsRelation.class)
  1082. .eq(GroupsRelation::getUserId, orderDon.getUserId())
  1083. .in(GroupsRelation::getId, dpRelationIds));
  1084. log.info("优惠加购订单orderId:{}退款,清除相关车票relation_ids:{}", orderDon.getId(), dpRelationIds);
  1085. groupsRelations.forEach(relation -> relationClearService.clearTicket(relation, UserTicketClearedRecord.Source.dp));
  1086. } catch (Exception e) {
  1087. }
  1088. }
  1089. String plusOrderIds = discountPlusPurchaseSkuRelation.getPlusOrderIds();
  1090. if (StrUtil.isNotBlank(plusOrderIds)) {
  1091. try {
  1092. log.info("关闭优惠加购orderId:{}关联实物订单", orderDon.getId());
  1093. List<Long> plusOrderIdList = Jsons.parseList(plusOrderIds, Long.class);
  1094. List<OrderDon> relate_orderDons = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class)
  1095. .in(OrderDon::getId, plusOrderIdList)
  1096. .notIn(OrderDon::getStatus, Constant.noOrderStatus));
  1097. relate_orderDons.forEach(relate_o -> {
  1098. //扣除用户自身实物权益
  1099. userRealOrderBenefitsService.deductUserRealGoodsBenefits(relate_o.getId());
  1100. });
  1101. orderDonMapper.update(null, Wrappers.lambdaUpdate(OrderDon.class)
  1102. .set(OrderDon::getStatus, OrderDon.Status.refund)
  1103. .in(OrderDon::getId, plusOrderIdList)
  1104. .ne(OrderDon::getStatus, OrderDon.Status.refund));
  1105. } catch (Exception e) {
  1106. }
  1107. }
  1108. }
  1109. }
  1110. //同步车票退款 重购记录
  1111. TASK_POOL.execute(() -> {
  1112. GroupsRelationExpiryRecord groupsRelationExpiryRecord = groupsRelationExpiryRecordService.getOne(Wrappers.lambdaQuery(GroupsRelationExpiryRecord.class)
  1113. .in(GroupsRelationExpiryRecord::getReBuyOrderId, orderDon.getId())
  1114. .eq(GroupsRelationExpiryRecord::getRelationId, orderDon.getRelationId()).last("limit 1"));
  1115. if (groupsRelationExpiryRecord == null) {
  1116. log.info("订单orderId:{}退款,同步是否有重购记录不是直接续费车票", orderDon.getId());
  1117. List<GroupsRelationExpiryRecord> groupsRelationExpiryRecords = groupsRelationExpiryRecordService.list(Wrappers.lambdaQuery(GroupsRelationExpiryRecord.class)
  1118. .in(GroupsRelationExpiryRecord::getReBuyOrderId, orderDon.getId()));
  1119. log.info("订单orderId:{}退款,重购记录不是直接续费车票大小:{}", groupsRelationExpiryRecords.size());
  1120. if (CollUtil.isNotEmpty(groupsRelationExpiryRecords)) {
  1121. groupsRelationExpiryRecords.forEach(data -> {
  1122. data.setIsReBuy(false);
  1123. });
  1124. groupsRelationExpiryRecordService.saveOrUpdateBatch(groupsRelationExpiryRecords);
  1125. }
  1126. }
  1127. if (groupsRelationExpiryRecord != null) {
  1128. groupsRelationExpiryRecord.setIsReBuy(false);
  1129. groupsRelationExpiryRecordService.saveOrUpdate(groupsRelationExpiryRecord);
  1130. }
  1131. });
  1132. //是否是礼品卡 现金支付订单
  1133. BigDecimal gcCash = orderDon.getGcCash();
  1134. if (gcCash != null && gcCash.compareTo(BigDecimal.ZERO) > 0) {
  1135. giftCardOrderUseRecordService.returnGiftCardCash(orderDon.getId());
  1136. }
  1137. //清除礼品卡
  1138. if (goodsDon.getSpecialType() != null && goodsDon.getSpecialType() == GoodsDon.SpecialType.giftCard) {
  1139. giftCardUserRecordMapper.update(null, Wrappers.lambdaUpdate(GiftCardUserRecord.class)
  1140. .set(GiftCardUserRecord::getIsPay, 0)
  1141. .eq(GiftCardUserRecord::getOrderId, orderDon.getId()));
  1142. }
  1143. //是否是分销订单
  1144. //处理下级渠道分销提成
  1145. handleSubRewards(orderDon);
  1146. //是否是用户套餐优惠权益订单
  1147. if (orderDon.getGoodsId() == 15) {
  1148. UserBenefitsComboRelationRecord userBenefitsComboRelationRecord = userBenefitsComboRelationRecordMapper.selectOne(Wrappers.lambdaQuery(UserBenefitsComboRelationRecord.class)
  1149. .eq(UserBenefitsComboRelationRecord::getOrderId, orderDon.getId()).last("limit 1"));
  1150. if (userBenefitsComboRelationRecord != null) {
  1151. try {
  1152. String relationIds = userBenefitsComboRelationRecord.getRelationIds();
  1153. List<Long> relationIdList = Jsons.parseList(relationIds, Long.class);
  1154. //清空车票或减少车票时间
  1155. relationIdList.forEach(relationId -> {
  1156. orderCommonService.clearUserTicketTime(relationId);
  1157. });
  1158. } catch (Exception e) {
  1159. }
  1160. }
  1161. }
  1162. //HBO GO退款,车队上架
  1163. setUpIfEmpty(orderDon.getGoodsId(), orderDon.getRelationId());
  1164. if (orderDon.getGoodsId() == Constant.NETFLIX_GID) {
  1165. List<Long> userIdList = userBindRelationService.getRelationUserIdList(orderDon.getUserId(), null);
  1166. NetflixUserAccountSubmitRecoverRecord recoverRecord = netflixUserAccountSubmitRecoverRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  1167. .eq(NetflixUserAccountSubmitRecoverRecord::getRelationId, orderDon.getRelationId())
  1168. .in(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList)
  1169. .eq(NetflixUserAccountSubmitRecoverRecord::getStatus, 0)
  1170. .last("limit 1"));
  1171. if (recoverRecord != null) {
  1172. recoverRecord.setStatus(3);
  1173. netflixUserAccountSubmitRecoverRecordMapper.updateById(recoverRecord);
  1174. }
  1175. }
  1176. //GPT独立会员
  1177. if (orderDon.getGoodsId() == Constant.GPT_PLUS_GID && sku.getNum() == 1) {
  1178. subRechargeNumOrder(orderDon.getUserId(), orderDon.getRelationId(), sku.getMonths(), operator);
  1179. }
  1180. }
  1181. //处理下级渠道分销提成
  1182. public void handleSubRewards(OrderDon orderDon) {
  1183. //是否是分销订单
  1184. //处理下级渠道分销提成
  1185. if (orderDon.getIsDistribute()) {
  1186. UserDistributeSub subRelate = userDistributeSubMapper.getSubRelate(orderDon.getUserId());
  1187. if (subRelate != null) {
  1188. List<UserDistributeSubWaiting> subWaitings = subWaitingMapper.selectList(Wrappers.lambdaQuery(UserDistributeSubWaiting.class)
  1189. .eq(UserDistributeSubWaiting::getSubUserId, subRelate.getSubUserId())
  1190. .eq(UserDistributeSubWaiting::getSendStatus, UserDistributeSubWaiting.Status.waiting));
  1191. if (CollUtil.isNotEmpty(subWaitings)) {
  1192. List<UserDistributeSubRewards> userDistributeSubRewards = userDistributeSubRewardsMapper.selectList(null);
  1193. Map<Integer, List<UserDistributeSubRewards>> rewardLevelMap = userDistributeSubRewards.stream().collect(Collectors.groupingBy(UserDistributeSubRewards::getLevel));
  1194. subWaitings.forEach(wait -> {
  1195. List<UserDistributeSubRewards> thisLevelList = rewardLevelMap.get(wait.getLevel());
  1196. if (thisLevelList == null) {
  1197. return;
  1198. }
  1199. UserDistributeSubRewards thisLevel = thisLevelList.get(0);
  1200. Integer months = thisLevel.getMonths();
  1201. BigDecimal subOrderMoney = Optional.ofNullable(orderDonMapper.selectSubChannelOrderMoney(wait.getSubUserId(), subRelate.getCreatedTime(), DateUtil.offsetMonth(subRelate.getCreatedTime(), months))).orElse(BigDecimal.ZERO);
  1202. if (subOrderMoney.compareTo(thisLevel.getTargetAmount()) < 0) {
  1203. subWaitingMapper.update(null, Wrappers.lambdaUpdate(UserDistributeSubWaiting.class)
  1204. .set(UserDistributeSubWaiting::getSendStatus, UserDistributeSubWaiting.Status.close)
  1205. .eq(UserDistributeSubWaiting::getSendStatus, UserDistributeSubWaiting.Status.waiting)
  1206. .eq(UserDistributeSubWaiting::getId, wait.getId()));
  1207. }
  1208. });
  1209. }
  1210. }
  1211. }
  1212. }
  1213. /**
  1214. * 退款 分销提成积分扣除
  1215. */
  1216. public void deductDsPoints(OrderDon orderDon) {
  1217. if (orderDon.getIsDistribute()) {
  1218. DistributeWaitingSendPoints distributeWaitingSendPoints = distributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(DistributeWaitingSendPoints.class).eq(DistributeWaitingSendPoints::getOrderId, orderDon.getId()).eq(DistributeWaitingSendPoints::getIsVip,Boolean.FALSE).last("limit 1"));
  1219. if (distributeWaitingSendPoints != null) {
  1220. BigDecimal money = orderDon.getMoney();
  1221. BigDecimal refundMoney = orderDon.getRefundMoney();
  1222. //已发送 发送中 部分 全额退款
  1223. DistributeWaitingSendPoints.Status sendStatus = distributeWaitingSendPoints.getSendStatus();
  1224. BigDecimal points = distributeWaitingSendPoints.getPoints();
  1225. if (sendStatus == DistributeWaitingSendPoints.Status.waiting) {
  1226. //实物设备退款就清0
  1227. if (refundMoney.compareTo(money) == 0 || orderDon.getGoodsId() == 15) {
  1228. //待发送状态 全额退款
  1229. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  1230. distributeWaitingSendPoints.setRefundPoints(points);
  1231. distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
  1232. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1233. return;
  1234. }
  1235. Integer thisGoodsRate = distributeWaitingSendPoints.getRate();
  1236. if (thisGoodsRate == null || thisGoodsRate == 0) {
  1237. thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
  1238. }
  1239. if (thisGoodsRate > 0) {
  1240. BigDecimal refundRate = refundMoney.divide(money, 2, RoundingMode.DOWN);
  1241. //退掉比例的提成
  1242. BigDecimal needSubPoints = points.multiply(refundRate);
  1243. distributeWaitingSendPoints.setRefundPoints(needSubPoints);
  1244. //剩余积分
  1245. BigDecimal remainPoints = points.subtract(needSubPoints);
  1246. distributeWaitingSendPoints.setPoints(remainPoints);
  1247. //原先获取积分也扣除
  1248. if (distributeWaitingSendPoints.getOriPoints().compareTo(BigDecimal.ZERO) > 0) {
  1249. BigDecimal oriNeedSubPoints = distributeWaitingSendPoints.getOriPoints().multiply(refundRate);
  1250. distributeWaitingSendPoints.setOriPoints(distributeWaitingSendPoints.getOriPoints().subtract(oriNeedSubPoints));
  1251. }
  1252. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1253. }
  1254. } else if (sendStatus == DistributeWaitingSendPoints.Status.success) {
  1255. //已发送的提成 部分退款 全额退款 需要扣除用户积分
  1256. //扣除固定推广者积分
  1257. //实物设备退款就清0
  1258. if (refundMoney.compareTo(money) == 0 || orderDon.getGoodsId() == 15) {
  1259. userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), points);
  1260. distributeWaitingSendPoints.setRefundPoints(points);
  1261. distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
  1262. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  1263. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1264. return;
  1265. }
  1266. Integer thisGoodsRate = distributeWaitingSendPoints.getRate();
  1267. if (thisGoodsRate == null || thisGoodsRate == 0) {
  1268. thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
  1269. }
  1270. if (thisGoodsRate > 0) {
  1271. BigDecimal refundRate = refundMoney.divide(money, 2, RoundingMode.DOWN);
  1272. //退掉比例的提成
  1273. BigDecimal needSubPoints = points.multiply(refundRate);
  1274. userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), needSubPoints);
  1275. //部分退款
  1276. distributeWaitingSendPoints.setRefundPoints(needSubPoints);
  1277. distributeWaitingSendPoints.setPoints(points.subtract(needSubPoints));
  1278. //原先获取积分也扣除
  1279. if (distributeWaitingSendPoints.getOriPoints().compareTo(BigDecimal.ZERO) > 0) {
  1280. BigDecimal oriNeedSubPoints = distributeWaitingSendPoints.getOriPoints().multiply(refundRate);
  1281. distributeWaitingSendPoints.setOriPoints(distributeWaitingSendPoints.getOriPoints().subtract(oriNeedSubPoints));
  1282. }
  1283. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1284. }
  1285. }
  1286. }
  1287. }
  1288. }
  1289. @Override
  1290. public void refundPriceDiffer(OrderRefundReq orderRefundReq) throws Exception {
  1291. Long orderId = orderRefundReq.getOrderId();
  1292. OrderDon orderDon = orderDonMapper.selectById(orderId);
  1293. if (orderDon == null) {
  1294. throw BusinessRuntimeException.getInstance("订单不存在");
  1295. }
  1296. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  1297. throw BusinessRuntimeException.getInstance("该订单是0元订单,无法补差价");
  1298. }
  1299. if (Constant.noOrderAllStatus.contains(orderDon.getStatus().name())) {
  1300. throw BusinessRuntimeException.getInstance("订单不是已支付状态");
  1301. }
  1302. //默认补差价余额
  1303. String refundType = Optional.ofNullable(orderRefundReq.getRefundType()).orElse("balance");
  1304. BigDecimal refundMoney = orderRefundReq.getRefundMoney();
  1305. BigDecimal orderRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  1306. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  1307. if (refundMoney.add(orderRefundMoney).add(orderDonRefundBalance).compareTo(orderDon.getRealMoney()) >= 0) {
  1308. throw BusinessRuntimeException.getInstance("补差价已达到该订单付款金额");
  1309. }
  1310. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  1311. GoodsDonSku sku = null;
  1312. if (orderDon.getSkuId() != null) {
  1313. sku = skuMapper.selectById(orderDon.getSkuId());
  1314. }
  1315. orderDon.setRefundDesc("补差价");
  1316. String outNo = StrUtil.EMPTY;
  1317. if ("money".equals(refundType)) {
  1318. if (refundMoney == null || refundMoney.compareTo(BigDecimal.ZERO) <= 0) {
  1319. throw BusinessRuntimeException.getInstance("请输入正确的差价金额");
  1320. }
  1321. if (refundMoney.compareTo(orderDon.getMoney()) >= 0) {
  1322. throw BusinessRuntimeException.getInstance("补差价金额应不大于订单金额");
  1323. }
  1324. //退款
  1325. orderRefundReq.setIsDiffer(true);
  1326. outNo = orderRefundService.centerRefund(orderRefundReq, orderDon);
  1327. orderDon.setRefundMoney(orderRefundMoney.add(refundMoney));
  1328. orderDonMapper.updateById(orderDon);
  1329. //补差价金额 扣除对应分销提成金额
  1330. orderDon.setRefundMoney(refundMoney);
  1331. deductDsPoints(orderDon);
  1332. //店铺分销提成金额扣除
  1333. yhShopDistributeService.deductDsMoney(orderDon);
  1334. } else {
  1335. BigDecimal refundBalance = refundMoney;
  1336. if (refundBalance == null || refundBalance.compareTo(BigDecimal.ZERO) <= 0 || refundBalance.compareTo(orderDon.getMoney()) > 0) {
  1337. throw BusinessRuntimeException.getInstance("请输入正确的差价金额");
  1338. }
  1339. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.price_differ, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.price_differ.getDesc(), true);
  1340. orderDon.setRefundBalance(orderDonRefundBalance.add(refundBalance));
  1341. orderDonMapper.updateById(orderDon);
  1342. }
  1343. orderRefundService.refundRecord(orderDon, refundMoney, orderRefundReq.getRefundBalance(), orderRefundReq.getOperator(), goodsDon, sku, outNo, refundType, null);
  1344. }
  1345. @Override
  1346. @Transactional(rollbackFor = Throwable.class)
  1347. public void clearBalanceToRefundMoney(OrderBalanceRefundReq refundReq) throws Exception {
  1348. Long refundOrderId = refundReq.getRefundOrderId();
  1349. BigDecimal refundMoney = refundReq.getRefundMoney();
  1350. RefundOrderDon refundOrderDon = refundOrderDonMapper.selectById(refundOrderId);
  1351. if (!"balance".equals(refundOrderDon.getRefundMethod())) {
  1352. throw BusinessRuntimeException.getInstance("该记录不是余额退款类型");
  1353. }
  1354. Long orderId = refundOrderDon.getOrderId();
  1355. OrderDon orderDon = orderDonMapper.selectById(orderId);
  1356. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  1357. throw BusinessRuntimeException.getInstance("该记录对应的订单无实际支付金额");
  1358. }
  1359. if (refundOrderDon.getIsClearBalance()) {
  1360. throw BusinessRuntimeException.getInstance("该笔退款余额记录已退款");
  1361. }
  1362. BigDecimal refundFee = refundOrderDon.getRefundFee();
  1363. //默认退全部余额
  1364. if (refundMoney != null) {
  1365. refundFee = refundMoney;
  1366. }
  1367. BigDecimal money = orderDon.getMoney();
  1368. //若退款余额 大于退款金额 将退款余额至为 退款金额
  1369. if (refundFee.compareTo(money) > 0) {
  1370. refundFee = money;
  1371. }
  1372. User user = userMapper.selectById(orderDon.getUserId());
  1373. if (user.getBalance().compareTo(refundFee) < 0) {
  1374. throw BusinessRuntimeException.getInstance("用户余额不足,无法扣除对应退款余额");
  1375. }
  1376. int update = userMapper.update(null, Wrappers.lambdaUpdate(User.class)
  1377. .set(User::getBalance, user.getBalance().subtract(refundFee))
  1378. .eq(User::getId, user.getId())
  1379. .eq(User::getBalance, user.getBalance()));
  1380. if (update == 0) {
  1381. throw BusinessRuntimeException.getInstance("扣除用户退款余额失败,请重试...");
  1382. }
  1383. OrderRefundReq orderRefundReq = new OrderRefundReq();
  1384. orderRefundReq.setOrderId(orderId);
  1385. orderRefundReq.setRefundMoney(refundFee);
  1386. orderRefundReq.setRefundType("money");
  1387. String outNo = orderRefundService.centerRefund(orderRefundReq, orderDon);
  1388. orderDon.setRefundBalance(orderDon.getRefundBalance().subtract(refundFee));
  1389. BigDecimal orderRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  1390. orderDon.setRefundMoney(orderRefundMoney.add(refundFee));
  1391. orderDonMapper.updateById(orderDon);
  1392. refundOrderDon.setOutRefundNo(outNo);
  1393. refundOrderDon.setIsClearBalance(true);
  1394. refundOrderDonMapper.updateById(refundOrderDon);
  1395. }
  1396. /**
  1397. * 寻找该车队空余车位
  1398. */
  1399. public GroupsRelation getRelationThisTrips(Long userId, Long groupsId, Integer retryNum) {
  1400. //寻找快满编车队进行占座
  1401. GroupsRelation relation = relationMapper.selectRandomOneRelationByGroupsId(groupsId);
  1402. if (relation == null) {
  1403. throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  1404. }
  1405. Long relationId = relation.getId();
  1406. if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
  1407. if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  1408. retryNum++;
  1409. return getRelationThisTrips(userId, groupsId, retryNum);
  1410. }
  1411. int count = groupsMapper.decrAvailableNum(relation.getGroupsId());
  1412. if (count == 0) {
  1413. log.error("车位异常 groupId:{}", groupsId);
  1414. groupsMapper.updateAvailableNum(groupsId);
  1415. throw new BusinessRuntimeException("车位异常");
  1416. }
  1417. return relation;
  1418. }
  1419. private GroupsRelation getChatGPTOutsideRelation(Long userId, Long groupsId, Integer relationNum, Integer retryNum) {
  1420. //寻找快满编车队额外座位
  1421. GroupsRelation relation = relationMapper.selectOutsideRelationByGroupsId(groupsId, relationNum);
  1422. if (relation == null) {
  1423. relation = new GroupsRelation();
  1424. relation.setStatus(GroupsRelation.Status.outside);
  1425. relation.setGroupsId(groupsId);
  1426. GroupsRelation maxNumRelation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getGroupsId, groupsId).orderByDesc(GroupsRelation::getNum).last("limit 1"));
  1427. relation.setNum(maxNumRelation.getNum() + 1);
  1428. relationMapper.insert(relation);
  1429. return relation;
  1430. }
  1431. Long relationId = relation.getId();
  1432. if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
  1433. if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  1434. retryNum++;
  1435. return getChatGPTOutsideRelation(userId, groupsId, relationNum, retryNum);
  1436. }
  1437. return relation;
  1438. }
  1439. private void checkMirrorRenewSku(OrderDon orderDon) {
  1440. Long skuId = orderDon.getSkuId();
  1441. Long orderId = orderDon.getId();
  1442. OrderDonRenewRecord orderDonRenewRecord = orderDonRenewRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonRenewRecord.class)
  1443. .eq(OrderDonRenewRecord::getOrderId, orderId)
  1444. .last("limit 1"));
  1445. if (orderDonRenewRecord != null) {
  1446. //gpt
  1447. if (orderDon.getGoodsId() == 18) {
  1448. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class)
  1449. .eq(ChatgptUser::getRelationId, orderDon.getRelationId())
  1450. .last("limit 1"));
  1451. Long presentRenewSkuId = chatgptUser.getRenewSkuId();
  1452. if (presentRenewSkuId != null) {
  1453. //存在不同升级套餐
  1454. GoodsDonSku presentRenewSku = skuMapper.selectById(presentRenewSkuId);
  1455. if (!ObjectUtil.equal(presentRenewSkuId, skuId)) {
  1456. throw BusinessRuntimeException.getInstance("请先退掉用户目前续费升级的{0}规格", presentRenewSku.getSpecVal());
  1457. }
  1458. }
  1459. }
  1460. //claude pro
  1461. if (orderDon.getGoodsId() == 75) {
  1462. ClaudeUser claudeUser = claudeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeUser.class)
  1463. .eq(ClaudeUser::getRelationId, orderDon.getRelationId())
  1464. .last("limit 1"));
  1465. Long presentRenewSkuId = claudeUser.getRenewSkuId();
  1466. if (presentRenewSkuId != null) {
  1467. //存在不同升级套餐
  1468. GoodsDonSku presentRenewSku = skuMapper.selectById(presentRenewSkuId);
  1469. if (!ObjectUtil.equal(presentRenewSkuId, skuId)) {
  1470. throw BusinessRuntimeException.getInstance("请先退掉用户目前续费升级的{0}规格", presentRenewSku.getSpecVal());
  1471. }
  1472. }
  1473. }
  1474. }
  1475. }
  1476. private void clearExtraRelation(OrderDon orderDon) {
  1477. List<UserPayEquipmentReceiveBenefitsRecord> userPayEquipmentReceiveBenefitsRecords = receiveBenefitsRecordMapper.selectList(Wrappers.lambdaQuery(UserPayEquipmentReceiveBenefitsRecord.class)
  1478. .eq(UserPayEquipmentReceiveBenefitsRecord::getRealOrderId, orderDon.getId()));
  1479. userPayEquipmentReceiveBenefitsRecords.forEach(record -> {
  1480. Long skuId = record.getSkuId();
  1481. List<GroupsRelation> relations = relationMapper.selectExtraRelation(orderDon.getUserId(), skuId, record.getRelationId());
  1482. relations.forEach(relation -> {
  1483. //不是优惠加购
  1484. Integer count = orderDiscountPlusPurchaseSkuRelationMapper.selectCount(Wrappers.lambdaQuery(OrderDiscountPlusPurchaseSkuRelation.class)
  1485. .eq(OrderDiscountPlusPurchaseSkuRelation::getUserId, relation.getUserId())
  1486. .apply("JSON_CONTAINS(relation_ids,'" + relation.getId() + "')"));
  1487. if (count == 0) {
  1488. log.info("非优惠加购订单,直接清除userId:{}车票:{}", relation.getUserId(), relation.getId());
  1489. relationClearService.clearTicket(relation, UserTicketClearedRecord.Source.manual);
  1490. }
  1491. });
  1492. });
  1493. }
  1494. /**
  1495. * 扣除用户镜像店铺提成
  1496. */
  1497. private void deductUserMirrorShopMoney(OrderDon orderDon) {
  1498. UserMirrorShopDistributeWaitingSendPoints distributeWaitingSendPoints = userMirrorShopDistributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShopDistributeWaitingSendPoints.class)
  1499. .eq(UserMirrorShopDistributeWaitingSendPoints::getOrderId, orderDon.getId())
  1500. .last("limit 1"));
  1501. if (distributeWaitingSendPoints != null) {
  1502. BigDecimal money = orderDon.getMoney();
  1503. BigDecimal refundMoney = orderDon.getRefundMoney();
  1504. //已发送 发送中 部分 全额退款
  1505. UserMirrorShopDistributeWaitingSendPoints.Status sendStatus = distributeWaitingSendPoints.getSendStatus();
  1506. BigDecimal take_money = distributeWaitingSendPoints.getMoney();
  1507. if (sendStatus == UserMirrorShopDistributeWaitingSendPoints.Status.waiting) {
  1508. if (refundMoney.compareTo(money) == 0) {
  1509. //待发送状态 全额退款
  1510. distributeWaitingSendPoints.setSendStatus(UserMirrorShopDistributeWaitingSendPoints.Status.close);
  1511. distributeWaitingSendPoints.setRefundMoney(take_money);
  1512. distributeWaitingSendPoints.setMoney(BigDecimal.ZERO);
  1513. userMirrorShopDistributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1514. return;
  1515. }
  1516. Integer rate = distributeWaitingSendPoints.getRate();
  1517. if (rate > 0) {
  1518. BigDecimal needDeductMoney = refundMoney.multiply(BigDecimal.valueOf(rate).divide(BigDecimal.valueOf(100)));
  1519. distributeWaitingSendPoints.setRefundMoney(needDeductMoney);
  1520. //剩余积分
  1521. distributeWaitingSendPoints.setMoney(take_money.subtract(needDeductMoney));
  1522. userMirrorShopDistributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1523. }
  1524. } else if (sendStatus == UserMirrorShopDistributeWaitingSendPoints.Status.success) {
  1525. //已发送的提成 部分退款 全额退款 需要扣除用户积分
  1526. //扣除固定推广者积分
  1527. if (refundMoney.compareTo(money) == 0) {
  1528. //扣除店铺主 已有的提成金额
  1529. userBenefitsService.deductUserMirrorShopTakeMoney(orderDon.getId(), distributeWaitingSendPoints.getShopUserId(), take_money);
  1530. distributeWaitingSendPoints.setRefundMoney(take_money);
  1531. distributeWaitingSendPoints.setMoney(BigDecimal.ZERO);
  1532. distributeWaitingSendPoints.setSendStatus(UserMirrorShopDistributeWaitingSendPoints.Status.close);
  1533. userMirrorShopDistributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1534. return;
  1535. }
  1536. Integer rate = distributeWaitingSendPoints.getRate();
  1537. if (rate > 0) {
  1538. BigDecimal needDeductMoney = refundMoney.multiply(BigDecimal.valueOf(rate).divide(BigDecimal.valueOf(100)));
  1539. //扣除店铺主 已有的提成金额
  1540. userBenefitsService.deductUserMirrorShopTakeMoney(orderDon.getId(), distributeWaitingSendPoints.getShopUserId(), needDeductMoney);
  1541. //部分退款
  1542. distributeWaitingSendPoints.setRefundMoney(needDeductMoney);
  1543. distributeWaitingSendPoints.setMoney(take_money.subtract(needDeductMoney));
  1544. userMirrorShopDistributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1545. }
  1546. }
  1547. }
  1548. }
  1549. /**
  1550. * 清除多余车票
  1551. */
  1552. private void clearOtherChangeTicket(Long userId, Long relationId, GroupsRelation newRelation, Long skuId) {
  1553. UserTicketClearedRecord userTicketClearedRecord = userTicketClearedRecordMapper.selectOne(Wrappers.lambdaQuery(UserTicketClearedRecord.class)
  1554. .eq(UserTicketClearedRecord::getUserId, userId)
  1555. .eq(UserTicketClearedRecord::getRelationId, relationId)
  1556. .eq(UserTicketClearedRecord::getSource, UserTicketClearedRecord.Source.change_ticket)
  1557. .orderByDesc(UserTicketClearedRecord::getId)
  1558. .last("limit 1"));
  1559. if (userTicketClearedRecord != null) {
  1560. Long newRelationId = userTicketClearedRecord.getNewRelationId();
  1561. List<GroupsRelation> others = relationMapper.selectList(Wrappers.lambdaQuery(GroupsRelation.class)
  1562. .ne(GroupsRelation::getId, newRelationId)
  1563. .eq(GroupsRelation::getUserId, userId)
  1564. .eq(GroupsRelation::getStartTime, newRelation.getStartTime())
  1565. .eq(GroupsRelation::getExpiryTime, newRelation.getExpiryTime()));
  1566. others.forEach(r -> {
  1567. Long groupsId = r.getGroupsId();
  1568. GroupsTrips groupsTrips = groupsMapper.selectById(groupsId);
  1569. //排除 非同规格车票
  1570. if (!skuId.equals(groupsTrips.getSkuId())) {
  1571. return;
  1572. }
  1573. Long rid = r.getId();
  1574. Integer selectCount = orderDonMapper.selectCount(Wrappers.lambdaQuery(OrderDon.class)
  1575. .eq(OrderDon::getUserId, userId)
  1576. .eq(OrderDon::getRelationId, rid)
  1577. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus));
  1578. if (selectCount == 0) {
  1579. //不是优惠加购
  1580. Integer count = orderDiscountPlusPurchaseSkuRelationMapper.selectCount(Wrappers.lambdaQuery(OrderDiscountPlusPurchaseSkuRelation.class)
  1581. .eq(OrderDiscountPlusPurchaseSkuRelation::getUserId, userId)
  1582. .apply("JSON_CONTAINS(relation_ids,'" + rid + "')"));
  1583. if (count == 0) {
  1584. log.info("清除用户:{}多余车票", userId);
  1585. relationClearService.clearTicket(r, UserTicketClearedRecord.Source.manual);
  1586. }
  1587. }
  1588. });
  1589. }
  1590. }
  1591. /**
  1592. * 车队退款 自动上架
  1593. */
  1594. private void setUpIfEmpty(Long goodsId, Long relationId) {
  1595. if (goodsId == Constant.HBO_GO_GOODS_ID) {
  1596. GroupsRelation relation = relationMapper.selectById(relationId);
  1597. if (relation == null) {
  1598. return;
  1599. }
  1600. GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
  1601. if (groupsTrips == null) {
  1602. return;
  1603. }
  1604. if (groupsTrips.getStatus() == GroupsTrips.Status.down) {
  1605. log.info("HBO GO车队:{}存在退款,自动上架", groupsTrips.getId());
  1606. groupsMapper.update(null, Wrappers.lambdaUpdate(GroupsTrips.class)
  1607. .set(GroupsTrips::getStatus, GroupsTrips.Status.validity)
  1608. .eq(GroupsTrips::getId, groupsTrips.getId()));
  1609. }
  1610. }
  1611. }
  1612. /**
  1613. * 退款扣除代充次数
  1614. */
  1615. private void subRechargeNumOrder(Long userId, Long relationId, Integer subNum, String operator) {
  1616. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1617. GroupsRelation relation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getId, relationId).in(GroupsRelation::getUserId, userIdList).gt(GroupsRelation::getExpiryTime, DateTime.now()));
  1618. if (relation != null && relation.getRechargeStatus() != null) {
  1619. if (relation.getRechargeRemainNum() == 0) {
  1620. return;
  1621. }
  1622. int update = 0;
  1623. while (update == 0) {
  1624. Integer rechargeRemainNum = relation.getRechargeRemainNum();
  1625. if (subNum > rechargeRemainNum) {
  1626. subNum = rechargeRemainNum;
  1627. }
  1628. update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  1629. .set(GroupsRelation::getRechargeRemainNum, rechargeRemainNum - subNum)
  1630. .eq(GroupsRelation::getId, relationId)
  1631. .eq(GroupsRelation::getRechargeRemainNum, rechargeRemainNum));
  1632. if (update == 1) {
  1633. //记录gpt代充记录
  1634. gptUserRechargeRecordService.recordGptUserRechargeNum(relation.getUserId(), relation.getId(), relation.getAccount(), -subNum, operator, "订单退款");
  1635. break;
  1636. }
  1637. relation = relationMapper.selectById(relationId);
  1638. }
  1639. }
  1640. }
  1641. }