CmsOrderDonServiceImpl.java 105 KB

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