CmsOrderDonServiceImpl.java 108 KB

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