CmsOrderDonServiceImpl.java 143 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571
  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.AlipayTradeFastpayRefundQueryModel;
  11. import com.alipay.api.domain.AlipayTradeRefundModel;
  12. import com.alipay.api.request.AlipayTradeRefundRequest;
  13. import com.alipay.api.response.AlipayTradeRefundResponse;
  14. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  15. import com.baomidou.mybatisplus.core.toolkit.Wrappers;
  16. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  17. import com.cyksj.common.constant.Constant;
  18. import com.cyksj.common.exception.BusinessRuntimeException;
  19. import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
  20. import com.cyksj.common.util.Codec;
  21. import com.cyksj.common.util.Jsons;
  22. import com.cyksj.common.util.StringUtil;
  23. import com.cyksj.common.util.Xmls;
  24. import com.cyksj.config.WeChatConfig;
  25. import com.cyksj.config.zfb.AliPayClientFactory;
  26. import com.cyksj.dto.RedisKey;
  27. import com.cyksj.mapper.*;
  28. import com.cyksj.mapper.channel.ShopConfigMapper;
  29. import com.cyksj.mapper.channel.UserPayEquipmentAvailableBenefitsMapper;
  30. import com.cyksj.mapper.channel.UserPayEquipmentReceiveBenefitsRecordMapper;
  31. import com.cyksj.mapper.claudecode.ClaudeCodeDeductOrderRelateMapper;
  32. import com.cyksj.mapper.claudecode.ClaudeCodeUserResetRecordMapper;
  33. import com.cyksj.mapper.manage.cms.CmsUserMapper;
  34. import com.cyksj.mapper.manage.coupon.CouponUserMapper;
  35. import com.cyksj.mapper.manage.distribute.DistributeWaitingSendPointsMapper;
  36. import com.cyksj.mapper.manage.distribute.UserDistributeBusinessOrderDonRecordMapper;
  37. import com.cyksj.mapper.manage.distribute.UserDistributeMapper;
  38. import com.cyksj.mapper.manage.distribute.equipment.EquipmentUserDistributeTransportBenefitsMapper;
  39. import com.cyksj.mapper.manage.distribute.sub.UserDistributeSubMapper;
  40. import com.cyksj.mapper.manage.distribute.sub.UserDistributeSubRewardsMapper;
  41. import com.cyksj.mapper.manage.distribute.sub.UserDistributeSubWaitingMapper;
  42. import com.cyksj.mapper.manage.sys.WorkOrderMapper;
  43. import com.cyksj.mapper.mirrorshop.UserMirrorShopDistributeWaitingSendPointsMapper;
  44. import com.cyksj.mapper.shop.YhShopUserDistributeBusinessOrderDonRecordMapper;
  45. import com.cyksj.mapper.stock.GoodsSkuStockRelateMapper;
  46. import com.cyksj.model.entity.*;
  47. import com.cyksj.model.excel.ExcelOrderDonInfo;
  48. import com.cyksj.model.manage.request.ReqSetLogisticsPost;
  49. import com.cyksj.model.manage.views.GroupsRelationView;
  50. import com.cyksj.model.request.ChangeRelationReq;
  51. import com.cyksj.model.request.ClickOutReq;
  52. import com.cyksj.model.request.OrderBalanceRefundReq;
  53. import com.cyksj.model.request.OrderRefundReq;
  54. import com.cyksj.redis.RedisService;
  55. import com.cyksj.service.chatgpt.GptUserRechargeRecordService;
  56. import com.cyksj.service.claude.ClaudeCodeService;
  57. import com.cyksj.service.coin.UserGalaxyCoinService;
  58. import com.cyksj.service.coupon.CouponFontService;
  59. import com.cyksj.service.distribute.equipment.EquipmentDistributeService;
  60. import com.cyksj.service.giftcard.GiftCardOrderUseRecordService;
  61. import com.cyksj.service.mange.CmsOrderDonService;
  62. import com.cyksj.service.mange.MirrorUserCleatService;
  63. import com.cyksj.service.mange.stock.GoodsDonStockService;
  64. import com.cyksj.service.market.MarketFrontService;
  65. import com.cyksj.service.order.OrderCommonService;
  66. import com.cyksj.service.order.OrderDonBusinessEventService;
  67. import com.cyksj.service.order.OrderDonTicketRecordService;
  68. import com.cyksj.service.order.MultiQuantityOrderService;
  69. import com.cyksj.service.order.OrderRefundService;
  70. import com.cyksj.service.order.UserRealOrderBenefitsService;
  71. import com.cyksj.service.relation.GroupRelationClearService;
  72. import com.cyksj.service.relation.GroupRelationFrontService;
  73. import com.cyksj.service.relation.GroupsRelationExpiryRecordService;
  74. import com.cyksj.service.relation.GroupsRelationNetflixService;
  75. import com.cyksj.service.shop.YhShopDistributeService;
  76. import com.cyksj.service.user.UserBenefitsService;
  77. import com.cyksj.service.user.UserBindRelationService;
  78. import com.cyksj.service.wechat.WeChatService;
  79. import com.ejlchina.searcher.BeanSearcher;
  80. import com.ejlchina.searcher.param.Operator;
  81. import com.ejlchina.searcher.util.MapUtils;
  82. import lombok.RequiredArgsConstructor;
  83. import lombok.extern.slf4j.Slf4j;
  84. import org.springframework.dao.DuplicateKeyException;
  85. import org.springframework.stereotype.Service;
  86. import org.springframework.transaction.annotation.Transactional;
  87. import org.springframework.transaction.support.TransactionSynchronization;
  88. import org.springframework.transaction.support.TransactionSynchronizationManager;
  89. import org.springframework.transaction.support.TransactionTemplate;
  90. import java.math.BigDecimal;
  91. import java.math.RoundingMode;
  92. import java.util.Date;
  93. import java.util.List;
  94. import java.util.Map;
  95. import java.util.Objects;
  96. import java.util.Optional;
  97. import java.util.UUID;
  98. import java.util.concurrent.atomic.AtomicInteger;
  99. import java.util.stream.Collectors;
  100. /**
  101. * @author chan
  102. * @date 2021/10/25 下午10:14
  103. */
  104. @Service
  105. @Slf4j
  106. @RequiredArgsConstructor
  107. public class CmsOrderDonServiceImpl extends ServiceImpl<OrderDonMapper,OrderDon> implements CmsOrderDonService {
  108. private final OrderDonTransportMapper transportMapper;
  109. private final OrderDonWaybillMapper orderDonWaybillMapper;
  110. private final GoodsSkuStockRelateMapper skuStockRelateMapper;
  111. private final GoodsDonStockService goodsDonStockService;
  112. private final GoodsDonSkuMapper goodsDonSkuMapper;
  113. private final UserRealOrderBenefitsService userRealOrderBenefitsService;
  114. private final UserRelationKickOutRecordMapper kickOutRecordMapper;
  115. private final CmsUserMapper cmsUserMapper;
  116. private final OrderCommonService orderCommonService;
  117. private final GoodsDonMapper goodsDonMapper;
  118. private final RedisService redisService;
  119. private final UserBenefitsService userBenefitsService;
  120. private final DistributeWaitingSendPointsMapper distributeWaitingSendPointsMapper;
  121. private final RefundOrderDonMapper refundOrderDonMapper;
  122. private final UserDistributeMapper userDistributeMapper;
  123. private final OrderDonMapper orderDonMapper;
  124. private final MarketFrontService marketFrontService;
  125. private final EquipmentDistributeService equipmentDistributeService;
  126. private final CouponFontService couponFontService;
  127. private final WeChatService weChatService;
  128. private final WeChatConfig weChatConfig;
  129. private final ShopConfigMapper shopConfigMapper;
  130. private final GroupRelationClearService relationClearService;
  131. private final GroupsRelationMapper relationMapper;
  132. private final GroupsMapper groupsMapper;
  133. private final GoodsDonSkuMapper skuMapper;
  134. private final UserDistributeBusinessOrderDonRecordMapper businessOrderDonRecordMapper;
  135. private final WorkOrderMapper workOrderMapper;
  136. private final OrderRefundService orderRefundService;
  137. private final OrderDiscountPlusPurchaseSkuRelationMapper orderDiscountPlusPurchaseSkuRelationMapper;
  138. private final EquipmentUserDistributeTransportBenefitsMapper transportBenefitsMapper;
  139. private final BeanSearcher beanSearcher;
  140. private final UserPayEquipmentReceiveBenefitsRecordMapper receiveBenefitsRecordMapper;
  141. private final GroupsRelationExpiryRecordService groupsRelationExpiryRecordService;
  142. private final GiftCardOrderUseRecordService giftCardOrderUseRecordService;
  143. private final GiftCardUserRecordMapper giftCardUserRecordMapper;
  144. private final YhShopDistributeService yhShopDistributeService;
  145. private final YhShopUserDistributeBusinessOrderDonRecordMapper yhShopBusinessOrderDonRecordMapper;
  146. private final UserPayEquipmentAvailableBenefitsMapper availableBenefitsMapper;
  147. private final GroupRelationFrontService groupRelationFrontService;
  148. private final UserMapper userMapper;
  149. private final ChatgptUserMapper chatgptUserMapper;
  150. private final UserDistributeSubMapper userDistributeSubMapper;
  151. private final UserDistributeSubWaitingMapper subWaitingMapper;
  152. private final UserDistributeSubRewardsMapper userDistributeSubRewardsMapper;
  153. private final UpgradeOrderDonMapper upgradeOrderDonMapper;
  154. private final UpgradePackageMapper upgradePackageMapper;
  155. private final MidjourneyUserMapper midjourneyUserMapper;
  156. private final GroupsRelationMapper groupsRelationMapper;
  157. private final UserBindRelationService userBindRelationService;
  158. private final GroupsRelationNetflixService groupsRelationNetflixService;
  159. private final AccountMapper accountMapper;
  160. private final MirrorUserCleatService mirrorUserCleatService;
  161. private final OrderDonRenewRecordMapper orderDonRenewRecordMapper;
  162. private final LumaUserMapper lumaUserMapper;
  163. private final UserBenefitsComboRelationRecordMapper userBenefitsComboRelationRecordMapper;
  164. private final UserMirrorShopDistributeWaitingSendPointsMapper userMirrorShopDistributeWaitingSendPointsMapper;
  165. private final ClaudeUserMapper claudeUserMapper;
  166. private final UserTicketClearedRecordMapper userTicketClearedRecordMapper;
  167. private final NetflixUserAccountSubmitRecoverRecordMapper netflixUserAccountSubmitRecoverRecordMapper;
  168. private final NetflixUserChangeOtherTicketRecordMapper netflixUserChangeOtherTicketRecordMapper;
  169. private final CouponUserMapper couponUserMapper;
  170. private final UserGalaxyCoinService userGalaxyCoinService;
  171. private final GptUserRechargeRecordService gptUserRechargeRecordService;
  172. private final ClaudeCodeUserResetRecordMapper claudeCodeUserResetRecordMapper;
  173. private final ClaudeCodeService claudeCodeService;
  174. private final ClaudeCodeDeductOrderRelateMapper claudeCodeDeductOrderRelateMapper;
  175. private final NanoUserQuotaMapper nanoUserQuotaMapper;
  176. private final AccountNetflixFrozenTicketReceivedRecordMapper receivedRecordMapper;
  177. private final OrderDonTicketRecordService orderDonTicketRecordService;
  178. private final MultiQuantityOrderService multiQuantityOrderService;
  179. private final OrderDonBusinessEventService orderDonBusinessEventService;
  180. private final OrderDonGalaxyCoinRecordMapper orderDonGalaxyCoinRecordMapper;
  181. private final UserBalanceSourceRecordMapper userBalanceSourceRecordMapper;
  182. private final TransactionTemplate transactionTemplate;
  183. private static final GlobalThreadPoolTaskExecutor TASK_POOL = GlobalThreadPoolTaskExecutor.getInstance();
  184. @Override
  185. public List<ExcelOrderDonInfo> exportOrderInfo(Long promotionId, String start, String end) {
  186. return this.getBaseMapper().exportOrderInfo(promotionId,start,end);
  187. }
  188. @Override
  189. public OrderDonTransport getTransport(Long orderId) {
  190. return transportMapper.selectOne(Wrappers.lambdaQuery(OrderDonTransport.class).eq(OrderDonTransport::getOrderId, orderId));
  191. }
  192. @Transactional(rollbackFor = Throwable.class)
  193. @Override
  194. public OrderDonWaybill setWaybill(ReqSetLogisticsPost reqSetLogisticsPost) {
  195. OrderDonWaybill orderDonWaybill = Optional.ofNullable(orderDonWaybillMapper.selectOne(Wrappers.lambdaQuery(OrderDonWaybill.class).eq(OrderDonWaybill::getOrderId, reqSetLogisticsPost.getOrderId()))).orElse(new OrderDonWaybill());
  196. orderDonWaybill.setCodeCn(reqSetLogisticsPost.getCodeCn());
  197. orderDonWaybill.setTrackingNumber(reqSetLogisticsPost.getTrackingNumber());
  198. orderDonWaybill.setOrderId(reqSetLogisticsPost.getOrderId());
  199. orderDonWaybill.setRemark(reqSetLogisticsPost.getRemark());
  200. OrderDon orderDon = getById(orderDonWaybill.getOrderId());
  201. Integer type = Optional.ofNullable(reqSetLogisticsPost.getType()).orElse(0);
  202. //实物发货
  203. if (type == 0 || type == 1) {
  204. if (orderDonWaybill.getId() == null) {
  205. try {
  206. orderDonWaybillMapper.insert(orderDonWaybill);
  207. } catch (DuplicateKeyException e) {
  208. return orderDonWaybill;
  209. }
  210. orderDon.setStatus(OrderDon.Status.transport);
  211. updateById(orderDon);
  212. //库存扣减逻辑
  213. List<GoodsSkuStockRelate> relateList = skuStockRelateMapper.selectList(Wrappers.lambdaQuery(GoodsSkuStockRelate.class).eq(GoodsSkuStockRelate::getSkuId, orderDon.getSkuId()));
  214. if (!relateList.isEmpty()) {
  215. relateList.forEach((relate) -> {
  216. goodsDonStockService.upStockRelate(relate.getStockId(), orderDon.getId(), "transport");
  217. });
  218. }
  219. } else {
  220. if (orderDon.getStatus() == OrderDon.Status.hasPayment) {
  221. orderDon.setStatus(OrderDon.Status.transport);
  222. updateById(orderDon);
  223. }
  224. orderDonWaybillMapper.updateById(orderDonWaybill);
  225. }
  226. //实物分销订单是否存在
  227. DistributeWaitingSendPoints waitingSendPoints = distributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(DistributeWaitingSendPoints.class)
  228. .eq(DistributeWaitingSendPoints::getOrderId, orderDon.getId())
  229. .eq(DistributeWaitingSendPoints::getIsDelivery, false)
  230. .last("limit 1"));
  231. if (waitingSendPoints != null) {
  232. //实物分销订单发货后再 进行提成结算期
  233. waitingSendPoints.setIsDelivery(true);
  234. distributeWaitingSendPointsMapper.updateById(waitingSendPoints);
  235. }
  236. //分销有礼 分销实物是否有发货后用户权益
  237. EquipmentUserDistributeTransportBenefits transportBenefits = transportBenefitsMapper.selectOne(Wrappers.lambdaQuery(EquipmentUserDistributeTransportBenefits.class)
  238. .eq(EquipmentUserDistributeTransportBenefits::getOrderId, orderDon.getId())
  239. .eq(EquipmentUserDistributeTransportBenefits::getStatus, EquipmentUserDistributeTransportBenefits.Status.hasPayment).last("limit 1"));
  240. if (transportBenefits != null) {
  241. if (transportBenefits.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  242. //7天后余额到账
  243. transportBenefitsMapper.update(null, Wrappers.lambdaUpdate(EquipmentUserDistributeTransportBenefits.class)
  244. .set(EquipmentUserDistributeTransportBenefits::getStatus, EquipmentUserDistributeTransportBenefits.Status.transport)
  245. .set(EquipmentUserDistributeTransportBenefits::getSendTime, DateUtil.offsetDay(DateTime.now(), 7))
  246. .eq(EquipmentUserDistributeTransportBenefits::getOrderId, orderDon.getId())
  247. .eq(EquipmentUserDistributeTransportBenefits::getStatus, EquipmentUserDistributeTransportBenefits.Status.hasPayment));
  248. }
  249. }
  250. }
  251. //权益发货
  252. if (type == 0 || type == 2) {
  253. GoodsDonSku sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  254. if (sku != null && sku.getIsBenefits()) {
  255. //是否实物权益已发放
  256. Integer count = receiveBenefitsRecordMapper.selectCount(Wrappers.lambdaQuery(UserPayEquipmentReceiveBenefitsRecord.class)
  257. .eq(UserPayEquipmentReceiveBenefitsRecord::getRealOrderId, orderDon.getId()));
  258. if (count == 0) {
  259. count = availableBenefitsMapper.selectCount(Wrappers.lambdaQuery(UserPayEquipmentAvailableBenefits.class)
  260. .eq(UserPayEquipmentAvailableBenefits::getRealOrderId, orderDon.getId()));
  261. }
  262. if (count == 0) {
  263. //实物权益未发
  264. String benefitsKey = RedisService.key.REAL_GOODS_BENEFITS_KEY.getNameFormat(orderDon.getId());
  265. if (redisService.setNx(benefitsKey, orderDon.getId(), RedisService.key.REAL_GOODS_BENEFITS_KEY.getTimeout())) {
  266. //发放实物购买权益
  267. if (StrUtil.isNotEmpty(sku.getBenefitsList())) {
  268. try {
  269. List<GoodsDonSku> goodsDonSkus = Jsons.parseList(sku.getBenefitsList(), GoodsDonSku.class);
  270. //自购实物 获取权益
  271. userRealOrderBenefitsService.getPayRealGoodsBenefits(orderDon.getUserId(), orderDon.getId(), orderDon.getYhsId(), goodsDonSkus);
  272. //清除多余的车票
  273. clearExtraRelation(orderDon);
  274. } catch (Exception e) {
  275. redisService.del(benefitsKey);
  276. }
  277. }
  278. }
  279. }
  280. }
  281. }
  282. return orderDonWaybill;
  283. }
  284. @Override
  285. public void kickOutRelationId(long adminId, ClickOutReq req) {
  286. Long orderId = req.getOrderId();
  287. OrderDon orderDon = getById(orderId);
  288. if (orderDon != null && orderDonTicketRecordService.exists(orderId)) {
  289. throw BusinessRuntimeException.getInstance("Multi-quantity orders cannot clear a single ticket");
  290. }
  291. if (orderDon != null && !orderDon.getIsKickOut()) {
  292. try {
  293. UserRelationKickOutRecord kickOutRecord = new UserRelationKickOutRecord();
  294. kickOutRecord.setUserId(orderDon.getUserId());
  295. kickOutRecord.setRelationId(orderDon.getRelationId());
  296. kickOutRecord.setGoodsId(orderDon.getGoodsId());
  297. kickOutRecord.setSkuId(orderDon.getSkuId());
  298. kickOutRecord.setReason(req.getReason());
  299. kickOutRecord.setImg(req.getImg());
  300. kickOutRecord.setRemark(req.getRemark());
  301. kickOutRecord.setOrderId(orderDon.getId());
  302. kickOutRecord.setOrderNo(orderDon.getOrderNo());
  303. Optional.ofNullable(cmsUserMapper.selectById(adminId)).ifPresent(cmsUser -> kickOutRecord.setOperator(cmsUser.getNickname()));
  304. kickOutRecordMapper.insert(kickOutRecord);
  305. orderDon.setIsKickOut(true);
  306. updateById(orderDon);
  307. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  308. GoodsDonSku goodsDonSku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  309. //清除车票
  310. orderCommonService.clearUnrealGoodsDetail(orderDon, goodsDon.getType(), goodsDonSku);
  311. } catch (DuplicateKeyException e) {
  312. }
  313. }
  314. }
  315. @Override
  316. public void unifiedRefund(OrderRefundReq refundReq) throws Exception {
  317. OrderDon orderDon = orderDonMapper.selectById(refundReq.getOrderId());
  318. boolean multiQuantityOrder = orderDon != null
  319. && orderDonTicketRecordService.exists(orderDon.getId());
  320. if (multiQuantityOrder) {
  321. refundMultiQuantityOrder(refundReq, orderDon);
  322. return;
  323. }
  324. GoodsDonSku sku = null;
  325. if (orderDon.getSkuId() != null) {
  326. sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
  327. }
  328. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  329. if (StrUtil.isEmpty(refundReq.getRefundType())) {
  330. refundReq.setRefundType("money");
  331. }
  332. String refundType = refundReq.getRefundType();
  333. //校验订单是否符合退款
  334. checkOrderRefund(orderDon, goodsDon, sku, refundReq);
  335. //空订单关闭
  336. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0 && orderDon.getBalance().compareTo(BigDecimal.ZERO) == 0
  337. && orderDon.getRelationId() == 0) {
  338. orderDon.setStatus(OrderDon.Status.refund);
  339. orderDonMapper.updateById(orderDon);
  340. if (goodsDon.getType() == 2) {
  341. //扣除用户自身实物权益
  342. userRealOrderBenefitsService.deductUserRealGoodsBenefits(orderDon.getId());
  343. }
  344. return;
  345. }
  346. //调用第三方接口退款
  347. String outNo = StrUtil.EMPTY;
  348. if (refundReq.getRefundMoney() != null && refundReq.getRefundMoney().compareTo(BigDecimal.ZERO) > 0) {
  349. outNo = orderRefundService.centerRefund(refundReq, orderDon);
  350. }
  351. orderDon.setRefundDesc(refundReq.getRefundDesc());
  352. //记录退款信息
  353. commonRefund(orderDon, refundReq.getRefundMoney(), refundReq.getOperator(), goodsDon, sku, outNo,
  354. refundType, refundReq.getIsOnly(), refundReq.getRefundBalance(), refundReq.getChatImg(),
  355. refundReq.getDeductBalance(), refundReq.getDpRelationIds(), multiQuantityOrder);
  356. //修改订单状态
  357. orderDon.setStatus(OrderDon.Status.refund);
  358. orderDonMapper.updateById(orderDon);
  359. //续费升级订单
  360. if (orderDon.getOrderType() == 2 && (orderDon.getGoodsId() == Constant.CLAUDE_CODE_GOODS_ID || sku.getIsMirror())) {
  361. mirrorUserCleatService.handleRenewUpgradeOrders(orderDon, sku);
  362. }
  363. //提交过工单的订单
  364. //将用户异常订单关闭
  365. workOrderMapper.update(null, Wrappers.lambdaUpdate(WorkOrder.class)
  366. .set(WorkOrder::getStatus, WorkOrder.Status.close)
  367. .eq(WorkOrder::getStatus, WorkOrder.Status.waiting)
  368. .eq(WorkOrder::getUserId, orderDon.getUserId())
  369. .eq(WorkOrder::getRelationId, orderDon.getRelationId()));
  370. //将GPT规格的车队 下次可停车时间置空
  371. groupRelationFrontService.setGroupsTripsParkingTimeEmpty(sku, orderDon.getRelationId());
  372. }
  373. /**
  374. * A multi-quantity order is one payment backed by independent ticket slots.
  375. * Ticket reclaim, provider refund and order-level side effects are deliberately split so
  376. * a provider call never participates in a database transaction.
  377. */
  378. private void refundMultiQuantityOrder(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
  379. refundMultiQuantityOrder(refundReq, orderDon, 5);
  380. }
  381. private void refundMultiQuantityOrder(OrderRefundReq refundReq, OrderDon orderDon,
  382. int leaseMinutes) throws Exception {
  383. Long orderId = orderDon.getId();
  384. OrderDonBusinessEvent existing = orderDonBusinessEventService.get(orderId, OrderDonBusinessEvent.Type.refund);
  385. if (orderDon.getStatus() == OrderDon.Status.refund
  386. && existing != null && existing.getStatus() == OrderDonBusinessEvent.Status.success) {
  387. return;
  388. }
  389. validateMultiQuantityWholeRefund(refundReq, orderDon);
  390. if (requiresManualMultiQuantityRefund(orderDon)) {
  391. throw BusinessRuntimeException.getInstance("PayPal/Stripe批量订单请人工核对后退款");
  392. }
  393. multiQuantityOrderService.prepareRefund(orderId);
  394. OrderDonBusinessEvent refundEvent = orderDonBusinessEventService.get(
  395. orderId, OrderDonBusinessEvent.Type.refund);
  396. if (refundEvent != null && refundEvent.getStatus() == OrderDonBusinessEvent.Status.processing) {
  397. tryFinalizeProcessingRefund(orderDon, refundReq, refundEvent);
  398. return;
  399. }
  400. String workerToken = UUID.randomUUID().toString().replace("-", "");
  401. orderDonTicketRecordService.startRefund(orderId, workerToken);
  402. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  403. GoodsDonSku sku = orderDon.getSkuId() == null ? null : goodsDonSkuMapper.selectById(orderDon.getSkuId());
  404. String refundType = getMultiQuantityRefundType(orderDon);
  405. String outRefundNo = buildMultiQuantityRefundNo(orderId);
  406. if (requiresExternalRefund(orderDon)) {
  407. try {
  408. orderRefundService.centerRefund(refundReq, orderDon, outRefundNo);
  409. } catch (Exception e) {
  410. log.error("Multi-quantity refund submission failed, orderId:{}", orderId, e);
  411. boolean restored = false;
  412. try {
  413. ProviderRefundStatus status = queryProviderRefundStatus(orderDon, outRefundNo);
  414. if (status == ProviderRefundStatus.FAILED) {
  415. orderDonTicketRecordService.restoreRefund(orderId, workerToken,
  416. "provider refund submission failed");
  417. restored = true;
  418. }
  419. } catch (Exception queryError) {
  420. log.warn("Unable to confirm refund submission result, orderId:{}", orderId, queryError);
  421. }
  422. if (restored) {
  423. throw BusinessRuntimeException.getInstance("退款申请失败,原车票已恢复");
  424. }
  425. throw BusinessRuntimeException.getInstance("退款申请状态确认中,请稍后查询");
  426. }
  427. if (orderDon.getType() == OrderDon.Type.WeChat) {
  428. // WeChat's refund API only acknowledges the request. Finalize on its SUCCESS
  429. // notification or a later query; tickets remain frozen meanwhile.
  430. return;
  431. }
  432. }
  433. final String finalWorkerToken = workerToken;
  434. transactionTemplate.executeWithoutResult(status -> finishMultiQuantityRefund(
  435. refundReq, orderDon, goodsDon, sku, outRefundNo, refundType, finalWorkerToken));
  436. }
  437. private void tryFinalizeProcessingRefund(OrderDon order, OrderRefundReq request,
  438. OrderDonBusinessEvent event) throws Exception {
  439. if (StrUtil.isBlank(event.getWorkerToken())) {
  440. throw BusinessRuntimeException.getInstance("订单退款状态异常");
  441. }
  442. String outRefundNo = buildMultiQuantityRefundNo(order.getId());
  443. ProviderRefundStatus status = queryProviderRefundStatus(order, outRefundNo);
  444. if (status == ProviderRefundStatus.SUCCESS) {
  445. GoodsDon goods = goodsDonMapper.selectById(order.getGoodsId());
  446. GoodsDonSku sku = order.getSkuId() == null ? null : goodsDonSkuMapper.selectById(order.getSkuId());
  447. transactionTemplate.executeWithoutResult(tx -> finishMultiQuantityRefund(
  448. request, order, goods, sku, outRefundNo,
  449. getMultiQuantityRefundType(order), event.getWorkerToken()));
  450. return;
  451. }
  452. if (status == ProviderRefundStatus.FAILED) {
  453. orderDonTicketRecordService.restoreRefund(order.getId(), event.getWorkerToken(),
  454. "provider refund failed or closed");
  455. throw BusinessRuntimeException.getInstance("退款失败,原车票已恢复");
  456. }
  457. throw BusinessRuntimeException.getInstance("订单退款正在处理中,请稍后查询退款状态");
  458. }
  459. @Override
  460. public int recoverMultiQuantityRefunds(int limit, int leaseMinutes) {
  461. int boundedLimit = Math.max(1, Math.min(limit, 500));
  462. int boundedLeaseMinutes = Math.max(1, Math.min(leaseMinutes, 120));
  463. int processed = 0;
  464. for (Long orderId : orderDonTicketRecordService.expiredRefundOrderIds(boundedLeaseMinutes, boundedLimit)) {
  465. OrderDon order = orderDonMapper.selectById(orderId);
  466. if (order == null || order.getStatus() == OrderDon.Status.refund) {
  467. continue;
  468. }
  469. try {
  470. recoverMultiQuantityRefund(order, boundedLeaseMinutes);
  471. } catch (Exception e) {
  472. log.error("Multi-quantity refund recovery failed, orderId:{}", orderId, e);
  473. }
  474. processed++;
  475. }
  476. return processed;
  477. }
  478. private void recoverMultiQuantityRefund(OrderDon order, int leaseMinutes) throws Exception {
  479. OrderDonBusinessEvent refundEvent = orderDonBusinessEventService.get(
  480. order.getId(), OrderDonBusinessEvent.Type.refund);
  481. if (refundEvent == null || refundEvent.getStatus() != OrderDonBusinessEvent.Status.processing) {
  482. return;
  483. }
  484. String outRefundNo = buildMultiQuantityRefundNo(order.getId());
  485. ProviderRefundStatus providerStatus = queryProviderRefundStatus(order, outRefundNo);
  486. if (providerStatus == ProviderRefundStatus.PROCESSING
  487. || providerStatus == ProviderRefundStatus.UNKNOWN) {
  488. if (StrUtil.isNotBlank(refundEvent.getWorkerToken())) {
  489. orderDonTicketRecordService.deferRefundCheck(order.getId(), refundEvent.getWorkerToken(),
  490. "provider refund is not final");
  491. }
  492. return;
  493. }
  494. if (!requiresRefundLeaseReclaim(providerStatus)) {
  495. return;
  496. }
  497. String workerToken = orderDonTicketRecordService.reclaimExpiredRefund(
  498. order.getId(), leaseMinutes);
  499. if (workerToken == null) {
  500. return;
  501. }
  502. if (providerStatus == ProviderRefundStatus.FAILED) {
  503. orderDonTicketRecordService.restoreRefund(order.getId(), workerToken,
  504. "provider refund failed or closed");
  505. log.error("Multi-quantity provider refund failed, orderId:{}, outRefundNo:{}",
  506. order.getId(), outRefundNo);
  507. return;
  508. }
  509. GoodsDon goodsDon = goodsDonMapper.selectById(order.getGoodsId());
  510. GoodsDonSku sku = order.getSkuId() == null ? null : goodsDonSkuMapper.selectById(order.getSkuId());
  511. OrderRefundReq request = buildRecoveryRefundRequest(order);
  512. transactionTemplate.executeWithoutResult(status -> finishMultiQuantityRefund(
  513. request, order, goodsDon, sku, outRefundNo,
  514. getMultiQuantityRefundType(order), workerToken));
  515. }
  516. private OrderRefundReq buildRecoveryRefundRequest(OrderDon order) {
  517. OrderRefundReq request = new OrderRefundReq();
  518. request.setOrderId(order.getId());
  519. request.setRefundMoney(Optional.ofNullable(order.getMoney()).orElse(BigDecimal.ZERO));
  520. request.setRefundBalance(Optional.ofNullable(order.getBalance()).orElse(BigDecimal.ZERO));
  521. request.setRefundDesc(StrUtil.blankToDefault(order.getRefundDesc(),
  522. "multi-quantity whole-order refund recovery"));
  523. request.setOperator("system-recovery");
  524. request.setIsDiffer(false);
  525. request.setRefundType(getMultiQuantityRefundType(order));
  526. return request;
  527. }
  528. private boolean requiresExternalRefund(OrderDon order) {
  529. return Optional.ofNullable(order.getMoney()).orElse(BigDecimal.ZERO).compareTo(BigDecimal.ZERO) > 0
  530. && order.getType() != OrderDon.Type.BALANCE;
  531. }
  532. private String refundShopId(OrderDon order) {
  533. return StrUtil.blankToDefault(order.getShopId(),
  534. order.getType() == OrderDon.Type.WeChat
  535. ? ShopConfig.WX_DEFAULT_APP_ID : ShopConfig.ZFB_DEFAULT_APP_ID);
  536. }
  537. private ProviderRefundStatus queryProviderRefundStatus(OrderDon order, String outRefundNo) throws Exception {
  538. if (!requiresExternalRefund(order)) {
  539. return ProviderRefundStatus.SUCCESS;
  540. }
  541. if (order.getType() == OrderDon.Type.WeChat) {
  542. Map<String, String> result = weChatService.getWxRefundDetail(
  543. weChatConfig.getAppid(), refundShopId(order), outRefundNo);
  544. return parseWxRefundStatus(result, order, outRefundNo);
  545. }
  546. if (order.getType() == OrderDon.Type.ALI_PAY) {
  547. com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse response =
  548. queryAliRefund(order, outRefundNo);
  549. if (response == null) {
  550. return ProviderRefundStatus.UNKNOWN;
  551. }
  552. if (!StrUtil.equals(order.getOrderNo(), response.getOutTradeNo())
  553. || !StrUtil.equals(outRefundNo, response.getOutRequestNo())
  554. || !StrUtil.equals(order.getTransactionId(), response.getTradeNo())) {
  555. throw BusinessRuntimeException.getInstance("支付宝退款查询订单信息不匹配");
  556. }
  557. BigDecimal expected = Optional.ofNullable(order.getMoney()).orElse(BigDecimal.ZERO);
  558. BigDecimal actual = yuanToCent(response.getRefundAmount());
  559. return actual.compareTo(expected) == 0
  560. ? ProviderRefundStatus.SUCCESS : ProviderRefundStatus.UNKNOWN;
  561. }
  562. return ProviderRefundStatus.UNKNOWN;
  563. }
  564. private com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse queryAliRefund(
  565. OrderDon order, String outRefundNo) throws Exception {
  566. AlipayClient alipayClient = AliPayClientFactory.getAlipayClient(
  567. refundShopId(order));
  568. com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest request =
  569. new com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest();
  570. AlipayTradeFastpayRefundQueryModel model = new AlipayTradeFastpayRefundQueryModel();
  571. model.setTradeNo(order.getTransactionId());
  572. model.setOutRequestNo(outRefundNo);
  573. request.setBizModel(model);
  574. ShopConfig shopConfig = shopConfigMapper.selectOne(Wrappers.lambdaQuery(ShopConfig.class)
  575. .eq(ShopConfig::getAppId, order.getShopId()).last("limit 1"));
  576. com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse response =
  577. shopConfig != null && Boolean.TRUE.equals(shopConfig.getIsCert())
  578. ? alipayClient.certificateExecute(request) : alipayClient.execute(request);
  579. return response != null && response.isSuccess() ? response : null;
  580. }
  581. private ProviderRefundStatus parseWxRefundStatus(Map<String, String> result,
  582. OrderDon order, String outRefundNo) {
  583. if (result == null || !"SUCCESS".equals(result.get("result_code"))) {
  584. return ProviderRefundStatus.UNKNOWN;
  585. }
  586. int index = findWxRefundIndex(result, outRefundNo);
  587. if (index < 0) {
  588. return ProviderRefundStatus.UNKNOWN;
  589. }
  590. if (!StrUtil.equals(order.getTransactionId(), result.get("transaction_id"))
  591. || !StrUtil.equals(order.getOrderNo(), result.get("out_trade_no"))
  592. || !StrUtil.equals(refundShopId(order), result.get("mch_id"))
  593. || parseCent(result.get("total_fee"))
  594. != Optional.ofNullable(order.getMoney()).orElse(BigDecimal.ZERO).longValueExact()
  595. || parseCent(result.get("refund_fee_" + index))
  596. != Optional.ofNullable(order.getMoney()).orElse(BigDecimal.ZERO).longValueExact()) {
  597. throw BusinessRuntimeException.getInstance("微信退款查询订单信息不匹配");
  598. }
  599. return mapWxRefundStatus(result.get("refund_status_" + index));
  600. }
  601. private int findWxRefundIndex(Map<String, String> result, String outRefundNo) {
  602. int count;
  603. try {
  604. count = Integer.parseInt(result.getOrDefault("refund_count", "0"));
  605. } catch (NumberFormatException e) {
  606. return -1;
  607. }
  608. for (int index = 0; index < count; index++) {
  609. if (StrUtil.equals(outRefundNo, result.get("out_refund_no_" + index))) {
  610. return index;
  611. }
  612. }
  613. return -1;
  614. }
  615. private ProviderRefundStatus mapWxRefundStatus(String status) {
  616. if ("SUCCESS".equals(status)) {
  617. return ProviderRefundStatus.SUCCESS;
  618. }
  619. if ("PROCESSING".equals(status)) {
  620. return ProviderRefundStatus.PROCESSING;
  621. }
  622. if ("CHANGE".equals(status) || "REFUNDCLOSE".equals(status)) {
  623. return ProviderRefundStatus.FAILED;
  624. }
  625. return ProviderRefundStatus.UNKNOWN;
  626. }
  627. private long parseCent(String value) {
  628. try {
  629. return Long.parseLong(value);
  630. } catch (Exception e) {
  631. throw BusinessRuntimeException.getInstance("退款金额格式异常");
  632. }
  633. }
  634. private BigDecimal yuanToCent(String value) {
  635. try {
  636. return new BigDecimal(value).multiply(BigDecimal.valueOf(100))
  637. .setScale(0, RoundingMode.UNNECESSARY);
  638. } catch (Exception e) {
  639. throw BusinessRuntimeException.getInstance("退款金额格式异常");
  640. }
  641. }
  642. static boolean requiresManualMultiQuantityRefund(OrderDon order) {
  643. return order != null && (order.getType() == OrderDon.Type.PAYPAL
  644. || order.getType() == OrderDon.Type.STRIPE);
  645. }
  646. static boolean requiresRefundLeaseReclaim(ProviderRefundStatus status) {
  647. return status == ProviderRefundStatus.SUCCESS || status == ProviderRefundStatus.FAILED;
  648. }
  649. enum ProviderRefundStatus {
  650. SUCCESS,
  651. PROCESSING,
  652. FAILED,
  653. UNKNOWN
  654. }
  655. private void validateMultiQuantityWholeRefund(OrderRefundReq refundReq, OrderDon orderDon) {
  656. if (orderDon.getStatus() == OrderDon.Status.noPayment || orderDon.getStatus() == OrderDon.Status.close) {
  657. throw BusinessRuntimeException.getInstance("订单{0}状态不支持退款", orderDon.getStatus());
  658. }
  659. if (orderDon.getStatus() == OrderDon.Status.refund) {
  660. throw BusinessRuntimeException.getInstance("该订单已退款");
  661. }
  662. if (orderDon.getCouponUserId() != null && orderDon.getCouponUserId() != 0) {
  663. throw BusinessRuntimeException.getInstance("批量订单不支持优惠券退款");
  664. }
  665. BigDecimal money = Optional.ofNullable(orderDon.getMoney()).orElse(BigDecimal.ZERO);
  666. BigDecimal balance = Optional.ofNullable(orderDon.getBalance()).orElse(BigDecimal.ZERO);
  667. BigDecimal refundMoney = Optional.ofNullable(refundReq.getRefundMoney()).orElse(BigDecimal.ZERO);
  668. BigDecimal requestedBalance = refundReq.getRefundBalance();
  669. if (refundMoney.compareTo(money) != 0
  670. || (requestedBalance != null && requestedBalance.compareTo(balance) != 0)
  671. || Boolean.TRUE.equals(refundReq.getIsOnly()) || Boolean.TRUE.equals(refundReq.getIsDiffer())) {
  672. throw BusinessRuntimeException.getInstance("批量订单仅支持整单退款,现金和余额必须全部退回");
  673. }
  674. refundReq.setRefundMoney(money);
  675. refundReq.setRefundBalance(balance);
  676. refundReq.setRefundType(getMultiQuantityRefundType(orderDon));
  677. }
  678. private void reclaimMultiQuantityTickets(OrderDon orderDon, String workerToken) {
  679. List<OrderDonTicketRecord> records = orderDonTicketRecordService.listByOrderId(orderDon.getId());
  680. int expected = Optional.ofNullable(orderDon.getNum()).orElse(records.size());
  681. if (records.size() != expected) {
  682. throw BusinessRuntimeException.getInstance("订单车票数量不匹配");
  683. }
  684. for (OrderDonTicketRecord record : records) {
  685. if (isTicketAlreadyReclaimed(record)) {
  686. continue;
  687. }
  688. if (record.getStatus() != OrderDonTicketRecord.Status.refunding) {
  689. throw BusinessRuntimeException.getInstance("订单车票状态异常,序号: {0}", record.getItemIndex());
  690. }
  691. if (currentTicketRelationId(record) != null) {
  692. clearMultiQuantityTicket(orderDon, record);
  693. }
  694. if (!orderDonTicketRecordService.markRefunded(record.getId(), workerToken)) {
  695. throw BusinessRuntimeException.getInstance("车票退款状态更新冲突,序号: {0}", record.getItemIndex());
  696. }
  697. }
  698. if (!areAllMultiQuantityTicketsReclaimed(orderDon,
  699. orderDonTicketRecordService.listByOrderId(orderDon.getId()))) {
  700. throw BusinessRuntimeException.getInstance("订单车票未全部回收");
  701. }
  702. }
  703. static boolean areAllMultiQuantityTicketsReclaimed(OrderDon orderDon,
  704. List<OrderDonTicketRecord> records) {
  705. int expected = Optional.ofNullable(orderDon.getNum()).orElse(records.size());
  706. if (records.size() != expected) {
  707. return false;
  708. }
  709. return records.stream().allMatch(CmsOrderDonServiceImpl::isTicketAlreadyReclaimed);
  710. }
  711. static boolean isTicketAlreadyReclaimed(OrderDonTicketRecord record) {
  712. return record.getStatus() == OrderDonTicketRecord.Status.refunded
  713. || record.getStatus() == OrderDonTicketRecord.Status.cleared;
  714. }
  715. private void clearMultiQuantityTicket(OrderDon orderDon, OrderDonTicketRecord record) {
  716. Long relationId = currentTicketRelationId(record);
  717. OrderDonTicketRecord activeRecord = orderDonTicketRecordService.getActiveByRelationIdForUpdate(
  718. relationId);
  719. if (activeRecord == null || !activeRecord.getId().equals(record.getId())
  720. || activeRecord.getStatus() != OrderDonTicketRecord.Status.refunding
  721. || !orderDon.getId().equals(activeRecord.getOrderId())) {
  722. throw BusinessRuntimeException.getInstance("车票分配记录已变更,relationId: {0}", relationId);
  723. }
  724. GroupsRelation relation = relationMapper.selectByIdForUpdate(relationId);
  725. if (relation == null) {
  726. throw BusinessRuntimeException.getInstance("退款车票不存在,relationId: {0}", relationId);
  727. }
  728. if (relation.getUserId() == null || relation.getUserId() == 0) {
  729. return;
  730. }
  731. if (!isMultiQuantityTicketOwner(orderDon, relation)) {
  732. throw BusinessRuntimeException.getInstance("车票归属异常,relationId: {0}", relation.getId());
  733. }
  734. relationClearService.clearRefundTicket(relation, activeRecord);
  735. }
  736. private Long currentTicketRelationId(OrderDonTicketRecord record) {
  737. return record.getRelationId();
  738. }
  739. static boolean isMultiQuantityTicketOwner(OrderDon orderDon, GroupsRelation relation) {
  740. return orderDon != null && relation != null && orderDon.getUserId() != null
  741. && orderDon.getUserId().equals(relation.getUserId());
  742. }
  743. private void finishMultiQuantityRefund(OrderRefundReq refundReq, OrderDon orderDon,
  744. GoodsDon goodsDon, GoodsDonSku sku, String outRefundNo,
  745. String refundType, String workerToken) {
  746. OrderDon latest = orderDonMapper.selectByIdForUpdate(orderDon.getId());
  747. if (latest == null) {
  748. throw BusinessRuntimeException.getInstance("订单不存在");
  749. }
  750. OrderDonBusinessEvent refundEvent = orderDonBusinessEventService.get(
  751. latest.getId(), OrderDonBusinessEvent.Type.refund);
  752. if (refundEvent != null && refundEvent.getStatus() == OrderDonBusinessEvent.Status.success) {
  753. return;
  754. }
  755. if (latest.getStatus() == OrderDon.Status.refund) {
  756. throw BusinessRuntimeException.getInstance("订单退款状态与幂等事件不一致");
  757. }
  758. if (refundEvent == null || refundEvent.getStatus() != OrderDonBusinessEvent.Status.processing
  759. || !StrUtil.equals(workerToken, refundEvent.getWorkerToken())) {
  760. throw BusinessRuntimeException.getInstance("订单退款执行权已失效");
  761. }
  762. reclaimMultiQuantityTickets(latest, workerToken);
  763. latest.setRefundDesc(refundReq.getRefundDesc());
  764. latest.setRefundMoney(latest.getMoney());
  765. latest.setRefundBalance(Optional.ofNullable(latest.getBalance()).orElse(BigDecimal.ZERO));
  766. Integer returnedBalance = userBalanceSourceRecordMapper.selectCount(
  767. Wrappers.lambdaQuery(UserBalanceSourceRecord.class)
  768. .eq(UserBalanceSourceRecord::getOrderId, latest.getId())
  769. .eq(UserBalanceSourceRecord::getSource, UserBalanceSourceRecord.Source.refund));
  770. if ((OrderRefundReq.RefundType.balance.name().equals(refundType)
  771. || OrderRefundReq.RefundType.bxj.name().equals(refundType))
  772. && latest.getRefundBalance().compareTo(BigDecimal.ZERO) > 0
  773. && returnedBalance != null && returnedBalance > 0) {
  774. throw BusinessRuntimeException.getInstance("订单余额已退回,退款幂等状态异常");
  775. }
  776. commonRefund(latest, latest.getRefundMoney(), refundReq.getOperator(), goodsDon, sku,
  777. outRefundNo, refundType, null, latest.getRefundBalance(), refundReq.getChatImg(),
  778. refundReq.getDeductBalance(), null, true);
  779. refundUsedGalaxyCoin(latest);
  780. latest.setStatus(OrderDon.Status.refund);
  781. if (orderDonMapper.update(latest, Wrappers.lambdaUpdate(OrderDon.class)
  782. .ne(OrderDon::getStatus, OrderDon.Status.refund)
  783. .eq(OrderDon::getId, latest.getId())) != 1) {
  784. throw BusinessRuntimeException.getInstance("订单退款状态更新冲突");
  785. }
  786. if (!orderDonBusinessEventService.markSuccess(latest.getId(), OrderDonBusinessEvent.Type.refund, workerToken)) {
  787. throw BusinessRuntimeException.getInstance("订单退款幂等状态更新冲突");
  788. }
  789. }
  790. private void refundUsedGalaxyCoin(OrderDon orderDon) {
  791. OrderDonGalaxyCoinRecord record = orderDonGalaxyCoinRecordMapper.selectOne(
  792. Wrappers.lambdaQuery(OrderDonGalaxyCoinRecord.class)
  793. .eq(OrderDonGalaxyCoinRecord::getOrderId, orderDon.getId())
  794. .eq(OrderDonGalaxyCoinRecord::getSource, OrderDonGalaxyCoinRecord.Source.ordinary.ordinal())
  795. .last("limit 1"));
  796. if (record == null || record.getGalaxyCoin() == null || record.getGalaxyCoin().compareTo(BigDecimal.ZERO) <= 0) {
  797. return;
  798. }
  799. userGalaxyCoinService.recordOrderRefundGalaxyCoinIfValid(orderDon.getId(), record.getUserId(),
  800. record.getGalaxyCoin(), OrderDonGalaxyCoinRecord.Source.ordinary);
  801. }
  802. private String getMultiQuantityRefundType(OrderDon orderDon) {
  803. BigDecimal money = Optional.ofNullable(orderDon.getMoney()).orElse(BigDecimal.ZERO);
  804. BigDecimal balance = Optional.ofNullable(orderDon.getBalance()).orElse(BigDecimal.ZERO);
  805. if (money.compareTo(BigDecimal.ZERO) > 0 && balance.compareTo(BigDecimal.ZERO) > 0) {
  806. return OrderRefundReq.RefundType.bxj.name();
  807. }
  808. if (money.compareTo(BigDecimal.ZERO) == 0 && balance.compareTo(BigDecimal.ZERO) > 0) {
  809. return OrderRefundReq.RefundType.balance.name();
  810. }
  811. return OrderRefundReq.RefundType.money.name();
  812. }
  813. private String buildMultiQuantityRefundNo(Long orderId) throws Exception {
  814. return Codec.DoDigest.custom()
  815. .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
  816. .setStringData("multi-order-refund:" + orderId)
  817. .toHexString();
  818. }
  819. @Override
  820. @Transactional(rollbackFor = Throwable.class)
  821. public void unifiedUpgradeRefund(OrderRefundReq refundReq) throws Exception {
  822. UpgradeOrderDon orderDon = upgradeOrderDonMapper.selectById(refundReq.getOrderId());
  823. UpgradePackage upgradePackage = upgradePackageMapper.selectById(orderDon.getPackageId());
  824. if (StrUtil.isEmpty(refundReq.getRefundType())) {
  825. refundReq.setRefundType("money");
  826. }
  827. String refundType = refundReq.getRefundType();
  828. //校验订单是否符合退款
  829. checkUpgradeOrderRefund(orderDon, refundReq);
  830. //空订单关闭
  831. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0 && orderDon.getBalance().compareTo(BigDecimal.ZERO) == 0) {
  832. orderDon.setStatus(UpgradeOrderDon.Status.refund);
  833. upgradeOrderDonMapper.updateById(orderDon);
  834. return;
  835. }
  836. Long userId = orderDon.getUserId();
  837. List<Long> userIdList = null;
  838. //检验gpt套餐
  839. if (upgradePackage.getGoodsId() == 18) {
  840. userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  841. //是否有更高级的套餐
  842. UpgradeOrderDon more = upgradeOrderDonMapper.selectOne(Wrappers.lambdaQuery(UpgradeOrderDon.class)
  843. .in(UpgradeOrderDon::getUserId, userIdList)
  844. .eq(UpgradeOrderDon::getRelationId, orderDon.getRelationId())
  845. .gt(UpgradeOrderDon::getNum, orderDon.getNum())
  846. .eq(UpgradeOrderDon::getStatus, UpgradeOrderDon.Status.complete)
  847. .last("limit 1"));
  848. if (more != null) {
  849. throw BusinessRuntimeException.getInstance("请先退掉其更高级套餐");
  850. }
  851. }
  852. //调用第三方接口退款
  853. String outNo = orderRefundService.centerUpgradeRefund(refundReq, orderDon);
  854. orderDon.setRefundDesc(refundReq.getRefundDesc());
  855. //记录退款信息
  856. commonUpgradeRefund(orderDon, refundReq.getRefundMoney(), refundReq.getOperator(), upgradePackage, outNo, refundType, refundReq.getIsOnly(), refundReq.getRefundBalance(), refundReq.getChatImg());
  857. //修改订单状态
  858. orderDon.setStatus(UpgradeOrderDon.Status.refund);
  859. upgradeOrderDonMapper.updateById(orderDon);
  860. //扣除套餐次数
  861. if (upgradePackage.getGoodsId() == 26) {
  862. MidjourneyUser midjourneyUser = midjourneyUserMapper.selectOne(Wrappers.lambdaQuery(MidjourneyUser.class).eq(MidjourneyUser::getRelationId, orderDon.getRelationId()));
  863. if (midjourneyUser != null) {
  864. int update = midjourneyUserMapper.update(null, Wrappers.lambdaUpdate(MidjourneyUser.class)
  865. .set(MidjourneyUser::getMjUpgradeNum, midjourneyUser.getMjUpgradeNum() < upgradePackage.getNum() ? 0 : midjourneyUser.getMjUpgradeNum() - upgradePackage.getNum())
  866. .eq(MidjourneyUser::getId, midjourneyUser.getId()));
  867. if (update == 0) {
  868. log.info("midjourneyUser 套餐包增值失败 id:{},orderId:{}", midjourneyUser.getId(), orderDon.getId());
  869. }
  870. Long decr = redisService.decr(RedisService.key.MIDJOURNEY_UPGRADE_LIMIT.getName() + midjourneyUser.getId(), upgradePackage.getNum().longValue());
  871. if (decr < 0) {
  872. redisService.set(RedisService.key.MIDJOURNEY_UPGRADE_LIMIT.getName() + midjourneyUser.getId(), 0L);
  873. }
  874. }
  875. }
  876. //扣除nano套餐次数
  877. if (upgradePackage.getGoodsId() == Constant.NANO_GOODS_ID) {
  878. NanoUserQuota nanoUserQuota = nanoUserQuotaMapper.selectOne(Wrappers.lambdaQuery(NanoUserQuota.class).eq(NanoUserQuota::getRelationId, orderDon.getRelationId()).last("limit 1"));
  879. if (nanoUserQuota != null) {
  880. int update = nanoUserQuotaMapper.update(null, Wrappers.lambdaUpdate(NanoUserQuota.class)
  881. .set(NanoUserQuota::getRemainingQuota, nanoUserQuota.getRemainingQuota() < upgradePackage.getNum() ? 0 : nanoUserQuota.getRemainingQuota() - upgradePackage.getNum())
  882. .set(NanoUserQuota::getTotalQuota, nanoUserQuota.getTotalQuota() <= upgradePackage.getNum() ? nanoUserQuota.getTotalQuota() : nanoUserQuota.getTotalQuota() - upgradePackage.getNum())
  883. .eq(NanoUserQuota::getId, nanoUserQuota.getId()));
  884. if (update == 0) {
  885. log.info("nano user 套餐包增值失败 id:{},orderId:{}", nanoUserQuota.getId(), orderDon.getId());
  886. }
  887. }
  888. }
  889. //扣除gpt套餐升级
  890. if (upgradePackage.getGoodsId() == 18) {
  891. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class).eq(ChatgptUser::getRelationId, orderDon.getRelationId()));
  892. if (chatgptUser != null) {
  893. GroupsRelation relation = groupsRelationMapper.selectById(chatgptUser.getRelationId());
  894. GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
  895. GoodsDonSku sku = skuMapper.selectById(groupsTrips.getSkuId());
  896. //原先sku的套餐
  897. Long gptLimitTime = sku.getGptLimitTime();
  898. Integer gptLimitNum = sku.getGptLimitNum();
  899. //次等套餐的规格
  900. UpgradeOrderDon secondUpgrade = upgradeOrderDonMapper.selectOne(Wrappers.lambdaQuery(UpgradeOrderDon.class)
  901. .in(UpgradeOrderDon::getUserId, userIdList)
  902. .eq(UpgradeOrderDon::getRelationId, orderDon.getRelationId())
  903. .lt(UpgradeOrderDon::getNum, orderDon.getNum())
  904. .eq(UpgradeOrderDon::getStatus, UpgradeOrderDon.Status.complete)
  905. .last("limit 1"));
  906. Long renewSkuId = chatgptUser.getRenewSkuId();
  907. //续费升级
  908. GoodsDonSku renewSku = null;
  909. if (renewSkuId != null) {
  910. renewSku = goodsDonSkuMapper.selectById(renewSkuId);
  911. gptLimitTime = renewSku.getGptLimitTime();
  912. gptLimitNum = renewSku.getGptLimitNum();
  913. }
  914. if (secondUpgrade != null) {
  915. gptLimitTime = secondUpgrade.getTime();
  916. gptLimitNum = secondUpgrade.getNum();
  917. if (renewSku != null) {
  918. //低级套餐
  919. GoodsDonSku secondSkuUpGrade = goodsDonSkuMapper.selectById(secondUpgrade.getSkuId());
  920. //续费升级套餐更高
  921. if (renewSku.getMonths() >= secondSkuUpGrade.getMonths() && renewSku.getGptLimitNum() >= secondSkuUpGrade.getGptLimitNum() && renewSku.getGptLimitTime() <= secondSkuUpGrade.getGptLimitTime()) {
  922. gptLimitTime = renewSku.getGptLimitTime();
  923. gptLimitNum = renewSku.getGptLimitNum();
  924. }
  925. }
  926. }
  927. Long packageId = 0l;
  928. //降级套餐
  929. if (secondUpgrade != null) {
  930. packageId = secondUpgrade.getPackageId();
  931. }
  932. int update = chatgptUserMapper.update(null, Wrappers.lambdaUpdate(ChatgptUser.class)
  933. .set(ChatgptUser::getLimitTime, gptLimitTime)
  934. .set(ChatgptUser::getLimitNum, gptLimitNum)
  935. .set(ChatgptUser::getPackageId, packageId)
  936. //无次等套餐 不需要清除套餐时间
  937. .set(secondUpgrade == null, ChatgptUser::getClearPackageTime, null)
  938. .eq(ChatgptUser::getId, chatgptUser.getId()));
  939. if (update == 0) {
  940. log.info("chatgptUser 升级套餐包增值失败 id:{},orderId:{}", chatgptUser.getId(), orderDon.getId());
  941. }
  942. }
  943. }
  944. //扣除luma套餐次数
  945. if (upgradePackage.getGoodsId() == Constant.LUMA_GOODS_ID) {
  946. LumaUser lumaUser = lumaUserMapper.selectOne(Wrappers.lambdaQuery(LumaUser.class).eq(LumaUser::getRelationId, orderDon.getRelationId()));
  947. if (lumaUser != null) {
  948. int update = lumaUserMapper.update(null, Wrappers.lambdaUpdate(LumaUser.class)
  949. .set(LumaUser::getNum, lumaUser.getNum() < upgradePackage.getNum() ? 0 : lumaUser.getNum() - upgradePackage.getNum())
  950. .eq(LumaUser::getId, lumaUser.getId()));
  951. if (update == 0) {
  952. log.info("lumaUser 套餐包增值失败 id:{},orderId:{}", lumaUser.getId(), orderDon.getId());
  953. }
  954. Long decr = redisService.decr(RedisService.key.LUMA_NUM_LIMIT.getName() + lumaUser.getId(), upgradePackage.getNum().longValue());
  955. if (decr < 0) {
  956. redisService.set(RedisService.key.LUMA_NUM_LIMIT.getName() + lumaUser.getId(), 0L);
  957. }
  958. }
  959. }
  960. }
  961. /**
  962. * 退款后 处理关联
  963. */
  964. public void commonUpgradeRefund(UpgradeOrderDon orderDon, BigDecimal refundMoney, String operator, UpgradePackage upgradePackage, String outNo, String refundType, Boolean isOnly, BigDecimal refundBalance, String chatImg) {
  965. TASK_POOL.execute(() -> {
  966. orderRefundService.refundUpgradeRecord(orderDon, refundMoney, refundBalance, upgradePackage, operator, outNo, refundType, chatImg);
  967. //退等比例
  968. if (isOnly != null && isOnly) {
  969. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.refund, 0L, orderDon.getId(), upgradePackage.getName()+ UserBalanceSourceRecord.Source.refund.getDesc(), true);
  970. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  971. orderDon.setRefundBalance(orderDonRefundBalance.add(refundBalance));
  972. }
  973. // //若存在余额支付,退还余额
  974. // if (isOnly == null && orderDon.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  975. // userBenefitsService.addUserBalance(orderDon.getUserId(), orderDon.getBalance(), UserBalanceSourceRecord.Source.refund, 0L, orderDon.getId(), upgradePackage.getName() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  976. // }
  977. //是否全额退款
  978. // BigDecimal orderDonRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  979. // BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  980. // if (orderDonRefundMoney.add(orderDonRefundBalance).compareTo(orderDon.getMoney().add(Optional.ofNullable(orderDon.getBalance()).orElse(BigDecimal.ZERO))) == 0) {
  981. // //是否使用银河币支付
  982. // OrderDonGalaxyCoinRecord orderDonGalaxyCoinRecord = orderDonGalaxyCoinRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonGalaxyCoinRecord.class)
  983. // .eq(OrderDonGalaxyCoinRecord::getOrderId, orderDon.getId())
  984. // .eq(OrderDonGalaxyCoinRecord::getSource, OrderDonGalaxyCoinRecord.Source.upgrade.ordinal())
  985. // .last("limit 1"));
  986. // if (orderDonGalaxyCoinRecord != null) {
  987. // //有效时,返还银河币 并记录
  988. // userGalaxyCoinService.recordOrderRefundGalaxyCoinIfValid(orderDon.getId(), orderDonGalaxyCoinRecord.getUserId(), orderDonGalaxyCoinRecord.getGalaxyCoin().abs(), OrderDonGalaxyCoinRecord.Source.upgrade);
  989. // }
  990. // }
  991. //扣除 该笔订单产生的返现银河币
  992. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) > 0) {
  993. userGalaxyCoinService.subOrderGenerateGalaxyCoin(orderDon.getId(), OrderDonGalaxyCoinRecord.Source.upgrade);
  994. }
  995. //余额现金混合退款
  996. if (OrderRefundReq.RefundType.bxj.name().equals(refundType)) {
  997. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.refund, 0L, orderDon.getId(), upgradePackage.getName() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  998. }
  999. if (UpgradeOrderDon.Type.BALANCE.getType().equals(refundType)) {
  1000. if (isOnly == null && orderDon.getMoney().compareTo(BigDecimal.ZERO) > 0) {
  1001. userBenefitsService.addUserBalance(orderDon.getUserId(), refundMoney, UserBalanceSourceRecord.Source.refund, 0L, orderDon.getId(), upgradePackage.getName() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  1002. }
  1003. }
  1004. });
  1005. }
  1006. /**
  1007. * 校验订单是否符合退款操作
  1008. */
  1009. private void checkUpgradeOrderRefund(UpgradeOrderDon orderDon, OrderRefundReq refundReq) {
  1010. if (orderDon == null) {
  1011. throw BusinessRuntimeException.getInstance("订单不存在");
  1012. }
  1013. BigDecimal orderDonRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  1014. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  1015. String refundType = refundReq.getRefundType();
  1016. // if (orderDon.getType() == UpgradeOrderDon.Type.BALANCE && !UpgradeOrderDon.Type.BALANCE.getType().equals(refundType)) {
  1017. // throw BusinessRuntimeException.getInstance("余额支付的订单不支持金额退款");
  1018. // }
  1019. if (UpgradeOrderDon.Status.refund == orderDon.getStatus()) {
  1020. throw BusinessRuntimeException.getInstance("该订单已退款");
  1021. }
  1022. if (UpgradeOrderDon.Status.noPayment == orderDon.getStatus() || UpgradeOrderDon.Status.close == orderDon.getStatus()) {
  1023. throw BusinessRuntimeException.getInstance("订单{0}状态不支持退款", orderDon.getStatus());
  1024. }
  1025. BigDecimal refundMoney = refundReq.getRefundMoney();
  1026. BigDecimal money = orderDon.getMoney();
  1027. BigDecimal balance = orderDon.getBalance();
  1028. BigDecimal refundBalance = refundReq.getRefundBalance();
  1029. //余额退款
  1030. if (UpgradeOrderDon.Type.BALANCE.getType().equals(refundType)) {
  1031. refundMoney = orderDonRefundBalance.add(refundMoney);
  1032. if (UpgradeOrderDon.Type.BALANCE != orderDon.getType() && refundMoney.compareTo(money) > 0) {
  1033. throw BusinessRuntimeException.getInstance("退款余额大于订单支付金额");
  1034. }
  1035. orderDon.setRefundBalance(refundMoney);
  1036. orderDon.setRefundMoney(BigDecimal.ZERO);
  1037. } else if (OrderRefundReq.RefundType.bxj.name().equals(refundType)) {
  1038. balance = balance.add(money);
  1039. if (refundBalance.compareTo(balance) > 0) {
  1040. throw BusinessRuntimeException.getInstance("退款余额大于订单支付余额");
  1041. }
  1042. refundBalance = refundBalance.add(orderDonRefundBalance);
  1043. orderDon.setRefundBalance(refundBalance);
  1044. refundMoney = orderDonRefundMoney.add(refundMoney);
  1045. if (refundMoney.compareTo(money) > 0) {
  1046. throw BusinessRuntimeException.getInstance("退款金额大于订单支付金额");
  1047. }
  1048. orderDon.setRefundMoney(refundMoney);
  1049. } else {
  1050. //退金额
  1051. refundMoney = orderDonRefundMoney.add(refundMoney);
  1052. if (refundMoney.compareTo(money) > 0) {
  1053. throw BusinessRuntimeException.getInstance("退款金额大于订单支付金额");
  1054. }
  1055. orderDon.setRefundMoney(refundMoney);
  1056. }
  1057. if (!redisService.setNx(String.format("%s", refundReq.getOrderId()), refundReq.getOrderId(), 10l)) {
  1058. throw BusinessRuntimeException.getInstance("请勿重复点击,正在退款中..");
  1059. }
  1060. }
  1061. public String wxRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
  1062. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) <=0){
  1063. return StrUtil.EMPTY;
  1064. }
  1065. long time = System.currentTimeMillis();
  1066. //退款订单号
  1067. String outRefundNo = Codec.DoDigest.custom()
  1068. .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
  1069. .setStringData(time + String.valueOf(orderDon.getId()))
  1070. .toHexString();
  1071. weChatService.refundWxOrder(weChatConfig.getAppid(),
  1072. Optional.ofNullable(orderDon.getShopId()).orElse(ShopConfig.WX_DEFAULT_APP_ID),
  1073. orderDon.getTransactionId(),
  1074. outRefundNo,
  1075. orderDon.getMoney(),
  1076. refundReq.getRefundMoney(),
  1077. weChatConfig.getNotifyDomain() + "manage/order/wx/refund/notify");
  1078. //记录退款信息
  1079. return outRefundNo;
  1080. }
  1081. @Override
  1082. public void wxRefundNotify(Map<String, String> map) throws Exception {
  1083. ShopConfig callbackShop = shopConfigMapper.getByAppId(map.get("mch_id"));
  1084. if (callbackShop == null || StrUtil.isBlank(callbackShop.getSecret())) {
  1085. throw BusinessRuntimeException.getInstance("退款回调商户不存在");
  1086. }
  1087. String md5Key = Codec.DoDigest.custom().setAlgorithm(Codec.DoDigest.Algorithm.MD5)
  1088. .setStringData(callbackShop.getSecret()).toHexString();
  1089. String reqInfoXml = Codec.DoCipher.custom()
  1090. .setAlgorithm(Codec.DoCipher.Trans.AES_ECB_PKCS7Padding)
  1091. .setBase64Data(map.get("req_info")).setStringKey(md5Key).ofDecrypt().toText();
  1092. log.info("=== 退款数据解密: \n {}", reqInfoXml);
  1093. Map<String, String> refund = Xmls.toMap(reqInfoXml);
  1094. String transactionId = refund.get("transaction_id");
  1095. OrderDon order = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  1096. .eq(OrderDon::getTransactionId, transactionId).last("limit 1"));
  1097. if (order == null) {
  1098. throw BusinessRuntimeException.getInstance("退款回调订单不存在");
  1099. }
  1100. String expectedRefundNo = buildMultiQuantityRefundNo(order.getId());
  1101. boolean multiQuantity = orderDonTicketRecordService.exists(order.getId());
  1102. if (!multiQuantity) {
  1103. log.info("微信普通订单退款回调, transactionId:{}, outRefundNo:{}",
  1104. transactionId, refund.get("out_refund_no"));
  1105. return;
  1106. }
  1107. if (order.getType() != OrderDon.Type.WeChat) {
  1108. throw BusinessRuntimeException.getInstance("退款回调支付方式不匹配");
  1109. }
  1110. validateWxRefundCallback(refund, order, callbackShop, expectedRefundNo);
  1111. String status = refund.get("refund_status");
  1112. if ("SUCCESS".equals(status)) {
  1113. OrderDonBusinessEvent event = orderDonBusinessEventService.get(
  1114. order.getId(), OrderDonBusinessEvent.Type.refund);
  1115. if (event != null && event.getStatus() == OrderDonBusinessEvent.Status.success) {
  1116. return;
  1117. }
  1118. if (event == null) {
  1119. log.error("WeChat refund succeeded without a local refund event, orderId:{}", order.getId());
  1120. throw BusinessRuntimeException.getInstance("退款回调缺少本地退款记录");
  1121. }
  1122. if (event.getStatus() == OrderDonBusinessEvent.Status.failed
  1123. && StrUtil.isBlank(event.getWorkerToken())) {
  1124. String callbackToken = UUID.randomUUID().toString().replace("-", "");
  1125. orderDonTicketRecordService.startRefund(order.getId(), callbackToken);
  1126. event = orderDonBusinessEventService.get(order.getId(), OrderDonBusinessEvent.Type.refund);
  1127. }
  1128. if (event.getStatus() != OrderDonBusinessEvent.Status.processing
  1129. || StrUtil.isBlank(event.getWorkerToken())) {
  1130. throw BusinessRuntimeException.getInstance("退款回调状态异常");
  1131. }
  1132. GoodsDon goods = goodsDonMapper.selectById(order.getGoodsId());
  1133. GoodsDonSku sku = order.getSkuId() == null ? null : goodsDonSkuMapper.selectById(order.getSkuId());
  1134. OrderRefundReq request = buildRecoveryRefundRequest(order);
  1135. String workerToken = event.getWorkerToken();
  1136. transactionTemplate.executeWithoutResult(tx -> finishMultiQuantityRefund(
  1137. request, order, goods, sku, expectedRefundNo,
  1138. getMultiQuantityRefundType(order), workerToken));
  1139. return;
  1140. }
  1141. if ("CHANGE".equals(status) || "REFUNDCLOSE".equals(status)) {
  1142. OrderDonBusinessEvent event = orderDonBusinessEventService.get(
  1143. order.getId(), OrderDonBusinessEvent.Type.refund);
  1144. if (event != null && event.getStatus() == OrderDonBusinessEvent.Status.processing
  1145. && StrUtil.isNotBlank(event.getWorkerToken())) {
  1146. orderDonTicketRecordService.restoreRefund(order.getId(), event.getWorkerToken(),
  1147. "WeChat refund " + status);
  1148. }
  1149. log.error("微信批量订单退款失败, orderId:{}, status:{}", order.getId(), status);
  1150. }
  1151. }
  1152. private void validateWxRefundCallback(Map<String, String> refund, OrderDon order,
  1153. ShopConfig callbackShop, String expectedRefundNo) {
  1154. long expectedMoney = Optional.ofNullable(order.getMoney()).orElse(BigDecimal.ZERO).longValueExact();
  1155. if (!StrUtil.equals(callbackShop.getAppId(), refundShopId(order))
  1156. || !StrUtil.equals(callbackShop.getAppId(), refund.get("mch_id"))
  1157. || !StrUtil.equals(weChatConfig.getAppid(), refund.get("appid"))
  1158. || !StrUtil.equals(expectedRefundNo, refund.get("out_refund_no"))
  1159. || !StrUtil.equals(order.getTransactionId(), refund.get("transaction_id"))
  1160. || !StrUtil.equals(order.getOrderNo(), refund.get("out_trade_no"))
  1161. || parseCent(refund.get("total_fee")) != expectedMoney
  1162. || parseCent(refund.get("refund_fee")) != expectedMoney) {
  1163. throw BusinessRuntimeException.getInstance("微信退款回调订单信息不匹配");
  1164. }
  1165. }
  1166. @Override
  1167. @Transactional(rollbackFor = Throwable.class)
  1168. public void changeRelation(ChangeRelationReq req) throws Exception {
  1169. Long relationId = req.getRelationId();
  1170. Long groupId = req.getGroupsId();
  1171. UserTicketClearedRecord.Source source = req.getSource();
  1172. if (source == null) source = UserTicketClearedRecord.Source.change_ticket;
  1173. GroupsRelation relation = relationMapper.selectById(relationId);
  1174. Long yhsId = relation == null ? null : relation.getYhsId();
  1175. Assert.notNull(relation, "车票已不存在");
  1176. if (relation.getRechargeStatus() != null) {
  1177. throw BusinessRuntimeException.getInstance("代充账号车票无法更换车票");
  1178. }
  1179. //冻结中 不允许更换车票
  1180. if (relation.getIsFrozen()) {
  1181. throw BusinessRuntimeException.getInstance("用户车票冻结中,无法更换车票");
  1182. }
  1183. Integer reservedDays = relation.getReservedDays();
  1184. String key = RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getName() + relationId;
  1185. if (!redisService.setNx(key, relationId, RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getTimeout())) {
  1186. throw BusinessRuntimeException.getInstance("正在更换车票中..");
  1187. }
  1188. Long userId = relation.getUserId();
  1189. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  1190. OrderDonTicketRecord multiTicketRecord = orderDonTicketRecordService.getActiveByRelationIdForUpdate(relationId);
  1191. if (multiTicketRecord != null
  1192. && multiTicketRecord.getStatus() == OrderDonTicketRecord.Status.refunding) {
  1193. throw BusinessRuntimeException.getInstance("订单退款处理中,暂不支持更换车票");
  1194. }
  1195. try {
  1196. log.info("用户userId:{}更换车票relationId:{}", userId, relationId);
  1197. OrderDon orderDon = multiTicketRecord == null
  1198. ? orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  1199. .in(OrderDon::getUserId, userIdList)
  1200. .eq(OrderDon::getRelationId, relationId)
  1201. .notIn(OrderDon::getStatus, Constant.noOrderStatus)
  1202. .orderByDesc(OrderDon::getId)
  1203. .last("limit 1"))
  1204. : orderDonMapper.selectById(multiTicketRecord.getOrderId());
  1205. OrderDiscountPlusPurchaseSkuRelation plusPurchaseSkuRelation = null;
  1206. List<Long> plus_relationList = null;
  1207. if (orderDon == null) {
  1208. List<OrderDiscountPlusPurchaseSkuRelation> plusPurchaseSkuRelations = orderDiscountPlusPurchaseSkuRelationMapper.selectPlusRelationByIdAndUserId(relation.getId(), relation.getUserId());
  1209. for (OrderDiscountPlusPurchaseSkuRelation data : plusPurchaseSkuRelations) {
  1210. String relationIds = data.getRelationIds();
  1211. if (StrUtil.isEmpty(relationIds)) {
  1212. return;
  1213. }
  1214. List<Long> relationList = Jsons.parseList(relationIds, Long.class);
  1215. if (relationList.contains(relationId)) {
  1216. plusPurchaseSkuRelation = data;
  1217. break;
  1218. }
  1219. }
  1220. if (plusPurchaseSkuRelation != null) {
  1221. String relationIds = plusPurchaseSkuRelation.getRelationIds();
  1222. if (StrUtil.isNotEmpty(relationIds)) {
  1223. plus_relationList = Jsons.parseList(relationIds, Long.class);
  1224. if (plus_relationList.contains(relationId)) {
  1225. orderDon = new OrderDon();
  1226. GroupsRelationView groupsRelationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder().field(GroupsRelationView::getId, relationId).build());
  1227. Assert.notNull(groupsRelationView, "车票已不存在");
  1228. orderDon.setUserId(groupsRelationView.getUserId());
  1229. orderDon.setSkuId(groupsRelationView.getSkuId());
  1230. orderDon.setGoodsId(groupsRelationView.getGoodsId());
  1231. orderDon.setStatus(OrderDon.Status.complete);
  1232. orderDon.setOrderType(1);
  1233. }
  1234. }
  1235. }
  1236. }
  1237. Assert.notNull(orderDon, "订单不存在");
  1238. // if (orderDon.getStatus() == OrderDon.Status.refund) {
  1239. // throw BusinessRuntimeException.getInstance("订单已退款");
  1240. // }
  1241. //获取新车队
  1242. LambdaQueryWrapper<GroupsTrips> queryWrapper = Wrappers.lambdaQuery(GroupsTrips.class)
  1243. .eq(GroupsTrips::getSkuId, orderDon.getSkuId())
  1244. .eq(GroupsTrips::getId, groupId)
  1245. .ne(GroupsTrips::getId, relation.getGroupsId())
  1246. .ne(GroupsTrips::getStatus, GroupsTrips.Status.down)
  1247. .last("limit 1");
  1248. GroupsTrips groups = groupsMapper.selectOne(queryWrapper);
  1249. if (groups == null) throw BusinessRuntimeException.getInstance("车队不存在或已下架");
  1250. if (!Constant.AI_goodsIds.contains(orderDon.getGoodsId()) && groups.getAvailableNum() <= 0) {
  1251. throw BusinessRuntimeException.getInstance("该新车位人员已满");
  1252. }
  1253. Integer relationNum = groups.getNum();
  1254. //获取新车队车位
  1255. GroupsRelation newRelation;
  1256. Boolean isOutside = req.getIsOutside();
  1257. if (Constant.AI_goodsIds.contains(orderDon.getGoodsId()) && ((isOutside != null && isOutside) || groups.getAvailableNum() == 0) && groups.getNum() > 1) {
  1258. //Ai车队 额外增加车位 并不让上车
  1259. newRelation = getChatGPTOutsideRelation(orderDon.getUserId(), groupId, relationNum, 1);
  1260. } else {
  1261. newRelation = getRelationThisTrips(orderDon.getUserId(), groupId, 1);
  1262. }
  1263. //校验座位
  1264. int update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  1265. .set(GroupsRelation::getUserId, userId)
  1266. .eq(GroupsRelation::getUserId, 0)
  1267. .eq(GroupsRelation::getId, newRelation.getId()));
  1268. if (update == 0) {
  1269. throw BusinessRuntimeException.getInstance("系统繁忙,请重新操作");
  1270. }
  1271. newRelation.setUserId(userId);
  1272. newRelation.setStartTime(relation.getStartTime());
  1273. newRelation.setExpiryTime(relation.getExpiryTime());
  1274. newRelation.setYhsId(yhsId);
  1275. newRelation.setCmt(relation.getCmt());
  1276. newRelation.setCustomerService(relation.getCustomerService());
  1277. if (newRelation.getStatus() != GroupsRelation.Status.outside) {
  1278. newRelation.setStatus(GroupsRelation.Status.validity);
  1279. }
  1280. //代充信息
  1281. newRelation.setRechargeStatus(relation.getRechargeStatus());
  1282. newRelation.setRechargeNum(relation.getRechargeNum());
  1283. newRelation.setRechargeRemainNum(relation.getRechargeRemainNum());
  1284. newRelation.setSubmitTime(relation.getSubmitTime());
  1285. newRelation.setSendTime(relation.getSendTime());
  1286. newRelation.setAccount(relation.getAccount());
  1287. newRelation.setPassword(relation.getPassword());
  1288. newRelation.setGptTaskId(relation.getGptTaskId());
  1289. newRelation.setCardKey(relation.getCardKey());
  1290. newRelation.setGptToken(relation.getGptToken());
  1291. //补偿时长
  1292. newRelation.setCompensationDays(relation.getCompensationDays());
  1293. //清除原先车票
  1294. relation.setNewRelationId(newRelation.getId());
  1295. relationClearService.clearTicket(relation, source);
  1296. //兜底处理 多余车票
  1297. if (multiTicketRecord == null) {
  1298. clearOtherChangeTicket(userId, relationId, newRelation, orderDon.getSkuId());
  1299. }
  1300. //奈飞车票
  1301. if (orderDon.getGoodsId() == 1) {
  1302. User user = userMapper.selectById(newRelation.getUserId());
  1303. GroupsTrips groupsTrips = groupsMapper.selectById(newRelation.getGroupsId());
  1304. Account account = accountMapper.selectById(groupsTrips.getAccountId());
  1305. AtomicInteger start = new AtomicInteger(1);
  1306. groupsRelationNetflixService.timingSetNetflix(newRelation.getNum(), user.getNickname(), account.getAccount(), account.getPassword(), newRelation.getExpiryTime(), start);
  1307. }
  1308. if (plusPurchaseSkuRelation != null && plus_relationList != null) {
  1309. plus_relationList.remove(relationId);
  1310. plus_relationList.add(newRelation.getId());
  1311. plusPurchaseSkuRelation.setRelationIds(plus_relationList.toString());
  1312. orderDiscountPlusPurchaseSkuRelationMapper.updateById(plusPurchaseSkuRelation);
  1313. }
  1314. if (source != null && source == UserTicketClearedRecord.Source.abnormal) {
  1315. //将用户异常订单关闭
  1316. workOrderMapper.update(null, Wrappers.lambdaUpdate(WorkOrder.class)
  1317. .set(WorkOrder::getStatus, WorkOrder.Status.close)
  1318. .eq(WorkOrder::getStatus, WorkOrder.Status.waiting)
  1319. .eq(WorkOrder::getUserId, userId)
  1320. .eq(WorkOrder::getRelationId, relationId));
  1321. }
  1322. if (orderDon.getMoney() != null && orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  1323. //是否是实物权益车票
  1324. UserPayEquipmentReceiveBenefitsRecord receiveBenefitsRecord = receiveBenefitsRecordMapper.selectOne(Wrappers.lambdaQuery(UserPayEquipmentReceiveBenefitsRecord.class)
  1325. .eq(UserPayEquipmentReceiveBenefitsRecord::getTicketOrderId, orderDon.getId())
  1326. .eq(UserPayEquipmentReceiveBenefitsRecord::getRelationId, relationId).last("limit 1"));
  1327. if (receiveBenefitsRecord != null) {
  1328. receiveBenefitsRecord.setRelationId(newRelation.getId());
  1329. receiveBenefitsRecordMapper.updateById(receiveBenefitsRecord);
  1330. }
  1331. }
  1332. if ((newRelation.getStartTime() == null || newRelation.getExpiryTime() == null)) {
  1333. if (multiTicketRecord != null) {
  1334. relationMapper.updateById(newRelation);
  1335. return;
  1336. }
  1337. List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.hasPayment));
  1338. if (orderDonList.isEmpty()) {
  1339. orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class)
  1340. .eq(OrderDon::getUserId, userId)
  1341. .eq(OrderDon::getRelationId, relationId)
  1342. .eq(OrderDon::getStatus, OrderDon.Status.complete)
  1343. .orderByDesc(OrderDon::getId)
  1344. .last("limit 1"));
  1345. }
  1346. if (groups.getStatus() == GroupsTrips.Status.waiting) {
  1347. orderDonList.forEach(hasPaymentOrder -> {
  1348. hasPaymentOrder.setRelationId(newRelation.getId());
  1349. orderDonMapper.updateById(hasPaymentOrder);
  1350. });
  1351. relationMapper.updateById(newRelation);
  1352. return;
  1353. }
  1354. orderDonList.forEach((hasPaymentOrder) -> {
  1355. //如果续费增加时间,如果首次则设置当前时间为初始时间
  1356. Date expiryTime = Optional.ofNullable(newRelation.getExpiryTime()).orElse(new Date());
  1357. GoodsDonSku donSku = skuMapper.selectById(hasPaymentOrder.getSkuId());
  1358. Date newDate;
  1359. if (donSku.getDays() != null && donSku.getDays() > 0) {
  1360. newDate = DateUtil.offsetDay(expiryTime, donSku.getDays() * hasPaymentOrder.getNum());
  1361. } else {
  1362. newDate = DateUtil.offset(expiryTime, DateField.MONTH, donSku.getMonths() * hasPaymentOrder.getNum());
  1363. }
  1364. newRelation.setExpiryTime(newDate);
  1365. newRelation.setStartTime(newRelation.getStartTime() == null ? new Date() : null);
  1366. relationMapper.updateById(newRelation);
  1367. hasPaymentOrder.setStatus(OrderDon.Status.complete);
  1368. hasPaymentOrder.setRelationId(newRelation.getId());
  1369. orderDonMapper.updateById(hasPaymentOrder);
  1370. });
  1371. return;
  1372. }
  1373. List<OrderDon> orderDonList = multiTicketRecord == null
  1374. ? orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.complete))
  1375. : java.util.Collections.emptyList();
  1376. orderDonList.forEach(completeOrder->{
  1377. completeOrder.setRelationId(newRelation.getId());
  1378. orderDonMapper.updateById(completeOrder);
  1379. });
  1380. log.info("userId:{}更换车票,原座位号relationId:{}======>新座位号newRelationId:{}", newRelation.getUserId(), relationId, newRelation.getId());
  1381. relationMapper.updateById(newRelation);
  1382. //更换车票 调整GPT相关规格新车队 上车数
  1383. GoodsDonSku sku = goodsDonSkuMapper.selectById(groups.getSkuId());
  1384. groupRelationFrontService.adjustGroupsParkingTime(newRelation.getId(), sku);
  1385. //关闭正在恢复的车票
  1386. if (orderDon.getGoodsId() == Constant.NETFLIX_GID) {
  1387. NetflixUserAccountSubmitRecoverRecord recoverRecord = netflixUserAccountSubmitRecoverRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  1388. .eq(NetflixUserAccountSubmitRecoverRecord::getRelationId, relationId)
  1389. .in(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList)
  1390. .eq(NetflixUserAccountSubmitRecoverRecord::getStatus, 0)
  1391. .last("limit 1"));
  1392. if (recoverRecord != null) {
  1393. recoverRecord.setStatus(3);
  1394. netflixUserAccountSubmitRecoverRecordMapper.updateById(recoverRecord);
  1395. newRelation.setExpiryTime(DateUtil.offsetDay(DateTime.now(), recoverRecord.getRemainDays().intValue()));
  1396. relationMapper.updateById(newRelation);
  1397. } else {
  1398. if (reservedDays != null) {
  1399. newRelation.setExpiryTime(DateUtil.offsetDay(DateTime.now(), reservedDays));
  1400. relationMapper.updateById(newRelation);
  1401. }
  1402. }
  1403. }
  1404. } finally {
  1405. if (redisService.hasKey(key)) {
  1406. redisService.del(key);
  1407. }
  1408. }
  1409. }
  1410. public String zfbRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
  1411. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) <=0){
  1412. return StrUtil.EMPTY;
  1413. }
  1414. AlipayTradeRefundResponse response;
  1415. //支付宝退款
  1416. AlipayClient alipayClient = AliPayClientFactory.getAlipayClient(Optional.ofNullable(orderDon.getShopId()).orElse(ShopConfig.ZFB_DEFAULT_APP_ID));
  1417. AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
  1418. AlipayTradeRefundModel model = new AlipayTradeRefundModel();
  1419. //支付宝交易号
  1420. model.setTradeNo(orderDon.getTransactionId());
  1421. model.setRefundAmount(refundReq.getRefundMoney().divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_EVEN).toString());
  1422. model.setQueryOptions(List.of("gmt_refund_pay"));
  1423. long time = System.currentTimeMillis();
  1424. //退款订单号
  1425. String outRefundNo = Codec.DoDigest.custom()
  1426. .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
  1427. .setStringData(time + String.valueOf(orderDon.getId()))
  1428. .toHexString();
  1429. //退款请求号
  1430. model.setOutRequestNo(outRefundNo);
  1431. request.setBizModel(model);
  1432. String shopId = orderDon.getShopId();
  1433. ShopConfig shopConfig = shopConfigMapper.selectOne(Wrappers.lambdaQuery(ShopConfig.class).eq(ShopConfig::getAppId, orderDon.getShopId()));
  1434. if (shopId != null && shopConfig != null && shopConfig.getIsCert()) {
  1435. response = alipayClient.certificateExecute(request);
  1436. } else {
  1437. response = alipayClient.execute(request);
  1438. }
  1439. if (!response.isSuccess()) throw BusinessRuntimeException.getInstance("退款失败,e:{0}", response.getSubMsg());
  1440. // AliPayRefundRep aliPayRefundRep = Jsons.parseObject(response.getBody(), AliPayRefundRep.class);
  1441. // AliPayRefundRep.AlipayTradeRefundResponse res = aliPayRefundRep.getResponse();
  1442. // orderDon.setRefundMoney(res.getRefundFee().multiply(BigDecimal.valueOf(100)));
  1443. return outRefundNo;
  1444. }
  1445. /**
  1446. * 校验订单是否符合退款操作
  1447. */
  1448. private void checkOrderRefund(OrderDon orderDon, GoodsDon goodsDon, GoodsDonSku sku, OrderRefundReq refundReq) {
  1449. if (orderDon == null) {
  1450. throw BusinessRuntimeException.getInstance("订单不存在");
  1451. }
  1452. validateOrdinaryRefundRequest(orderDon, refundReq);
  1453. BigDecimal orderDonRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  1454. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  1455. String refundType = refundReq.getRefundType();
  1456. // if (orderDon.getType() == OrderDon.Type.BALANCE && !OrderDon.Type.BALANCE.getType().equals(refundType)) {
  1457. // throw BusinessRuntimeException.getInstance("余额支付的订单不支持金额退款");
  1458. // }
  1459. if (OrderDon.Status.refund == orderDon.getStatus()) {
  1460. throw BusinessRuntimeException.getInstance("该订单已退款");
  1461. }
  1462. if (OrderDon.Status.noPayment == orderDon.getStatus() || OrderDon.Status.close == orderDon.getStatus()) {
  1463. throw BusinessRuntimeException.getInstance("订单{0}状态不支持退款", orderDon.getStatus());
  1464. }
  1465. if (goodsDon.getId() == Constant.NETFLIX_GID) {
  1466. Integer selectCount = netflixUserChangeOtherTicketRecordMapper.selectCount(Wrappers.lambdaQuery(NetflixUserChangeOtherTicketRecord.class)
  1467. .eq(NetflixUserChangeOtherTicketRecord::getOrderId, orderDon.getId()));
  1468. if (selectCount > 0) {
  1469. throw BusinessRuntimeException.getInstance("该奈飞车票已替换其他车票,无法退款");
  1470. }
  1471. }
  1472. if (goodsDon.getType() == 1 && sku != null) {
  1473. if (goodsDon.getId() == Constant.CLAUDE_CODE_GOODS_ID) {
  1474. //车票是否存在
  1475. Long relationId = orderDon.getRelationId();
  1476. List<Long> userIdList = userBindRelationService.getRelationUserIdList(orderDon.getUserId(), null);
  1477. Integer selectCount1 = userTicketClearedRecordMapper.selectCount(Wrappers.lambdaQuery(UserTicketClearedRecord.class)
  1478. .eq(UserTicketClearedRecord::getRelationId, relationId)
  1479. .in(UserTicketClearedRecord::getUserId, userIdList)
  1480. .eq(UserTicketClearedRecord::getSource, UserTicketClearedRecord.Source.cc_deduct)
  1481. .gt(UserTicketClearedRecord::getCreatedTime, orderDon.getCreatedTime()));
  1482. if (selectCount1 > 0) {
  1483. //抵扣车票对应的 新车票是否已经退款
  1484. Integer selectCount = claudeCodeDeductOrderRelateMapper.selectDeductUpgradeRelation(relationId, userIdList);
  1485. if (selectCount == 0) {
  1486. throw BusinessRuntimeException.getInstance("车票已被抵扣升级 无法退款");
  1487. }
  1488. }
  1489. }
  1490. //虚拟原订单是否已过期
  1491. Integer months = sku.getMonths();
  1492. Integer days = sku.getDays();
  1493. Integer num = orderDon.getNum();
  1494. DateTime now = DateTime.now();
  1495. DateTime endTime;
  1496. if (days != null && days > 0) {
  1497. endTime = DateUtil.offsetDay(orderDon.getCreatedTime(), days * num);
  1498. } else {
  1499. endTime = DateUtil.offsetMonth(orderDon.getCreatedTime(), months * num);
  1500. }
  1501. // if (now.isAfter(endTime)) {
  1502. // throw BusinessRuntimeException.getInstance("该订单车票已过期");
  1503. // }
  1504. if (orderDon.getOrderType() == 1) {
  1505. //是否有其他付款订单是否过期
  1506. OrderDon otherOrder = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  1507. .eq(OrderDon::getRelationId, orderDon.getRelationId())
  1508. .eq(OrderDon::getUserId, orderDon.getUserId())
  1509. .ne(OrderDon::getId, orderDon.getId())
  1510. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  1511. .eq(OrderDon::getOrderType, 2)
  1512. .orderByDesc(OrderDon::getId)
  1513. .last("limit 1"));
  1514. if (otherOrder != null) {
  1515. throw BusinessRuntimeException.getInstance("该笔订单存在续费订单,请先退掉续费订单");
  1516. }
  1517. }
  1518. }
  1519. BigDecimal refundMoney = refundReq.getRefundMoney();
  1520. BigDecimal refundBalance = refundReq.getRefundBalance();
  1521. BigDecimal money = orderDon.getMoney();
  1522. BigDecimal balance = orderDon.getBalance();
  1523. //余额退款
  1524. if (OrderDon.Type.BALANCE.getType().equals(refundType)) {
  1525. refundMoney = orderDonRefundBalance.add(refundMoney);
  1526. if (OrderDon.Type.BALANCE != orderDon.getType() && refundMoney.compareTo(money) > 0) {
  1527. throw BusinessRuntimeException.getInstance("退款余额大于订单支付金额");
  1528. }
  1529. orderDon.setRefundBalance(refundMoney);
  1530. } else if (OrderRefundReq.RefundType.bxj.name().equals(refundType)) {
  1531. balance = balance.add(money);
  1532. if (orderDon.getGoodsId() == Constant.CLAUDE_CODE_GOODS_ID) {
  1533. ClaudeCodeDeductOrderRelate claudeCodeDeductOrderRelate = claudeCodeDeductOrderRelateMapper.selectOne(Wrappers.lambdaQuery(ClaudeCodeDeductOrderRelate.class).eq(ClaudeCodeDeductOrderRelate::getOrderId, orderDon.getId()).last("limit 1"));
  1534. //特殊处理 cc抵扣升级订单 余额退款
  1535. if (claudeCodeDeductOrderRelate != null && claudeCodeDeductOrderRelate.getDeductMoney() != null) {
  1536. balance = balance.add(claudeCodeDeductOrderRelate.getDeductMoney());
  1537. }
  1538. }
  1539. if (refundBalance != null) {
  1540. if (refundBalance.compareTo(balance) > 0) {
  1541. throw BusinessRuntimeException.getInstance("退款余额大于订单总金额");
  1542. }
  1543. refundBalance = refundBalance.add(orderDonRefundBalance);
  1544. orderDon.setRefundBalance(refundBalance);
  1545. }
  1546. refundMoney = orderDonRefundMoney.add(refundMoney);
  1547. if (refundMoney.compareTo(money) > 0) {
  1548. throw BusinessRuntimeException.getInstance("退款金额大于订单支付金额");
  1549. }
  1550. orderDon.setRefundMoney(refundMoney);
  1551. } else {
  1552. //退金额
  1553. refundMoney = orderDonRefundMoney.add(refundMoney);
  1554. if (refundMoney.compareTo(money) > 0) {
  1555. throw BusinessRuntimeException.getInstance("退款金额大于订单支付金额");
  1556. }
  1557. orderDon.setRefundMoney(refundMoney);
  1558. }
  1559. //礼品卡是否已使用
  1560. GiftCardUserRecord giftCardUserRecord = null;
  1561. if (goodsDon.getSpecialType() != null && goodsDon.getSpecialType() == GoodsDon.SpecialType.giftCard) {
  1562. Integer count = giftCardUserRecordMapper.selectCount(Wrappers.lambdaQuery(GiftCardUserRecord.class)
  1563. .eq(GiftCardUserRecord::getIsUsed, 1)
  1564. .eq(GiftCardUserRecord::getOrderId, orderDon.getId()));
  1565. if (count > 0) {
  1566. throw BusinessRuntimeException.getInstance("该礼品卡已使用无法退款");
  1567. }
  1568. }
  1569. if (!redisService.setNx(String.format("%s", refundReq.getOrderId()), refundReq.getOrderId(), 10l)) {
  1570. throw BusinessRuntimeException.getInstance("请勿重复点击,正在退款中..");
  1571. }
  1572. //礼品卡购买状态
  1573. if (giftCardUserRecord != null) {
  1574. giftCardUserRecord.setIsPay(false);
  1575. giftCardUserRecordMapper.updateById(giftCardUserRecord);
  1576. }
  1577. //校验续费升级规格
  1578. // checkMirrorRenewSku(orderDon);
  1579. }
  1580. /**
  1581. * 普通订单退款仍由管理端选择退款方式,但金额字段必须与退款方式一致。
  1582. * 否则错误地把纯余额订单按 money 提交时,会清票并关闭订单,却不会退回余额。
  1583. */
  1584. private void validateOrdinaryRefundRequest(OrderDon orderDon, OrderRefundReq refundReq) {
  1585. String refundType = refundReq.getRefundType();
  1586. boolean supportedType = OrderRefundReq.RefundType.money.name().equals(refundType)
  1587. || OrderRefundReq.RefundType.balance.name().equals(refundType)
  1588. || OrderRefundReq.RefundType.bxj.name().equals(refundType);
  1589. if (!supportedType) {
  1590. throw BusinessRuntimeException.getInstance("退款类型不正确");
  1591. }
  1592. BigDecimal refundMoney = Optional.ofNullable(refundReq.getRefundMoney()).orElse(BigDecimal.ZERO);
  1593. BigDecimal refundBalance = Optional.ofNullable(refundReq.getRefundBalance()).orElse(BigDecimal.ZERO);
  1594. if (refundMoney.signum() < 0 || refundBalance.signum() < 0) {
  1595. throw BusinessRuntimeException.getInstance("退款金额不能小于0");
  1596. }
  1597. // Existing user-side expired-ticket refunds use money + refundBalance with
  1598. // isOnly=true to return the balance-funded portion while refunding cash.
  1599. // Reject only the malformed management request that carries a balance
  1600. // amount without opting into that established mixed-refund path.
  1601. if (OrderRefundReq.RefundType.money.name().equals(refundType)
  1602. && !Boolean.TRUE.equals(refundReq.getIsOnly())
  1603. && (refundBalance.signum() > 0 || orderDon.getType() == OrderDon.Type.BALANCE)) {
  1604. throw BusinessRuntimeException.getInstance("退款类型与余额退款金额不匹配");
  1605. }
  1606. if (OrderRefundReq.RefundType.balance.name().equals(refundType)
  1607. && !Boolean.TRUE.equals(refundReq.getIsOnly())
  1608. && refundMoney.signum() <= 0 && refundBalance.signum() > 0) {
  1609. throw BusinessRuntimeException.getInstance("退至余额的金额字段不正确");
  1610. }
  1611. }
  1612. /**
  1613. * 退款后 处理关联
  1614. */
  1615. public void commonRefund(OrderDon orderDon, BigDecimal refundMoney, String operator, GoodsDon goodsDon,
  1616. GoodsDonSku sku, String outNo, String refundType, Boolean isOnly,
  1617. BigDecimal refundBalance, String chatImg, BigDecimal deductBalance,
  1618. List<Long> dpRelationIds, boolean multiQuantityOrder) {
  1619. orderRefundService.refundRecord(orderDon, refundMoney, refundBalance, operator, goodsDon, sku, outNo, refundType, chatImg);
  1620. if (shouldRestoreStock(goodsDon, multiQuantityOrder)) {
  1621. goodsDonStockService.upStockRelate(null, orderDon.getId(), "refund");
  1622. }
  1623. try {
  1624. if (!multiQuantityOrder && !Boolean.TRUE.equals(orderDon.getIsDp())) {
  1625. GroupsRelation relation = relationMapper.selectById(orderDon.getRelationId());
  1626. //冻结车票 清除
  1627. if (relation != null && Boolean.TRUE.equals(relation.getIsFrozen())) {
  1628. Optional.ofNullable(receivedRecordMapper.selectOne(Wrappers.lambdaQuery(AccountNetflixFrozenTicketReceivedRecord.class).eq(AccountNetflixFrozenTicketReceivedRecord::getRelationId, relation.getId()).last("limit 1")))
  1629. .ifPresent(rr -> {
  1630. Long sendRelationId = rr.getSendRelationId();
  1631. List<Long> userIdList = userBindRelationService.getRelationUserIdList(orderDon.getUserId(), null);
  1632. GroupsRelation sendRelation = groupsRelationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getId, sendRelationId).in(GroupsRelation::getUserId, userIdList).last("limit 1"));
  1633. if (sendRelation != null) {
  1634. relationClearService.clearTicket(sendRelation, UserTicketClearedRecord.Source.manual);
  1635. }
  1636. });
  1637. }
  1638. //虚物订单退款,清出车队,车票变为已过期
  1639. orderCommonService.clearUnrealGoodsDetail(orderDon, goodsDon.getType(), sku);
  1640. }
  1641. } catch (Exception e) {
  1642. log.error("清除车票错误:{}", StringUtil.getErrorText(e));
  1643. }
  1644. //若存在优惠券使用,退还优惠券
  1645. if (orderDon.getCouponUserId() != null && orderDon.getCouponUserId() != 0L) {
  1646. couponFontService.updateOrderDonCouponStatus(orderDon);
  1647. }
  1648. //退等比例
  1649. if (isOnly != null && isOnly) {
  1650. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.refund, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  1651. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  1652. orderDon.setRefundBalance(orderDonRefundBalance.add(refundBalance));
  1653. }
  1654. //若存在余额支付,退还余额
  1655. // if (isOnly == null && orderDon.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  1656. // BigDecimal addBalance = orderDon.getBalance();
  1657. // //需额外扣除余额
  1658. // if (deductBalance != null && deductBalance.compareTo(BigDecimal.ZERO) > 0) {
  1659. // addBalance = addBalance.subtract(deductBalance);
  1660. // }
  1661. // userBenefitsService.addUserBalance(orderDon.getUserId(), addBalance, UserBalanceSourceRecord.Source.refund, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  1662. // }
  1663. //是否全额退款
  1664. // BigDecimal orderDonRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  1665. // BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  1666. // if (orderDonRefundMoney.add(orderDonRefundBalance).compareTo(orderDon.getMoney().add(Optional.ofNullable(orderDon.getBalance()).orElse(BigDecimal.ZERO))) == 0) {
  1667. // //是否使用银河币支付
  1668. // OrderDonGalaxyCoinRecord orderDonGalaxyCoinRecord = orderDonGalaxyCoinRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonGalaxyCoinRecord.class)
  1669. // .eq(OrderDonGalaxyCoinRecord::getSource, OrderDonGalaxyCoinRecord.Source.ordinary.ordinal())
  1670. // .eq(OrderDonGalaxyCoinRecord::getOrderId, orderDon.getId())
  1671. // .last("limit 1"));
  1672. // if (orderDonGalaxyCoinRecord != null) {
  1673. // //有效时,返还银河币 并记录
  1674. // userGalaxyCoinService.recordOrderRefundGalaxyCoinIfValid(orderDon.getId(), orderDonGalaxyCoinRecord.getUserId(), orderDonGalaxyCoinRecord.getGalaxyCoin().abs(), OrderDonGalaxyCoinRecord.Source.ordinary);
  1675. // }
  1676. // }
  1677. //扣除 该笔订单产生的返现银河币
  1678. if (Optional.ofNullable(orderDon.getMoney()).orElse(BigDecimal.ZERO)
  1679. .compareTo(BigDecimal.ZERO) > 0) {
  1680. userGalaxyCoinService.subOrderGenerateGalaxyCoin(orderDon.getId(), OrderDonGalaxyCoinRecord.Source.ordinary);
  1681. }
  1682. //余额现金混合退款
  1683. if (OrderRefundReq.RefundType.bxj.name().equals(refundType)) {
  1684. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.refund, null, orderDon.getId(), orderDon.getPayTitle() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  1685. }
  1686. try {
  1687. marketFrontService.subSpecificChanceNum(orderDon.getUserId(), orderDon.getId(), orderDon.getGoodsId(), orderDon.getUpdateTime());
  1688. if (goodsDon != null && Objects.equals(goodsDon.getType(), 2)
  1689. && !Boolean.TRUE.equals(orderDon.getIsDistribute())) {
  1690. equipmentDistributeService.subDistributeBenefitsChance(orderDon.getUserId(), orderDon.getId());
  1691. //扣除用户自身实物权益
  1692. userRealOrderBenefitsService.deductUserRealGoodsBenefits(orderDon.getId());
  1693. }
  1694. } catch (Exception e) {
  1695. log.error("wx减少抽奖机会错误,orderId:{},error:{}", orderDon.getId(), e);
  1696. }
  1697. if (OrderRefundReq.RefundType.balance.name().equals(refundType)) {
  1698. if (!Boolean.TRUE.equals(isOnly)) {
  1699. // 普通订单选择“退还至余额”时,退款数额放在 refundMoney;
  1700. // 多件整单退款的余额部分由服务端固定写入 refundBalance。
  1701. BigDecimal balanceAmount = multiQuantityOrder
  1702. ? Optional.ofNullable(refundBalance).orElse(BigDecimal.ZERO)
  1703. : Optional.ofNullable(refundMoney).orElse(BigDecimal.ZERO);
  1704. if (balanceAmount.compareTo(BigDecimal.ZERO) > 0) {
  1705. userBenefitsService.addUserBalance(orderDon.getUserId(), balanceAmount,
  1706. UserBalanceSourceRecord.Source.refund, orderDon.getYhsId(),
  1707. orderDon.getId(), goodsDon.getTitle()
  1708. + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  1709. }
  1710. }
  1711. } else {
  1712. //余额退款不需要扣除积分
  1713. //分销提成积分扣除
  1714. deductDsPoints(orderDon);
  1715. //店铺 分销提成金额扣除
  1716. yhShopDistributeService.deductDsMoney(orderDon);
  1717. //镜像店铺 分销提成金额扣除
  1718. deductUserMirrorShopMoney(orderDon);
  1719. }
  1720. if (Boolean.TRUE.equals(orderDon.getIsFixedDistribute())) {
  1721. //商务提成 因订单退款去掉
  1722. UserDistributeBusinessOrderDonRecord record = businessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(UserDistributeBusinessOrderDonRecord.class)
  1723. .eq(UserDistributeBusinessOrderDonRecord::getOrderId, orderDon.getId())
  1724. .eq(UserDistributeBusinessOrderDonRecord::getStatus, UserDistributeBusinessOrderDonRecord.Status.success)
  1725. .last("limit 1"));
  1726. if (record != null) {
  1727. record.setStatus(UserDistributeBusinessOrderDonRecord.Status.refund);
  1728. businessOrderDonRecordMapper.updateById(record);
  1729. }
  1730. }
  1731. //店铺商务提成
  1732. if (orderDon.getYhsId() != null && orderDon.getYhsId() > 0) {
  1733. YhShopUserDistributeBusinessOrderDonRecord shop_record = yhShopBusinessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(YhShopUserDistributeBusinessOrderDonRecord.class)
  1734. .eq(YhShopUserDistributeBusinessOrderDonRecord::getOrderId, orderDon.getId())
  1735. .eq(YhShopUserDistributeBusinessOrderDonRecord::getStatus, YhShopUserDistributeBusinessOrderDonRecord.Status.success)
  1736. .last("limit 1"));
  1737. if (shop_record != null) {
  1738. shop_record.setStatus(YhShopUserDistributeBusinessOrderDonRecord.Status.refund);
  1739. yhShopBusinessOrderDonRecordMapper.updateById(shop_record);
  1740. }
  1741. }
  1742. //是否是优惠加购关联订单
  1743. if (Boolean.TRUE.equals(orderDon.getIsDp())) {
  1744. OrderDiscountPlusPurchaseSkuRelation discountPlusPurchaseSkuRelation = orderDiscountPlusPurchaseSkuRelationMapper.selectOne(Wrappers.lambdaQuery(OrderDiscountPlusPurchaseSkuRelation.class)
  1745. .eq(OrderDiscountPlusPurchaseSkuRelation::getOrderId, orderDon.getId()).last("limit 1"));
  1746. if (discountPlusPurchaseSkuRelation != null) {
  1747. //选择清除加购车票
  1748. if (CollUtil.isNotEmpty(dpRelationIds)) {
  1749. try {
  1750. List<GroupsRelation> groupsRelations = relationMapper.selectList(Wrappers.lambdaQuery(GroupsRelation.class)
  1751. .eq(GroupsRelation::getUserId, orderDon.getUserId())
  1752. .in(GroupsRelation::getId, dpRelationIds));
  1753. log.info("优惠加购订单orderId:{}退款,清除相关车票relation_ids:{}", orderDon.getId(), dpRelationIds);
  1754. groupsRelations.forEach(relation -> relationClearService.clearTicket(relation, UserTicketClearedRecord.Source.dp));
  1755. } catch (Exception e) {
  1756. }
  1757. }
  1758. String plusOrderIds = discountPlusPurchaseSkuRelation.getPlusOrderIds();
  1759. if (StrUtil.isNotBlank(plusOrderIds)) {
  1760. try {
  1761. log.info("关闭优惠加购orderId:{}关联实物订单", orderDon.getId());
  1762. List<Long> plusOrderIdList = Jsons.parseList(plusOrderIds, Long.class);
  1763. List<OrderDon> relate_orderDons = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class)
  1764. .in(OrderDon::getId, plusOrderIdList)
  1765. .notIn(OrderDon::getStatus, Constant.noOrderStatus));
  1766. relate_orderDons.forEach(relate_o -> {
  1767. //扣除用户自身实物权益
  1768. userRealOrderBenefitsService.deductUserRealGoodsBenefits(relate_o.getId());
  1769. });
  1770. orderDonMapper.update(null, Wrappers.lambdaUpdate(OrderDon.class)
  1771. .set(OrderDon::getStatus, OrderDon.Status.refund)
  1772. .in(OrderDon::getId, plusOrderIdList)
  1773. .ne(OrderDon::getStatus, OrderDon.Status.refund));
  1774. } catch (Exception e) {
  1775. }
  1776. }
  1777. }
  1778. }
  1779. //同步车票退款 重购记录
  1780. Runnable syncRebuyRecords = () -> {
  1781. GroupsRelationExpiryRecord groupsRelationExpiryRecord = groupsRelationExpiryRecordService.getOne(Wrappers.lambdaQuery(GroupsRelationExpiryRecord.class)
  1782. .in(GroupsRelationExpiryRecord::getReBuyOrderId, orderDon.getId())
  1783. .eq(GroupsRelationExpiryRecord::getRelationId, orderDon.getRelationId()).last("limit 1"));
  1784. if (groupsRelationExpiryRecord == null) {
  1785. log.info("订单orderId:{}退款,同步是否有重购记录不是直接续费车票", orderDon.getId());
  1786. List<GroupsRelationExpiryRecord> groupsRelationExpiryRecords = groupsRelationExpiryRecordService.list(Wrappers.lambdaQuery(GroupsRelationExpiryRecord.class)
  1787. .in(GroupsRelationExpiryRecord::getReBuyOrderId, orderDon.getId()));
  1788. log.info("订单orderId:{}退款,重购记录不是直接续费车票大小:{}", orderDon.getId(), groupsRelationExpiryRecords.size());
  1789. if (CollUtil.isNotEmpty(groupsRelationExpiryRecords)) {
  1790. groupsRelationExpiryRecords.forEach(data -> data.setIsReBuy(false));
  1791. groupsRelationExpiryRecordService.saveOrUpdateBatch(groupsRelationExpiryRecords);
  1792. }
  1793. } else {
  1794. groupsRelationExpiryRecord.setIsReBuy(false);
  1795. groupsRelationExpiryRecordService.saveOrUpdate(groupsRelationExpiryRecord);
  1796. }
  1797. };
  1798. if (TransactionSynchronizationManager.isActualTransactionActive()) {
  1799. TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
  1800. @Override
  1801. public void afterCommit() {
  1802. TASK_POOL.execute(syncRebuyRecords);
  1803. }
  1804. });
  1805. } else {
  1806. TASK_POOL.execute(syncRebuyRecords);
  1807. }
  1808. //是否是礼品卡 现金支付订单
  1809. BigDecimal gcCash = orderDon.getGcCash();
  1810. if (gcCash != null && gcCash.compareTo(BigDecimal.ZERO) > 0) {
  1811. giftCardOrderUseRecordService.returnGiftCardCash(orderDon.getId());
  1812. }
  1813. //清除礼品卡
  1814. if (goodsDon.getSpecialType() != null && goodsDon.getSpecialType() == GoodsDon.SpecialType.giftCard) {
  1815. giftCardUserRecordMapper.update(null, Wrappers.lambdaUpdate(GiftCardUserRecord.class)
  1816. .set(GiftCardUserRecord::getIsPay, 0)
  1817. .eq(GiftCardUserRecord::getOrderId, orderDon.getId()));
  1818. }
  1819. //是否是分销订单
  1820. //处理下级渠道分销提成
  1821. handleSubRewards(orderDon);
  1822. //是否是用户套餐优惠权益订单
  1823. if (Objects.equals(orderDon.getGoodsId(), 15L)) {
  1824. UserBenefitsComboRelationRecord userBenefitsComboRelationRecord = userBenefitsComboRelationRecordMapper.selectOne(Wrappers.lambdaQuery(UserBenefitsComboRelationRecord.class)
  1825. .eq(UserBenefitsComboRelationRecord::getOrderId, orderDon.getId()).last("limit 1"));
  1826. if (userBenefitsComboRelationRecord != null) {
  1827. try {
  1828. String relationIds = userBenefitsComboRelationRecord.getRelationIds();
  1829. List<Long> relationIdList = Jsons.parseList(relationIds, Long.class);
  1830. //清空车票或减少车票时间
  1831. relationIdList.forEach(relationId -> {
  1832. orderCommonService.clearUserTicketTime(relationId);
  1833. });
  1834. } catch (Exception e) {
  1835. }
  1836. }
  1837. }
  1838. //HBO GO退款,车队上架
  1839. setUpIfEmpty(orderDon.getGoodsId(), orderDon.getRelationId());
  1840. if (Objects.equals(orderDon.getGoodsId(), Constant.NETFLIX_GID)) {
  1841. List<Long> userIdList = userBindRelationService.getRelationUserIdList(orderDon.getUserId(), null);
  1842. NetflixUserAccountSubmitRecoverRecord recoverRecord = netflixUserAccountSubmitRecoverRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  1843. .eq(NetflixUserAccountSubmitRecoverRecord::getRelationId, orderDon.getRelationId())
  1844. .in(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList)
  1845. .eq(NetflixUserAccountSubmitRecoverRecord::getStatus, 0)
  1846. .last("limit 1"));
  1847. if (recoverRecord != null) {
  1848. recoverRecord.setStatus(3);
  1849. netflixUserAccountSubmitRecoverRecordMapper.updateById(recoverRecord);
  1850. }
  1851. }
  1852. //GPT独立会员
  1853. if (Objects.equals(orderDon.getGoodsId(), Constant.GPT_PLUS_GID)
  1854. && sku != null && Objects.equals(sku.getNum(), 1)) {
  1855. subRechargeNumOrder(orderDon.getUserId(), orderDon.getRelationId(), sku.getMonths(), operator);
  1856. }
  1857. //GPT独立会员退款 或代充退款 退还平台发券
  1858. if ((Objects.equals(orderDon.getGoodsId(), Constant.GPT_PLUS_GID)
  1859. && sku != null && Objects.equals(sku.getNum(), 1))
  1860. || Objects.equals(orderDon.getGoodsId(), Constant.GPT_RECHARGE_GOODS_ID)) {
  1861. //若不存在对应的车票 则清除优惠券
  1862. List<Long> skuIds = goodsDonSkuMapper.selectIdpGptAndRechargeSkuIds(Constant.GPT_PLUS_GID, Constant.GPT_RECHARGE_GOODS_ID);
  1863. List<Long> userIdList = userBindRelationService.getRelationUserIdList(orderDon.getUserId(), null);
  1864. Number number = beanSearcher.searchCount(GroupsRelationView.class, MapUtils.builder()
  1865. .field(GroupsRelationView::getUserId, userIdList).op(Operator.InList)
  1866. .field(GroupsRelationView::getSkuId, skuIds).op(Operator.InList)
  1867. .field(GroupsRelationView::getStatus, GroupsRelation.Status.validity.name())
  1868. .build());
  1869. if (number.intValue() == 0) {
  1870. List<CouponUser> couponUsers = couponUserMapper.selectList(Wrappers.lambdaQuery(CouponUser.class)
  1871. .eq(CouponUser::getUserId, orderDon.getUserId())
  1872. .eq(CouponUser::getChannel, CouponUser.Channel.ptfq)
  1873. .eq(CouponUser::getStatus, CouponUser.Status.unused));
  1874. if (CollUtil.isNotEmpty(couponUsers)) {
  1875. couponUserMapper.deleteBatchIds(couponUsers.stream().map(CouponUser::getId).collect(Collectors.toList()));
  1876. }
  1877. }
  1878. }
  1879. //claude code 退款
  1880. if (Objects.equals(orderDon.getGoodsId(), Constant.CLAUDE_CODE_GOODS_ID)) {
  1881. DistributeWaitingSendPoints distributeWaitingSendPoints = distributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(DistributeWaitingSendPoints.class).eq(DistributeWaitingSendPoints::getOrderId, orderDon.getId()).last("limit 1"));
  1882. if (distributeWaitingSendPoints != null) {
  1883. if (distributeWaitingSendPoints.getSendStatus() == DistributeWaitingSendPoints.Status.close) {
  1884. //是否是普通cc推广
  1885. Long orderId = distributeWaitingSendPoints.getOrderId();
  1886. ClaudeCodeUserResetRecord claudeCodeUserResetRecord = claudeCodeUserResetRecordMapper.selectOne(Wrappers.lambdaQuery(ClaudeCodeUserResetRecord.class).eq(ClaudeCodeUserResetRecord::getOrderId, orderId).last("limit 1"));
  1887. if (claudeCodeUserResetRecord != null) {
  1888. claudeCodeService.adjUserRestNum(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), -1, "新用户订单退款");
  1889. }
  1890. }
  1891. }
  1892. }
  1893. }
  1894. //处理下级渠道分销提成
  1895. static boolean shouldRestoreStock(GoodsDon goodsDon, boolean multiQuantityOrder) {
  1896. return !multiQuantityOrder || goodsDon == null || !Objects.equals(goodsDon.getType(), 1);
  1897. }
  1898. public void handleSubRewards(OrderDon orderDon) {
  1899. //是否是分销订单
  1900. //处理下级渠道分销提成
  1901. if (orderDon != null && Boolean.TRUE.equals(orderDon.getIsDistribute())) {
  1902. UserDistributeSub subRelate = userDistributeSubMapper.getSubRelate(orderDon.getUserId());
  1903. if (subRelate != null) {
  1904. List<UserDistributeSubWaiting> subWaitings = subWaitingMapper.selectList(Wrappers.lambdaQuery(UserDistributeSubWaiting.class)
  1905. .eq(UserDistributeSubWaiting::getSubUserId, subRelate.getSubUserId())
  1906. .eq(UserDistributeSubWaiting::getSendStatus, UserDistributeSubWaiting.Status.waiting));
  1907. if (CollUtil.isNotEmpty(subWaitings)) {
  1908. List<UserDistributeSubRewards> userDistributeSubRewards = userDistributeSubRewardsMapper.selectList(null);
  1909. Map<Integer, List<UserDistributeSubRewards>> rewardLevelMap = userDistributeSubRewards.stream().collect(Collectors.groupingBy(UserDistributeSubRewards::getLevel));
  1910. subWaitings.forEach(wait -> {
  1911. List<UserDistributeSubRewards> thisLevelList = rewardLevelMap.get(wait.getLevel());
  1912. if (thisLevelList == null) {
  1913. return;
  1914. }
  1915. UserDistributeSubRewards thisLevel = thisLevelList.get(0);
  1916. Integer months = thisLevel.getMonths();
  1917. BigDecimal subOrderMoney = Optional.ofNullable(orderDonMapper.selectSubChannelOrderMoney(wait.getSubUserId(), subRelate.getCreatedTime(), DateUtil.offsetMonth(subRelate.getCreatedTime(), months))).orElse(BigDecimal.ZERO);
  1918. if (subOrderMoney.compareTo(thisLevel.getTargetAmount()) < 0) {
  1919. subWaitingMapper.update(null, Wrappers.lambdaUpdate(UserDistributeSubWaiting.class)
  1920. .set(UserDistributeSubWaiting::getSendStatus, UserDistributeSubWaiting.Status.close)
  1921. .eq(UserDistributeSubWaiting::getSendStatus, UserDistributeSubWaiting.Status.waiting)
  1922. .eq(UserDistributeSubWaiting::getId, wait.getId()));
  1923. }
  1924. });
  1925. }
  1926. }
  1927. }
  1928. }
  1929. /**
  1930. * 退款 分销提成积分扣除
  1931. */
  1932. public void deductDsPoints(OrderDon orderDon) {
  1933. if (orderDon != null && Boolean.TRUE.equals(orderDon.getIsDistribute())) {
  1934. DistributeWaitingSendPoints distributeWaitingSendPoints = distributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(DistributeWaitingSendPoints.class).eq(DistributeWaitingSendPoints::getOrderId, orderDon.getId()).eq(DistributeWaitingSendPoints::getIsVip,Boolean.FALSE).last("limit 1"));
  1935. if (distributeWaitingSendPoints != null) {
  1936. BigDecimal money = orderDon.getMoney();
  1937. BigDecimal refundMoney = orderDon.getRefundMoney();
  1938. //已发送 发送中 部分 全额退款
  1939. DistributeWaitingSendPoints.Status sendStatus = distributeWaitingSendPoints.getSendStatus();
  1940. BigDecimal points = distributeWaitingSendPoints.getPoints();
  1941. if (sendStatus == DistributeWaitingSendPoints.Status.waiting) {
  1942. //实物设备退款就清0
  1943. if (refundMoney.compareTo(money) == 0 || Objects.equals(orderDon.getGoodsId(), 15L)) {
  1944. //待发送状态 全额退款
  1945. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  1946. distributeWaitingSendPoints.setRefundPoints(points);
  1947. distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
  1948. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1949. return;
  1950. }
  1951. Integer thisGoodsRate = distributeWaitingSendPoints.getRate();
  1952. if (thisGoodsRate == null || thisGoodsRate == 0) {
  1953. thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
  1954. }
  1955. if (thisGoodsRate > 0) {
  1956. BigDecimal refundRate = refundMoney.divide(money, 2, RoundingMode.DOWN);
  1957. //退掉比例的提成
  1958. BigDecimal needSubPoints = points.multiply(refundRate);
  1959. distributeWaitingSendPoints.setRefundPoints(needSubPoints);
  1960. //剩余积分
  1961. BigDecimal remainPoints = points.subtract(needSubPoints);
  1962. distributeWaitingSendPoints.setPoints(remainPoints);
  1963. //原先获取积分也扣除
  1964. BigDecimal oriPoints = distributeWaitingSendPoints.getOriPoints();
  1965. if (oriPoints != null && oriPoints.compareTo(BigDecimal.ZERO) > 0) {
  1966. BigDecimal oriNeedSubPoints = oriPoints.multiply(refundRate);
  1967. distributeWaitingSendPoints.setOriPoints(oriPoints.subtract(oriNeedSubPoints));
  1968. }
  1969. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1970. }
  1971. } else if (sendStatus == DistributeWaitingSendPoints.Status.success) {
  1972. //已发送的提成 部分退款 全额退款 需要扣除用户积分
  1973. //扣除固定推广者积分
  1974. //实物设备退款就清0
  1975. if (refundMoney.compareTo(money) == 0 || Objects.equals(orderDon.getGoodsId(), 15L)) {
  1976. userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), points);
  1977. distributeWaitingSendPoints.setRefundPoints(points);
  1978. distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
  1979. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  1980. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1981. return;
  1982. }
  1983. Integer thisGoodsRate = distributeWaitingSendPoints.getRate();
  1984. if (thisGoodsRate == null || thisGoodsRate == 0) {
  1985. thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
  1986. }
  1987. if (thisGoodsRate > 0) {
  1988. BigDecimal refundRate = refundMoney.divide(money, 2, RoundingMode.DOWN);
  1989. //退掉比例的提成
  1990. BigDecimal needSubPoints = points.multiply(refundRate);
  1991. userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), needSubPoints);
  1992. //部分退款
  1993. distributeWaitingSendPoints.setRefundPoints(needSubPoints);
  1994. distributeWaitingSendPoints.setPoints(points.subtract(needSubPoints));
  1995. //原先获取积分也扣除
  1996. BigDecimal oriPoints = distributeWaitingSendPoints.getOriPoints();
  1997. if (oriPoints != null && oriPoints.compareTo(BigDecimal.ZERO) > 0) {
  1998. BigDecimal oriNeedSubPoints = oriPoints.multiply(refundRate);
  1999. distributeWaitingSendPoints.setOriPoints(oriPoints.subtract(oriNeedSubPoints));
  2000. }
  2001. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  2002. }
  2003. }
  2004. }
  2005. }
  2006. }
  2007. @Override
  2008. public void refundPriceDiffer(OrderRefundReq orderRefundReq) throws Exception {
  2009. Long orderId = orderRefundReq.getOrderId();
  2010. OrderDon orderDon = orderDonMapper.selectById(orderId);
  2011. if (orderDon == null) {
  2012. throw BusinessRuntimeException.getInstance("订单不存在");
  2013. }
  2014. if (orderDonTicketRecordService.exists(orderId)) {
  2015. throw BusinessRuntimeException.getInstance("Multi-quantity orders only support whole-order refunds");
  2016. }
  2017. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  2018. throw BusinessRuntimeException.getInstance("该订单是0元订单,无法补差价");
  2019. }
  2020. if (Constant.noOrderAllStatus.contains(orderDon.getStatus().name())) {
  2021. throw BusinessRuntimeException.getInstance("订单不是已支付状态");
  2022. }
  2023. //默认补差价余额
  2024. String refundType = Optional.ofNullable(orderRefundReq.getRefundType()).orElse("balance");
  2025. BigDecimal refundMoney = orderRefundReq.getRefundMoney();
  2026. BigDecimal orderRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  2027. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  2028. if (refundMoney.add(orderRefundMoney).add(orderDonRefundBalance).compareTo(orderDon.getRealMoney()) >= 0) {
  2029. throw BusinessRuntimeException.getInstance("补差价已达到该订单付款金额");
  2030. }
  2031. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  2032. GoodsDonSku sku = null;
  2033. if (orderDon.getSkuId() != null) {
  2034. sku = skuMapper.selectById(orderDon.getSkuId());
  2035. }
  2036. orderDon.setRefundDesc("补差价");
  2037. String outNo = StrUtil.EMPTY;
  2038. if ("money".equals(refundType)) {
  2039. if (refundMoney == null || refundMoney.compareTo(BigDecimal.ZERO) <= 0) {
  2040. throw BusinessRuntimeException.getInstance("请输入正确的差价金额");
  2041. }
  2042. if (refundMoney.compareTo(orderDon.getMoney()) >= 0) {
  2043. throw BusinessRuntimeException.getInstance("补差价金额应不大于订单金额");
  2044. }
  2045. //退款
  2046. orderRefundReq.setIsDiffer(true);
  2047. outNo = orderRefundService.centerRefund(orderRefundReq, orderDon);
  2048. orderDon.setRefundMoney(orderRefundMoney.add(refundMoney));
  2049. orderDonMapper.updateById(orderDon);
  2050. //补差价金额 扣除对应分销提成金额
  2051. orderDon.setRefundMoney(refundMoney);
  2052. deductDsPoints(orderDon);
  2053. //店铺分销提成金额扣除
  2054. yhShopDistributeService.deductDsMoney(orderDon);
  2055. } else {
  2056. BigDecimal refundBalance = refundMoney;
  2057. if (refundBalance == null || refundBalance.compareTo(BigDecimal.ZERO) <= 0 || refundBalance.compareTo(orderDon.getMoney()) > 0) {
  2058. throw BusinessRuntimeException.getInstance("请输入正确的差价金额");
  2059. }
  2060. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.price_differ, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.price_differ.getDesc(), true);
  2061. orderDon.setRefundBalance(orderDonRefundBalance.add(refundBalance));
  2062. orderDonMapper.updateById(orderDon);
  2063. }
  2064. orderRefundService.refundRecord(orderDon, refundMoney, orderRefundReq.getRefundBalance(), orderRefundReq.getOperator(), goodsDon, sku, outNo, refundType, null);
  2065. }
  2066. @Override
  2067. @Transactional(rollbackFor = Throwable.class)
  2068. public void clearBalanceToRefundMoney(OrderBalanceRefundReq refundReq) throws Exception {
  2069. Long refundOrderId = refundReq.getRefundOrderId();
  2070. BigDecimal refundMoney = refundReq.getRefundMoney();
  2071. RefundOrderDon refundOrderDon = refundOrderDonMapper.selectById(refundOrderId);
  2072. if (!"balance".equals(refundOrderDon.getRefundMethod())) {
  2073. throw BusinessRuntimeException.getInstance("该记录不是余额退款类型");
  2074. }
  2075. Long orderId = refundOrderDon.getOrderId();
  2076. OrderDon orderDon = orderDonMapper.selectById(orderId);
  2077. if (orderDon == null) {
  2078. throw BusinessRuntimeException.getInstance("Order does not exist");
  2079. }
  2080. if (orderDonTicketRecordService.exists(orderId)) {
  2081. throw BusinessRuntimeException.getInstance("Multi-quantity orders only support whole-order refunds");
  2082. }
  2083. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  2084. throw BusinessRuntimeException.getInstance("该记录对应的订单无实际支付金额");
  2085. }
  2086. if (refundOrderDon.getIsClearBalance()) {
  2087. throw BusinessRuntimeException.getInstance("该笔退款余额记录已退款");
  2088. }
  2089. BigDecimal refundFee = refundOrderDon.getRefundFee();
  2090. //默认退全部余额
  2091. if (refundMoney != null) {
  2092. refundFee = refundMoney;
  2093. }
  2094. BigDecimal money = orderDon.getMoney();
  2095. //若退款余额 大于退款金额 将退款余额至为 退款金额
  2096. if (refundFee.compareTo(money) > 0) {
  2097. refundFee = money;
  2098. }
  2099. User user = userMapper.selectById(orderDon.getUserId());
  2100. if (user.getBalance().compareTo(refundFee) < 0) {
  2101. throw BusinessRuntimeException.getInstance("用户余额不足,无法扣除对应退款余额");
  2102. }
  2103. int update = userMapper.update(null, Wrappers.lambdaUpdate(User.class)
  2104. .set(User::getBalance, user.getBalance().subtract(refundFee))
  2105. .eq(User::getId, user.getId())
  2106. .eq(User::getBalance, user.getBalance()));
  2107. if (update == 0) {
  2108. throw BusinessRuntimeException.getInstance("扣除用户退款余额失败,请重试...");
  2109. }
  2110. OrderRefundReq orderRefundReq = new OrderRefundReq();
  2111. orderRefundReq.setOrderId(orderId);
  2112. orderRefundReq.setRefundMoney(refundFee);
  2113. orderRefundReq.setRefundType("money");
  2114. String outNo = orderRefundService.centerRefund(orderRefundReq, orderDon);
  2115. orderDon.setRefundBalance(orderDon.getRefundBalance().subtract(refundFee));
  2116. BigDecimal orderRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  2117. orderDon.setRefundMoney(orderRefundMoney.add(refundFee));
  2118. orderDonMapper.updateById(orderDon);
  2119. refundOrderDon.setOutRefundNo(outNo);
  2120. refundOrderDon.setIsClearBalance(true);
  2121. refundOrderDonMapper.updateById(refundOrderDon);
  2122. }
  2123. /**
  2124. * 寻找该车队空余车位
  2125. */
  2126. public GroupsRelation getRelationThisTrips(Long userId, Long groupsId, Integer retryNum) {
  2127. //寻找快满编车队进行占座
  2128. GroupsRelation relation = relationMapper.selectRandomOneRelationByGroupsId(groupsId);
  2129. if (relation == null) {
  2130. throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  2131. }
  2132. Long relationId = relation.getId();
  2133. if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
  2134. if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  2135. retryNum++;
  2136. return getRelationThisTrips(userId, groupsId, retryNum);
  2137. }
  2138. int count = groupsMapper.decrAvailableNum(relation.getGroupsId());
  2139. if (count == 0) {
  2140. log.error("车位异常 groupId:{}", groupsId);
  2141. groupsMapper.updateAvailableNum(groupsId);
  2142. throw new BusinessRuntimeException("车位异常");
  2143. }
  2144. return relation;
  2145. }
  2146. private GroupsRelation getChatGPTOutsideRelation(Long userId, Long groupsId, Integer relationNum, Integer retryNum) {
  2147. //寻找快满编车队额外座位
  2148. GroupsRelation relation = relationMapper.selectOutsideRelationByGroupsId(groupsId, relationNum);
  2149. if (relation == null) {
  2150. relation = new GroupsRelation();
  2151. relation.setStatus(GroupsRelation.Status.outside);
  2152. relation.setGroupsId(groupsId);
  2153. GroupsRelation maxNumRelation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getGroupsId, groupsId).orderByDesc(GroupsRelation::getNum).last("limit 1"));
  2154. relation.setNum(maxNumRelation.getNum() + 1);
  2155. relationMapper.insert(relation);
  2156. return relation;
  2157. }
  2158. Long relationId = relation.getId();
  2159. if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
  2160. if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  2161. retryNum++;
  2162. return getChatGPTOutsideRelation(userId, groupsId, relationNum, retryNum);
  2163. }
  2164. return relation;
  2165. }
  2166. private void checkMirrorRenewSku(OrderDon orderDon) {
  2167. Long skuId = orderDon.getSkuId();
  2168. Long orderId = orderDon.getId();
  2169. OrderDonRenewRecord orderDonRenewRecord = orderDonRenewRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonRenewRecord.class)
  2170. .eq(OrderDonRenewRecord::getOrderId, orderId)
  2171. .last("limit 1"));
  2172. if (orderDonRenewRecord != null) {
  2173. //gpt
  2174. if (orderDon.getGoodsId() == 18) {
  2175. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class)
  2176. .eq(ChatgptUser::getRelationId, orderDon.getRelationId())
  2177. .last("limit 1"));
  2178. Long presentRenewSkuId = chatgptUser.getRenewSkuId();
  2179. if (presentRenewSkuId != null) {
  2180. //存在不同升级套餐
  2181. GoodsDonSku presentRenewSku = skuMapper.selectById(presentRenewSkuId);
  2182. if (!ObjectUtil.equal(presentRenewSkuId, skuId)) {
  2183. throw BusinessRuntimeException.getInstance("请先退掉用户目前续费升级的{0}规格", presentRenewSku.getSpecVal());
  2184. }
  2185. }
  2186. }
  2187. //claude pro
  2188. if (orderDon.getGoodsId() == 75) {
  2189. ClaudeUser claudeUser = claudeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeUser.class)
  2190. .eq(ClaudeUser::getRelationId, orderDon.getRelationId())
  2191. .last("limit 1"));
  2192. Long presentRenewSkuId = claudeUser.getRenewSkuId();
  2193. if (presentRenewSkuId != null) {
  2194. //存在不同升级套餐
  2195. GoodsDonSku presentRenewSku = skuMapper.selectById(presentRenewSkuId);
  2196. if (!ObjectUtil.equal(presentRenewSkuId, skuId)) {
  2197. throw BusinessRuntimeException.getInstance("请先退掉用户目前续费升级的{0}规格", presentRenewSku.getSpecVal());
  2198. }
  2199. }
  2200. }
  2201. }
  2202. }
  2203. private void clearExtraRelation(OrderDon orderDon) {
  2204. List<UserPayEquipmentReceiveBenefitsRecord> userPayEquipmentReceiveBenefitsRecords = receiveBenefitsRecordMapper.selectList(Wrappers.lambdaQuery(UserPayEquipmentReceiveBenefitsRecord.class)
  2205. .eq(UserPayEquipmentReceiveBenefitsRecord::getRealOrderId, orderDon.getId()));
  2206. userPayEquipmentReceiveBenefitsRecords.forEach(record -> {
  2207. Long skuId = record.getSkuId();
  2208. List<GroupsRelation> relations = relationMapper.selectExtraRelation(orderDon.getUserId(), skuId, record.getRelationId());
  2209. relations.forEach(relation -> {
  2210. //不是优惠加购
  2211. Integer count = orderDiscountPlusPurchaseSkuRelationMapper.selectCount(Wrappers.lambdaQuery(OrderDiscountPlusPurchaseSkuRelation.class)
  2212. .eq(OrderDiscountPlusPurchaseSkuRelation::getUserId, relation.getUserId())
  2213. .apply("JSON_CONTAINS(relation_ids,'" + relation.getId() + "')"));
  2214. if (count == 0) {
  2215. log.info("非优惠加购订单,直接清除userId:{}车票:{}", relation.getUserId(), relation.getId());
  2216. relationClearService.clearTicket(relation, UserTicketClearedRecord.Source.manual);
  2217. }
  2218. });
  2219. });
  2220. }
  2221. /**
  2222. * 扣除用户镜像店铺提成
  2223. */
  2224. private void deductUserMirrorShopMoney(OrderDon orderDon) {
  2225. UserMirrorShopDistributeWaitingSendPoints distributeWaitingSendPoints = userMirrorShopDistributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShopDistributeWaitingSendPoints.class)
  2226. .eq(UserMirrorShopDistributeWaitingSendPoints::getOrderId, orderDon.getId())
  2227. .last("limit 1"));
  2228. if (distributeWaitingSendPoints != null) {
  2229. BigDecimal money = orderDon.getMoney();
  2230. BigDecimal refundMoney = orderDon.getRefundMoney();
  2231. //已发送 发送中 部分 全额退款
  2232. UserMirrorShopDistributeWaitingSendPoints.Status sendStatus = distributeWaitingSendPoints.getSendStatus();
  2233. BigDecimal take_money = distributeWaitingSendPoints.getMoney();
  2234. if (sendStatus == UserMirrorShopDistributeWaitingSendPoints.Status.waiting) {
  2235. if (refundMoney.compareTo(money) == 0) {
  2236. //待发送状态 全额退款
  2237. distributeWaitingSendPoints.setSendStatus(UserMirrorShopDistributeWaitingSendPoints.Status.close);
  2238. distributeWaitingSendPoints.setRefundMoney(take_money);
  2239. distributeWaitingSendPoints.setMoney(BigDecimal.ZERO);
  2240. userMirrorShopDistributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  2241. return;
  2242. }
  2243. Integer rate = distributeWaitingSendPoints.getRate();
  2244. if (rate > 0) {
  2245. BigDecimal needDeductMoney = refundMoney.multiply(BigDecimal.valueOf(rate).divide(BigDecimal.valueOf(100)));
  2246. distributeWaitingSendPoints.setRefundMoney(needDeductMoney);
  2247. //剩余积分
  2248. distributeWaitingSendPoints.setMoney(take_money.subtract(needDeductMoney));
  2249. userMirrorShopDistributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  2250. }
  2251. } else if (sendStatus == UserMirrorShopDistributeWaitingSendPoints.Status.success) {
  2252. //已发送的提成 部分退款 全额退款 需要扣除用户积分
  2253. //扣除固定推广者积分
  2254. if (refundMoney.compareTo(money) == 0) {
  2255. //扣除店铺主 已有的提成金额
  2256. userBenefitsService.deductUserMirrorShopTakeMoney(orderDon.getId(), distributeWaitingSendPoints.getShopUserId(), take_money);
  2257. distributeWaitingSendPoints.setRefundMoney(take_money);
  2258. distributeWaitingSendPoints.setMoney(BigDecimal.ZERO);
  2259. distributeWaitingSendPoints.setSendStatus(UserMirrorShopDistributeWaitingSendPoints.Status.close);
  2260. userMirrorShopDistributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  2261. return;
  2262. }
  2263. Integer rate = distributeWaitingSendPoints.getRate();
  2264. if (rate > 0) {
  2265. BigDecimal needDeductMoney = refundMoney.multiply(BigDecimal.valueOf(rate).divide(BigDecimal.valueOf(100)));
  2266. //扣除店铺主 已有的提成金额
  2267. userBenefitsService.deductUserMirrorShopTakeMoney(orderDon.getId(), distributeWaitingSendPoints.getShopUserId(), needDeductMoney);
  2268. //部分退款
  2269. distributeWaitingSendPoints.setRefundMoney(needDeductMoney);
  2270. distributeWaitingSendPoints.setMoney(take_money.subtract(needDeductMoney));
  2271. userMirrorShopDistributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  2272. }
  2273. }
  2274. }
  2275. }
  2276. /**
  2277. * 清除多余车票
  2278. */
  2279. private void clearOtherChangeTicket(Long userId, Long relationId, GroupsRelation newRelation, Long skuId) {
  2280. UserTicketClearedRecord userTicketClearedRecord = userTicketClearedRecordMapper.selectOne(Wrappers.lambdaQuery(UserTicketClearedRecord.class)
  2281. .eq(UserTicketClearedRecord::getUserId, userId)
  2282. .eq(UserTicketClearedRecord::getRelationId, relationId)
  2283. .eq(UserTicketClearedRecord::getSource, UserTicketClearedRecord.Source.change_ticket)
  2284. .orderByDesc(UserTicketClearedRecord::getId)
  2285. .last("limit 1"));
  2286. if (userTicketClearedRecord != null) {
  2287. Long newRelationId = userTicketClearedRecord.getNewRelationId();
  2288. List<GroupsRelation> others = relationMapper.selectList(Wrappers.lambdaQuery(GroupsRelation.class)
  2289. .ne(GroupsRelation::getId, newRelationId)
  2290. .eq(GroupsRelation::getUserId, userId)
  2291. .eq(GroupsRelation::getStartTime, newRelation.getStartTime())
  2292. .eq(GroupsRelation::getExpiryTime, newRelation.getExpiryTime()));
  2293. others.forEach(r -> {
  2294. Long groupsId = r.getGroupsId();
  2295. GroupsTrips groupsTrips = groupsMapper.selectById(groupsId);
  2296. //排除 非同规格车票
  2297. if (!skuId.equals(groupsTrips.getSkuId())) {
  2298. return;
  2299. }
  2300. Long rid = r.getId();
  2301. Integer selectCount = orderDonMapper.selectCount(Wrappers.lambdaQuery(OrderDon.class)
  2302. .eq(OrderDon::getUserId, userId)
  2303. .eq(OrderDon::getRelationId, rid)
  2304. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus));
  2305. if (selectCount == 0) {
  2306. //不是优惠加购
  2307. Integer count = orderDiscountPlusPurchaseSkuRelationMapper.selectCount(Wrappers.lambdaQuery(OrderDiscountPlusPurchaseSkuRelation.class)
  2308. .eq(OrderDiscountPlusPurchaseSkuRelation::getUserId, userId)
  2309. .apply("JSON_CONTAINS(relation_ids,'" + rid + "')"));
  2310. if (count == 0) {
  2311. log.info("清除用户:{}多余车票", userId);
  2312. relationClearService.clearTicket(r, UserTicketClearedRecord.Source.manual);
  2313. }
  2314. }
  2315. });
  2316. }
  2317. }
  2318. /**
  2319. * 车队退款 自动上架
  2320. */
  2321. private void setUpIfEmpty(Long goodsId, Long relationId) {
  2322. if (goodsId == Constant.HBO_GO_GOODS_ID) {
  2323. GroupsRelation relation = relationMapper.selectById(relationId);
  2324. if (relation == null) {
  2325. return;
  2326. }
  2327. GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
  2328. if (groupsTrips == null) {
  2329. return;
  2330. }
  2331. if (groupsTrips.getStatus() == GroupsTrips.Status.down) {
  2332. log.info("HBO GO车队:{}存在退款,自动上架", groupsTrips.getId());
  2333. groupsMapper.update(null, Wrappers.lambdaUpdate(GroupsTrips.class)
  2334. .set(GroupsTrips::getStatus, GroupsTrips.Status.validity)
  2335. .eq(GroupsTrips::getId, groupsTrips.getId()));
  2336. }
  2337. }
  2338. }
  2339. /**
  2340. * 退款扣除代充次数
  2341. */
  2342. private void subRechargeNumOrder(Long userId, Long relationId, Integer subNum, String operator) {
  2343. List<Long> userIdList = userBindRelationService.getRelationUserIdList(userId, null);
  2344. GroupsRelation relation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getId, relationId).in(GroupsRelation::getUserId, userIdList).gt(GroupsRelation::getExpiryTime, DateTime.now()));
  2345. if (relation != null && relation.getRechargeStatus() != null) {
  2346. if (relation.getRechargeRemainNum() == 0) {
  2347. return;
  2348. }
  2349. int update = 0;
  2350. while (update == 0) {
  2351. Integer rechargeRemainNum = relation.getRechargeRemainNum();
  2352. if (subNum > rechargeRemainNum) {
  2353. subNum = rechargeRemainNum;
  2354. }
  2355. update = groupsRelationMapper.update(null, Wrappers.lambdaUpdate(GroupsRelation.class)
  2356. .set(GroupsRelation::getRechargeRemainNum, rechargeRemainNum - subNum)
  2357. .eq(GroupsRelation::getId, relationId)
  2358. .eq(GroupsRelation::getRechargeRemainNum, rechargeRemainNum));
  2359. if (update == 1) {
  2360. //记录gpt代充记录
  2361. gptUserRechargeRecordService.recordGptUserRechargeNum(null, relation.getUserId(), relation.getId(), relation.getAccount(), -subNum, operator, "订单退款");
  2362. break;
  2363. }
  2364. relation = relationMapper.selectById(relationId);
  2365. }
  2366. }
  2367. }
  2368. }