CmsOrderDonServiceImpl.java 92 KB

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