CmsOrderDonServiceImpl.java 110 KB

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