CmsOrderDonServiceImpl.java 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700
  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. //是否全额退款
  486. // BigDecimal orderDonRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  487. // BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  488. // if (orderDonRefundMoney.add(orderDonRefundBalance).compareTo(orderDon.getMoney().add(Optional.ofNullable(orderDon.getBalance()).orElse(BigDecimal.ZERO))) == 0) {
  489. // //是否使用银河币支付
  490. // OrderDonGalaxyCoinRecord orderDonGalaxyCoinRecord = orderDonGalaxyCoinRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonGalaxyCoinRecord.class)
  491. // .eq(OrderDonGalaxyCoinRecord::getOrderId, orderDon.getId())
  492. // .eq(OrderDonGalaxyCoinRecord::getSource, OrderDonGalaxyCoinRecord.Source.upgrade.ordinal())
  493. // .last("limit 1"));
  494. // if (orderDonGalaxyCoinRecord != null) {
  495. // //有效时,返还银河币 并记录
  496. // userGalaxyCoinService.recordOrderRefundGalaxyCoinIfValid(orderDon.getId(), orderDonGalaxyCoinRecord.getUserId(), orderDonGalaxyCoinRecord.getGalaxyCoin().abs(), OrderDonGalaxyCoinRecord.Source.upgrade);
  497. // }
  498. // }
  499. //扣除 该笔订单产生的返现银河币
  500. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) > 0) {
  501. userGalaxyCoinService.subOrderGenerateGalaxyCoin(orderDon.getId(), OrderDonGalaxyCoinRecord.Source.upgrade);
  502. }
  503. if (UpgradeOrderDon.Type.BALANCE.getType().equals(refundType)) {
  504. if (isOnly == null && orderDon.getMoney().compareTo(BigDecimal.ZERO) > 0) {
  505. userBenefitsService.addUserBalance(orderDon.getUserId(), orderDon.getRefundBalance(), UserBalanceSourceRecord.Source.refund, 0L, orderDon.getId(), upgradePackage.getName() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  506. }
  507. }
  508. });
  509. }
  510. /**
  511. * 校验订单是否符合退款操作
  512. */
  513. private void checkUpgradeOrderRefund(UpgradeOrderDon orderDon, OrderRefundReq refundReq) {
  514. if (orderDon == null) {
  515. throw BusinessRuntimeException.getInstance("订单不存在");
  516. }
  517. BigDecimal orderDonRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  518. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  519. String refundType = refundReq.getRefundType();
  520. // if (orderDon.getType() == UpgradeOrderDon.Type.BALANCE && !UpgradeOrderDon.Type.BALANCE.getType().equals(refundType)) {
  521. // throw BusinessRuntimeException.getInstance("余额支付的订单不支持金额退款");
  522. // }
  523. if (UpgradeOrderDon.Status.refund == orderDon.getStatus()) {
  524. throw BusinessRuntimeException.getInstance("该订单已退款");
  525. }
  526. if (UpgradeOrderDon.Status.noPayment == orderDon.getStatus() || UpgradeOrderDon.Status.close == orderDon.getStatus()) {
  527. throw BusinessRuntimeException.getInstance("订单{0}状态不支持退款", orderDon.getStatus());
  528. }
  529. BigDecimal refundMoney = refundReq.getRefundMoney();
  530. BigDecimal money = orderDon.getMoney();
  531. //余额退款
  532. if (UpgradeOrderDon.Type.BALANCE.getType().equals(refundType)) {
  533. BigDecimal balance = orderDon.getBalance();
  534. refundMoney = orderDonRefundBalance.add(refundMoney);
  535. if (UpgradeOrderDon.Type.BALANCE == orderDon.getType() && refundMoney.compareTo(balance) > 0) {
  536. throw BusinessRuntimeException.getInstance("退款余额大于订单支付余额");
  537. }
  538. if (UpgradeOrderDon.Type.BALANCE != orderDon.getType() && refundMoney.compareTo(money) > 0) {
  539. throw BusinessRuntimeException.getInstance("退款余额大于订单支付金额");
  540. }
  541. orderDon.setRefundBalance(refundMoney);
  542. orderDon.setRefundMoney(BigDecimal.ZERO);
  543. } else {
  544. //退金额
  545. refundMoney = orderDonRefundMoney.add(refundMoney);
  546. if (refundMoney.compareTo(money) > 0) {
  547. throw BusinessRuntimeException.getInstance("退款金额大于订单支付金额");
  548. }
  549. orderDon.setRefundMoney(refundMoney);
  550. }
  551. if (!redisService.setNx(String.format("%s", refundReq.getOrderId()), refundReq.getOrderId(), 10l)) {
  552. throw BusinessRuntimeException.getInstance("请勿重复点击,正在退款中..");
  553. }
  554. }
  555. public String wxRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
  556. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) <=0){
  557. return StrUtil.EMPTY;
  558. }
  559. long time = System.currentTimeMillis();
  560. //退款订单号
  561. String outRefundNo = Codec.DoDigest.custom()
  562. .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
  563. .setStringData(time + String.valueOf(orderDon.getId()))
  564. .toHexString();
  565. weChatService.refundWxOrder(weChatConfig.getAppid(),
  566. Optional.ofNullable(orderDon.getShopId()).orElse(ShopConfig.WX_DEFAULT_APP_ID),
  567. orderDon.getTransactionId(),
  568. outRefundNo,
  569. orderDon.getMoney(),
  570. refundReq.getRefundMoney(),
  571. weChatConfig.getNotifyDomain() + "manage/order/wx/refund/notify");
  572. //记录退款信息
  573. return outRefundNo;
  574. }
  575. @Override
  576. public void wxRefundNotify(Map<String, String> map) throws Exception {
  577. // 对退款数据 解密
  578. String md5Key = Codec.DoDigest.custom().setAlgorithm(Codec.DoDigest.Algorithm.MD5).setStringData(shopConfigMapper.getByAppId(map.get("mch_id")).getSecret()).toHexString();
  579. String reqInfoXml = Codec.DoCipher.custom().setAlgorithm(Codec.DoCipher.Trans.AES_ECB_PKCS7Padding).setBase64Data(map.get("req_info")).setStringKey(md5Key).ofDecrypt().toText();
  580. log.info("=== 退款数据解密: \n {}", reqInfoXml);
  581. Map<String, String> reqInfoMap = Xmls.toMap(reqInfoXml);
  582. // 退款失败
  583. if (StrUtil.equals("CHANGE", reqInfoMap.get("refund_status"))) {
  584. throw BusinessRuntimeException.getInstance("退款异常.");
  585. } else if (StrUtil.equals("REFUNDCLOSE", reqInfoMap.get("refund_status"))) {
  586. throw BusinessRuntimeException.getInstance("退款关闭.");
  587. }
  588. /* 此处处理业务逻辑 */
  589. String outRefundNo = reqInfoMap.get("out_refund_no");
  590. String transactionId = reqInfoMap.get("transaction_id");
  591. String refundFee = reqInfoMap.get("refund_fee");
  592. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getTransactionId, transactionId).last("limit 1"));
  593. if (orderDon == null) {
  594. log.error("退款回调,transactionId:{}订单不存在", transactionId);
  595. return;
  596. }
  597. log.info("微信退款: 退款单号[{}] 退款成功.", outRefundNo);
  598. }
  599. @Override
  600. @Transactional(rollbackFor = Throwable.class)
  601. public void changeRelation(ChangeRelationReq req) throws Exception {
  602. Long relationId = req.getRelationId();
  603. Long groupId = req.getGroupsId();
  604. UserTicketClearedRecord.Source source = req.getSource();
  605. if (source == null) source = UserTicketClearedRecord.Source.change_ticket;
  606. GroupsRelation relation = relationMapper.selectById(relationId);
  607. Long yhsId = relation.getYhsId();
  608. Assert.notNull(relation, "车票已不存在");
  609. if (relation.getRechargeStatus() != null) {
  610. throw BusinessRuntimeException.getInstance("代充账号车票无法更换车票");
  611. }
  612. String key = RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getName() + relationId;
  613. if (!redisService.setNx(key, relationId, RedisService.key.NETFLIX_CHANGE_TICKET_KEY.getTimeout())) {
  614. throw BusinessRuntimeException.getInstance("正在更换车票中..");
  615. }
  616. Long userId = relation.getUserId();
  617. log.info("用户userId:{}更换车票relationId:{}", userId, relationId);
  618. OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  619. .eq(OrderDon::getUserId, userId)
  620. .eq(OrderDon::getRelationId, relationId)
  621. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  622. .orderByDesc(OrderDon::getId)
  623. .last("limit 1"));
  624. OrderDiscountPlusPurchaseSkuRelation plusPurchaseSkuRelation = null;
  625. List<Long> plus_relationList = null;
  626. if (orderDon == null) {
  627. List<OrderDiscountPlusPurchaseSkuRelation> plusPurchaseSkuRelations = orderDiscountPlusPurchaseSkuRelationMapper.selectPlusRelationByIdAndUserId(relation.getId(), relation.getUserId());
  628. for (OrderDiscountPlusPurchaseSkuRelation data : plusPurchaseSkuRelations) {
  629. String relationIds = data.getRelationIds();
  630. if (StrUtil.isEmpty(relationIds)) {
  631. return;
  632. }
  633. List<Long> relationList = Jsons.parseList(relationIds, Long.class);
  634. if (relationList.contains(relationId)) {
  635. plusPurchaseSkuRelation = data;
  636. break;
  637. }
  638. }
  639. if (plusPurchaseSkuRelation != null) {
  640. String relationIds = plusPurchaseSkuRelation.getRelationIds();
  641. if (StrUtil.isNotEmpty(relationIds)) {
  642. plus_relationList = Jsons.parseList(relationIds, Long.class);
  643. if (plus_relationList.contains(relationId)) {
  644. orderDon = new OrderDon();
  645. GroupsRelationView groupsRelationView = beanSearcher.searchFirst(GroupsRelationView.class, MapUtils.builder().field(GroupsRelationView::getId, relationId).build());
  646. Assert.notNull(groupsRelationView, "车票已不存在");
  647. orderDon.setUserId(groupsRelationView.getUserId());
  648. orderDon.setSkuId(groupsRelationView.getSkuId());
  649. orderDon.setGoodsId(groupsRelationView.getGoodsId());
  650. orderDon.setStatus(OrderDon.Status.complete);
  651. orderDon.setOrderType(1);
  652. }
  653. }
  654. }
  655. }
  656. Assert.notNull(orderDon, "订单不存在");
  657. if (orderDon.getStatus() == OrderDon.Status.refund) {
  658. throw BusinessRuntimeException.getInstance("订单已退款");
  659. }
  660. //获取新车队
  661. LambdaQueryWrapper<GroupsTrips> queryWrapper = Wrappers.lambdaQuery(GroupsTrips.class)
  662. .eq(GroupsTrips::getSkuId, orderDon.getSkuId())
  663. .eq(GroupsTrips::getId, groupId)
  664. .ne(GroupsTrips::getId, relation.getGroupsId())
  665. .ne(GroupsTrips::getStatus, GroupsTrips.Status.down)
  666. .last("limit 1");
  667. GroupsTrips groups = groupsMapper.selectOne(queryWrapper);
  668. if (groups == null) throw BusinessRuntimeException.getInstance("车队不存在或已下架");
  669. if (!Constant.AI_goodsIds.contains(orderDon.getGoodsId()) && groups.getAvailableNum() <= 0) {
  670. throw BusinessRuntimeException.getInstance("该新车位人员已满");
  671. }
  672. Integer relationNum = groups.getNum();
  673. //获取新车队车位
  674. GroupsRelation newRelation;
  675. Boolean isOutside = req.getIsOutside();
  676. if (Constant.AI_goodsIds.contains(orderDon.getGoodsId()) && ((isOutside != null && isOutside) || groups.getAvailableNum() == 0) && groups.getNum() > 1) {
  677. //Ai车队 额外增加车位 并不让上车
  678. newRelation = getChatGPTOutsideRelation(orderDon.getUserId(), groupId, relationNum, 1);
  679. } else {
  680. newRelation = getRelationThisTrips(orderDon.getUserId(), groupId, 1);
  681. }
  682. newRelation.setUserId(userId);
  683. newRelation.setStartTime(relation.getStartTime());
  684. newRelation.setExpiryTime(relation.getExpiryTime());
  685. newRelation.setYhsId(yhsId);
  686. newRelation.setCmt(relation.getCmt());
  687. newRelation.setCustomerService(relation.getCustomerService());
  688. if (newRelation.getStatus() != GroupsRelation.Status.outside) {
  689. newRelation.setStatus(GroupsRelation.Status.validity);
  690. }
  691. //清除原先车票
  692. relation.setNewRelationId(newRelation.getId());
  693. relationClearService.clearTicket(relation, source);
  694. //兜底处理 多余车票
  695. clearOtherChangeTicket(userId, relationId, newRelation, orderDon.getSkuId());
  696. //奈飞车票
  697. if (orderDon.getGoodsId() == 1) {
  698. User user = userMapper.selectById(newRelation.getUserId());
  699. GroupsTrips groupsTrips = groupsMapper.selectById(newRelation.getGroupsId());
  700. Account account = accountMapper.selectById(groupsTrips.getAccountId());
  701. AtomicInteger start = new AtomicInteger(1);
  702. groupsRelationNetflixService.timingSetNetflix(newRelation.getNum(), user.getNickname(), account.getAccount(), account.getPassword(), newRelation.getExpiryTime(), start);
  703. }
  704. if (plusPurchaseSkuRelation != null && plus_relationList != null) {
  705. plus_relationList.remove(relationId);
  706. plus_relationList.add(newRelation.getId());
  707. plusPurchaseSkuRelation.setRelationIds(plus_relationList.toString());
  708. orderDiscountPlusPurchaseSkuRelationMapper.updateById(plusPurchaseSkuRelation);
  709. }
  710. if (source != null && source == UserTicketClearedRecord.Source.abnormal) {
  711. //将用户异常订单关闭
  712. workOrderMapper.update(null, Wrappers.lambdaUpdate(WorkOrder.class)
  713. .set(WorkOrder::getStatus, WorkOrder.Status.close)
  714. .eq(WorkOrder::getStatus, WorkOrder.Status.waiting)
  715. .eq(WorkOrder::getUserId, userId)
  716. .eq(WorkOrder::getRelationId, relationId));
  717. }
  718. if (orderDon.getMoney() != null && orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  719. //是否是实物权益车票
  720. UserPayEquipmentReceiveBenefitsRecord receiveBenefitsRecord = receiveBenefitsRecordMapper.selectOne(Wrappers.lambdaQuery(UserPayEquipmentReceiveBenefitsRecord.class)
  721. .eq(UserPayEquipmentReceiveBenefitsRecord::getTicketOrderId, orderDon.getId())
  722. .eq(UserPayEquipmentReceiveBenefitsRecord::getRelationId, relationId).last("limit 1"));
  723. if (receiveBenefitsRecord != null) {
  724. receiveBenefitsRecord.setRelationId(newRelation.getId());
  725. receiveBenefitsRecordMapper.updateById(receiveBenefitsRecord);
  726. }
  727. }
  728. if ((newRelation.getStartTime() == null || newRelation.getExpiryTime() == null)) {
  729. List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.hasPayment));
  730. if (orderDonList.isEmpty()) {
  731. orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class)
  732. .eq(OrderDon::getUserId, userId)
  733. .eq(OrderDon::getRelationId, relationId)
  734. .eq(OrderDon::getStatus, OrderDon.Status.complete)
  735. .orderByDesc(OrderDon::getId)
  736. .last("limit 1"));
  737. }
  738. if (groups.getStatus() == GroupsTrips.Status.waiting) {
  739. orderDonList.forEach(hasPaymentOrder -> {
  740. hasPaymentOrder.setRelationId(newRelation.getId());
  741. orderDonMapper.updateById(hasPaymentOrder);
  742. });
  743. relationMapper.updateById(newRelation);
  744. return;
  745. }
  746. orderDonList.forEach((hasPaymentOrder) -> {
  747. //如果续费增加时间,如果首次则设置当前时间为初始时间
  748. Date expiryTime = Optional.ofNullable(newRelation.getExpiryTime()).orElse(new Date());
  749. GoodsDonSku donSku = skuMapper.selectById(hasPaymentOrder.getSkuId());
  750. Date newDate;
  751. if (donSku.getDays() != null && donSku.getDays() > 0) {
  752. newDate = DateUtil.offsetDay(expiryTime, donSku.getDays() * hasPaymentOrder.getNum());
  753. } else {
  754. newDate = DateUtil.offset(expiryTime, DateField.MONTH, donSku.getMonths() * hasPaymentOrder.getNum());
  755. }
  756. newRelation.setExpiryTime(newDate);
  757. newRelation.setStartTime(newRelation.getStartTime() == null ? new Date() : null);
  758. relationMapper.updateById(newRelation);
  759. hasPaymentOrder.setStatus(OrderDon.Status.complete);
  760. hasPaymentOrder.setRelationId(newRelation.getId());
  761. orderDonMapper.updateById(hasPaymentOrder);
  762. });
  763. return;
  764. }
  765. List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.complete));
  766. orderDonList.forEach(completeOrder->{
  767. completeOrder.setRelationId(newRelation.getId());
  768. orderDonMapper.updateById(completeOrder);
  769. });
  770. log.info("userId:{}更换车票,原座位号relationId:{}======>新座位号newRelationId:{}", newRelation.getUserId(), relationId, newRelation.getId());
  771. relationMapper.updateById(newRelation);
  772. //更换车票 调整GPT相关规格新车队 上车数
  773. GoodsDonSku sku = goodsDonSkuMapper.selectById(groups.getSkuId());
  774. groupRelationFrontService.adjustGroupsParkingTime(newRelation.getId(), sku);
  775. //关闭正在恢复的车票
  776. if (orderDon.getGoodsId() == Constant.NETFLIX_GID) {
  777. List<Long> userIdList = userBindRelationService.getRelationUserIdList(orderDon.getUserId(), null);
  778. NetflixUserAccountSubmitRecoverRecord recoverRecord = netflixUserAccountSubmitRecoverRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  779. .eq(NetflixUserAccountSubmitRecoverRecord::getRelationId, orderDon.getRelationId())
  780. .in(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList)
  781. .eq(NetflixUserAccountSubmitRecoverRecord::getStatus, 0)
  782. .last("limit 1"));
  783. if (recoverRecord != null) {
  784. recoverRecord.setStatus(3);
  785. netflixUserAccountSubmitRecoverRecordMapper.updateById(recoverRecord);
  786. }
  787. }
  788. }
  789. public String zfbRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
  790. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) <=0){
  791. return StrUtil.EMPTY;
  792. }
  793. AlipayTradeRefundResponse response;
  794. //支付宝退款
  795. AlipayClient alipayClient = AliPayClientFactory.getAlipayClient(Optional.ofNullable(orderDon.getShopId()).orElse(ShopConfig.ZFB_DEFAULT_APP_ID));
  796. AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
  797. AlipayTradeRefundModel model = new AlipayTradeRefundModel();
  798. //支付宝交易号
  799. model.setTradeNo(orderDon.getTransactionId());
  800. model.setRefundAmount(refundReq.getRefundMoney().divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_EVEN).toString());
  801. model.setQueryOptions(List.of("gmt_refund_pay"));
  802. long time = System.currentTimeMillis();
  803. //退款订单号
  804. String outRefundNo = Codec.DoDigest.custom()
  805. .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
  806. .setStringData(time + String.valueOf(orderDon.getId()))
  807. .toHexString();
  808. //退款请求号
  809. model.setOutRequestNo(outRefundNo);
  810. request.setBizModel(model);
  811. String shopId = orderDon.getShopId();
  812. ShopConfig shopConfig = shopConfigMapper.selectOne(Wrappers.lambdaQuery(ShopConfig.class).eq(ShopConfig::getAppId, orderDon.getShopId()));
  813. if (shopId != null && shopConfig != null && shopConfig.getIsCert()) {
  814. response = alipayClient.certificateExecute(request);
  815. } else {
  816. response = alipayClient.execute(request);
  817. }
  818. if (!response.isSuccess()) throw BusinessRuntimeException.getInstance("退款失败,e:{0}", response.getSubMsg());
  819. // AliPayRefundRep aliPayRefundRep = Jsons.parseObject(response.getBody(), AliPayRefundRep.class);
  820. // AliPayRefundRep.AlipayTradeRefundResponse res = aliPayRefundRep.getResponse();
  821. // orderDon.setRefundMoney(res.getRefundFee().multiply(BigDecimal.valueOf(100)));
  822. return outRefundNo;
  823. }
  824. /**
  825. * 校验订单是否符合退款操作
  826. */
  827. private void checkOrderRefund(OrderDon orderDon, GoodsDon goodsDon, GoodsDonSku sku, OrderRefundReq refundReq) {
  828. if (orderDon == null) {
  829. throw BusinessRuntimeException.getInstance("订单不存在");
  830. }
  831. BigDecimal orderDonRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  832. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  833. String refundType = refundReq.getRefundType();
  834. // if (orderDon.getType() == OrderDon.Type.BALANCE && !OrderDon.Type.BALANCE.getType().equals(refundType)) {
  835. // throw BusinessRuntimeException.getInstance("余额支付的订单不支持金额退款");
  836. // }
  837. if (OrderDon.Status.refund == orderDon.getStatus()) {
  838. throw BusinessRuntimeException.getInstance("该订单已退款");
  839. }
  840. if (OrderDon.Status.noPayment == orderDon.getStatus() || OrderDon.Status.close == orderDon.getStatus()) {
  841. throw BusinessRuntimeException.getInstance("订单{0}状态不支持退款", orderDon.getStatus());
  842. }
  843. if (goodsDon.getId() == Constant.NETFLIX_GID) {
  844. Integer selectCount = netflixUserChangeOtherTicketRecordMapper.selectCount(Wrappers.lambdaQuery(NetflixUserChangeOtherTicketRecord.class)
  845. .eq(NetflixUserChangeOtherTicketRecord::getOrderId, orderDon.getId()));
  846. if (selectCount > 0) {
  847. throw BusinessRuntimeException.getInstance("该奈飞车票已替换其他车票,无法退款");
  848. }
  849. }
  850. if (goodsDon.getType() == 1 && sku != null) {
  851. //虚拟原订单是否已过期
  852. Integer months = sku.getMonths();
  853. Integer days = sku.getDays();
  854. Integer num = orderDon.getNum();
  855. DateTime now = DateTime.now();
  856. DateTime endTime;
  857. if (days != null && days > 0) {
  858. endTime = DateUtil.offsetDay(orderDon.getCreatedTime(), days * num);
  859. } else {
  860. endTime = DateUtil.offsetMonth(orderDon.getCreatedTime(), months * num);
  861. }
  862. if (now.isAfter(endTime)) {
  863. throw BusinessRuntimeException.getInstance("该订单车票已过期");
  864. }
  865. if (orderDon.getOrderType() == 1) {
  866. //是否有其他付款订单是否过期
  867. OrderDon otherOrder = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  868. .eq(OrderDon::getRelationId, orderDon.getRelationId())
  869. .eq(OrderDon::getUserId, orderDon.getUserId())
  870. .ne(OrderDon::getId, orderDon.getId())
  871. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  872. .eq(OrderDon::getOrderType, 2)
  873. .orderByDesc(OrderDon::getId)
  874. .last("limit 1"));
  875. if (otherOrder != null) {
  876. throw BusinessRuntimeException.getInstance("该笔订单存在续费订单,请先退掉续费订单");
  877. }
  878. }
  879. }
  880. BigDecimal refundMoney = refundReq.getRefundMoney();
  881. BigDecimal money = orderDon.getMoney();
  882. //余额退款
  883. if (OrderDon.Type.BALANCE.getType().equals(refundType)) {
  884. BigDecimal balance = orderDon.getBalance();
  885. refundMoney = orderDonRefundBalance.add(refundMoney);
  886. if (OrderDon.Type.BALANCE == orderDon.getType() && refundMoney.compareTo(balance) > 0) {
  887. throw BusinessRuntimeException.getInstance("退款余额大于订单支付余额");
  888. }
  889. if (OrderDon.Type.BALANCE != orderDon.getType() && refundMoney.compareTo(money) > 0) {
  890. throw BusinessRuntimeException.getInstance("退款余额大于订单支付金额");
  891. }
  892. orderDon.setRefundBalance(refundMoney);
  893. orderDon.setRefundMoney(BigDecimal.ZERO);
  894. } else {
  895. //退金额
  896. refundMoney = orderDonRefundMoney.add(refundMoney);
  897. if (refundMoney.compareTo(money) > 0) {
  898. throw BusinessRuntimeException.getInstance("退款金额大于订单支付金额");
  899. }
  900. orderDon.setRefundMoney(refundMoney);
  901. }
  902. //礼品卡是否已使用
  903. GiftCardUserRecord giftCardUserRecord = null;
  904. if (goodsDon.getSpecialType() != null && goodsDon.getSpecialType() == GoodsDon.SpecialType.giftCard) {
  905. Integer count = giftCardUserRecordMapper.selectCount(Wrappers.lambdaQuery(GiftCardUserRecord.class)
  906. .eq(GiftCardUserRecord::getIsUsed, 1)
  907. .eq(GiftCardUserRecord::getOrderId, orderDon.getId()));
  908. if (count > 0) {
  909. throw BusinessRuntimeException.getInstance("该礼品卡已使用无法退款");
  910. }
  911. }
  912. if (!redisService.setNx(String.format("%s", refundReq.getOrderId()), refundReq.getOrderId(), 10l)) {
  913. throw BusinessRuntimeException.getInstance("请勿重复点击,正在退款中..");
  914. }
  915. //礼品卡购买状态
  916. if (giftCardUserRecord != null) {
  917. giftCardUserRecord.setIsPay(false);
  918. giftCardUserRecordMapper.updateById(giftCardUserRecord);
  919. }
  920. //校验续费升级规格
  921. checkMirrorRenewSku(orderDon);
  922. }
  923. /**
  924. * 退款后 处理关联
  925. */
  926. 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) {
  927. orderRefundService.refundRecord(orderDon, refundMoney, operator, goodsDon, sku, outNo, refundType, chatImg);
  928. //退款一次
  929. goodsDonStockService.upStockRelate(null, orderDon.getId(), "refund");
  930. try {
  931. if (!orderDon.getIsDp()) {
  932. //虚物订单退款,清出车队,车票变为已过期
  933. orderCommonService.clearUnrealGoodsDetail(orderDon, goodsDon.getType(), sku);
  934. }
  935. } catch (Exception e) {
  936. log.error("清除车票错误:{}", StringUtil.getErrorText(e));
  937. }
  938. //若存在优惠券使用,退还优惠券
  939. if (orderDon.getCouponUserId() != 0) {
  940. couponFontService.updateOrderDonCouponStatus(orderDon);
  941. }
  942. //退等比例
  943. if (isOnly != null && isOnly) {
  944. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.refund, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  945. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  946. orderDon.setRefundBalance(orderDonRefundBalance.add(refundBalance));
  947. }
  948. //若存在余额支付,退还余额
  949. if (isOnly == null && orderDon.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  950. BigDecimal addBalance = orderDon.getBalance();
  951. //需额外扣除余额
  952. if (deductBalance != null && deductBalance.compareTo(BigDecimal.ZERO) > 0) {
  953. addBalance = addBalance.subtract(deductBalance);
  954. }
  955. userBenefitsService.addUserBalance(orderDon.getUserId(), addBalance, UserBalanceSourceRecord.Source.refund, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  956. }
  957. //是否全额退款
  958. // BigDecimal orderDonRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  959. // BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  960. // if (orderDonRefundMoney.add(orderDonRefundBalance).compareTo(orderDon.getMoney().add(Optional.ofNullable(orderDon.getBalance()).orElse(BigDecimal.ZERO))) == 0) {
  961. // //是否使用银河币支付
  962. // OrderDonGalaxyCoinRecord orderDonGalaxyCoinRecord = orderDonGalaxyCoinRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonGalaxyCoinRecord.class)
  963. // .eq(OrderDonGalaxyCoinRecord::getSource, OrderDonGalaxyCoinRecord.Source.ordinary.ordinal())
  964. // .eq(OrderDonGalaxyCoinRecord::getOrderId, orderDon.getId())
  965. // .last("limit 1"));
  966. // if (orderDonGalaxyCoinRecord != null) {
  967. // //有效时,返还银河币 并记录
  968. // userGalaxyCoinService.recordOrderRefundGalaxyCoinIfValid(orderDon.getId(), orderDonGalaxyCoinRecord.getUserId(), orderDonGalaxyCoinRecord.getGalaxyCoin().abs(), OrderDonGalaxyCoinRecord.Source.ordinary);
  969. // }
  970. // }
  971. //扣除 该笔订单产生的返现银河币
  972. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) > 0) {
  973. userGalaxyCoinService.subOrderGenerateGalaxyCoin(orderDon.getId(), OrderDonGalaxyCoinRecord.Source.ordinary);
  974. }
  975. try {
  976. marketFrontService.subSpecificChanceNum(orderDon.getUserId(), orderDon.getId(), orderDon.getGoodsId(), orderDon.getUpdateTime());
  977. if (goodsDon.getType() == 2 && !orderDon.getIsDistribute()) {
  978. equipmentDistributeService.subDistributeBenefitsChance(orderDon.getUserId(), orderDon.getId());
  979. //扣除用户自身实物权益
  980. userRealOrderBenefitsService.deductUserRealGoodsBenefits(orderDon.getId());
  981. }
  982. } catch (Exception e) {
  983. log.error("wx减少抽奖机会错误,orderId:{},error:{}", orderDon.getId(), e);
  984. }
  985. if (OrderDon.Type.BALANCE.getType().equals(refundType)) {
  986. if (isOnly == null && orderDon.getMoney().compareTo(BigDecimal.ZERO) > 0) {
  987. userBenefitsService.addUserBalance(orderDon.getUserId(), orderDon.getRefundBalance(), UserBalanceSourceRecord.Source.refund, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  988. }
  989. } else {
  990. //余额退款不需要扣除积分
  991. //分销提成积分扣除
  992. deductDsPoints(orderDon);
  993. //店铺 分销提成金额扣除
  994. yhShopDistributeService.deductDsMoney(orderDon);
  995. //镜像店铺 分销提成金额扣除
  996. deductUserMirrorShopMoney(orderDon);
  997. }
  998. if (orderDon.getIsFixedDistribute()) {
  999. //商务提成 因订单退款去掉
  1000. UserDistributeBusinessOrderDonRecord record = businessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(UserDistributeBusinessOrderDonRecord.class)
  1001. .eq(UserDistributeBusinessOrderDonRecord::getOrderId, orderDon.getId())
  1002. .eq(UserDistributeBusinessOrderDonRecord::getStatus, UserDistributeBusinessOrderDonRecord.Status.success)
  1003. .last("limit 1"));
  1004. if (record != null) {
  1005. record.setStatus(UserDistributeBusinessOrderDonRecord.Status.refund);
  1006. businessOrderDonRecordMapper.updateById(record);
  1007. }
  1008. }
  1009. //店铺商务提成
  1010. if (orderDon.getYhsId() != null && orderDon.getYhsId() > 0) {
  1011. YhShopUserDistributeBusinessOrderDonRecord shop_record = yhShopBusinessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(YhShopUserDistributeBusinessOrderDonRecord.class)
  1012. .eq(YhShopUserDistributeBusinessOrderDonRecord::getOrderId, orderDon.getId())
  1013. .eq(YhShopUserDistributeBusinessOrderDonRecord::getStatus, YhShopUserDistributeBusinessOrderDonRecord.Status.success)
  1014. .last("limit 1"));
  1015. if (shop_record != null) {
  1016. shop_record.setStatus(YhShopUserDistributeBusinessOrderDonRecord.Status.refund);
  1017. yhShopBusinessOrderDonRecordMapper.updateById(shop_record);
  1018. }
  1019. }
  1020. //是否是优惠加购关联订单
  1021. if (orderDon.getIsDp()) {
  1022. OrderDiscountPlusPurchaseSkuRelation discountPlusPurchaseSkuRelation = orderDiscountPlusPurchaseSkuRelationMapper.selectOne(Wrappers.lambdaQuery(OrderDiscountPlusPurchaseSkuRelation.class)
  1023. .eq(OrderDiscountPlusPurchaseSkuRelation::getOrderId, orderDon.getId()).last("limit 1"));
  1024. if (discountPlusPurchaseSkuRelation != null) {
  1025. //选择清除加购车票
  1026. if (CollUtil.isNotEmpty(dpRelationIds)) {
  1027. try {
  1028. List<GroupsRelation> groupsRelations = relationMapper.selectList(Wrappers.lambdaQuery(GroupsRelation.class)
  1029. .eq(GroupsRelation::getUserId, orderDon.getUserId())
  1030. .in(GroupsRelation::getId, dpRelationIds));
  1031. log.info("优惠加购订单orderId:{}退款,清除相关车票relation_ids:{}", orderDon.getId(), dpRelationIds);
  1032. groupsRelations.forEach(relation -> relationClearService.clearTicket(relation, UserTicketClearedRecord.Source.dp));
  1033. } catch (Exception e) {
  1034. }
  1035. }
  1036. String plusOrderIds = discountPlusPurchaseSkuRelation.getPlusOrderIds();
  1037. if (StrUtil.isNotBlank(plusOrderIds)) {
  1038. try {
  1039. log.info("关闭优惠加购orderId:{}关联实物订单", orderDon.getId());
  1040. List<Long> plusOrderIdList = Jsons.parseList(plusOrderIds, Long.class);
  1041. List<OrderDon> relate_orderDons = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class)
  1042. .in(OrderDon::getId, plusOrderIdList)
  1043. .notIn(OrderDon::getStatus, Constant.noOrderStatus));
  1044. relate_orderDons.forEach(relate_o -> {
  1045. //扣除用户自身实物权益
  1046. userRealOrderBenefitsService.deductUserRealGoodsBenefits(relate_o.getId());
  1047. });
  1048. orderDonMapper.update(null, Wrappers.lambdaUpdate(OrderDon.class)
  1049. .set(OrderDon::getStatus, OrderDon.Status.refund)
  1050. .in(OrderDon::getId, plusOrderIdList)
  1051. .ne(OrderDon::getStatus, OrderDon.Status.refund));
  1052. } catch (Exception e) {
  1053. }
  1054. }
  1055. }
  1056. }
  1057. //同步车票退款 重购记录
  1058. TASK_POOL.execute(() -> {
  1059. GroupsRelationExpiryRecord groupsRelationExpiryRecord = groupsRelationExpiryRecordService.getOne(Wrappers.lambdaQuery(GroupsRelationExpiryRecord.class)
  1060. .in(GroupsRelationExpiryRecord::getReBuyOrderId, orderDon.getId())
  1061. .eq(GroupsRelationExpiryRecord::getRelationId, orderDon.getRelationId()).last("limit 1"));
  1062. if (groupsRelationExpiryRecord == null) {
  1063. log.info("订单orderId:{}退款,同步是否有重购记录不是直接续费车票", orderDon.getId());
  1064. List<GroupsRelationExpiryRecord> groupsRelationExpiryRecords = groupsRelationExpiryRecordService.list(Wrappers.lambdaQuery(GroupsRelationExpiryRecord.class)
  1065. .in(GroupsRelationExpiryRecord::getReBuyOrderId, orderDon.getId()));
  1066. log.info("订单orderId:{}退款,重购记录不是直接续费车票大小:{}", groupsRelationExpiryRecords.size());
  1067. if (CollUtil.isNotEmpty(groupsRelationExpiryRecords)) {
  1068. groupsRelationExpiryRecords.forEach(data -> {
  1069. data.setIsReBuy(false);
  1070. });
  1071. groupsRelationExpiryRecordService.saveOrUpdateBatch(groupsRelationExpiryRecords);
  1072. }
  1073. }
  1074. if (groupsRelationExpiryRecord != null) {
  1075. groupsRelationExpiryRecord.setIsReBuy(false);
  1076. groupsRelationExpiryRecordService.saveOrUpdate(groupsRelationExpiryRecord);
  1077. }
  1078. });
  1079. //是否是礼品卡 现金支付订单
  1080. BigDecimal gcCash = orderDon.getGcCash();
  1081. if (gcCash != null && gcCash.compareTo(BigDecimal.ZERO) > 0) {
  1082. giftCardOrderUseRecordService.returnGiftCardCash(orderDon.getId());
  1083. }
  1084. //清除礼品卡
  1085. if (goodsDon.getSpecialType() != null && goodsDon.getSpecialType() == GoodsDon.SpecialType.giftCard) {
  1086. giftCardUserRecordMapper.update(null, Wrappers.lambdaUpdate(GiftCardUserRecord.class)
  1087. .set(GiftCardUserRecord::getIsPay, 0)
  1088. .eq(GiftCardUserRecord::getOrderId, orderDon.getId()));
  1089. }
  1090. //是否是分销订单
  1091. //处理下级渠道分销提成
  1092. handleSubRewards(orderDon);
  1093. //是否是用户套餐优惠权益订单
  1094. if (orderDon.getGoodsId() == 15) {
  1095. UserBenefitsComboRelationRecord userBenefitsComboRelationRecord = userBenefitsComboRelationRecordMapper.selectOne(Wrappers.lambdaQuery(UserBenefitsComboRelationRecord.class)
  1096. .eq(UserBenefitsComboRelationRecord::getOrderId, orderDon.getId()).last("limit 1"));
  1097. if (userBenefitsComboRelationRecord != null) {
  1098. try {
  1099. String relationIds = userBenefitsComboRelationRecord.getRelationIds();
  1100. List<Long> relationIdList = Jsons.parseList(relationIds, Long.class);
  1101. //清空车票或减少车票时间
  1102. relationIdList.forEach(relationId -> {
  1103. orderCommonService.clearUserTicketTime(relationId);
  1104. });
  1105. } catch (Exception e) {
  1106. }
  1107. }
  1108. }
  1109. //HBO GO退款,车队上架
  1110. setUpIfEmpty(orderDon.getGoodsId(), orderDon.getRelationId());
  1111. if (orderDon.getGoodsId() == Constant.NETFLIX_GID) {
  1112. List<Long> userIdList = userBindRelationService.getRelationUserIdList(orderDon.getUserId(), null);
  1113. NetflixUserAccountSubmitRecoverRecord recoverRecord = netflixUserAccountSubmitRecoverRecordMapper.selectOne(Wrappers.lambdaQuery(NetflixUserAccountSubmitRecoverRecord.class)
  1114. .eq(NetflixUserAccountSubmitRecoverRecord::getRelationId, orderDon.getRelationId())
  1115. .in(NetflixUserAccountSubmitRecoverRecord::getUserId, userIdList)
  1116. .eq(NetflixUserAccountSubmitRecoverRecord::getStatus, 0)
  1117. .last("limit 1"));
  1118. if (recoverRecord != null) {
  1119. recoverRecord.setStatus(3);
  1120. netflixUserAccountSubmitRecoverRecordMapper.updateById(recoverRecord);
  1121. }
  1122. }
  1123. }
  1124. //处理下级渠道分销提成
  1125. public void handleSubRewards(OrderDon orderDon) {
  1126. //是否是分销订单
  1127. //处理下级渠道分销提成
  1128. if (orderDon.getIsDistribute()) {
  1129. UserDistributeSub subRelate = userDistributeSubMapper.getSubRelate(orderDon.getUserId());
  1130. if (subRelate != null) {
  1131. List<UserDistributeSubWaiting> subWaitings = subWaitingMapper.selectList(Wrappers.lambdaQuery(UserDistributeSubWaiting.class)
  1132. .eq(UserDistributeSubWaiting::getSubUserId, subRelate.getSubUserId())
  1133. .eq(UserDistributeSubWaiting::getSendStatus, UserDistributeSubWaiting.Status.waiting));
  1134. if (CollUtil.isNotEmpty(subWaitings)) {
  1135. List<UserDistributeSubRewards> userDistributeSubRewards = userDistributeSubRewardsMapper.selectList(null);
  1136. Map<Integer, List<UserDistributeSubRewards>> rewardLevelMap = userDistributeSubRewards.stream().collect(Collectors.groupingBy(UserDistributeSubRewards::getLevel));
  1137. subWaitings.forEach(wait -> {
  1138. List<UserDistributeSubRewards> thisLevelList = rewardLevelMap.get(wait.getLevel());
  1139. if (thisLevelList == null) {
  1140. return;
  1141. }
  1142. UserDistributeSubRewards thisLevel = thisLevelList.get(0);
  1143. Integer months = thisLevel.getMonths();
  1144. BigDecimal subOrderMoney = Optional.ofNullable(orderDonMapper.selectSubChannelOrderMoney(wait.getSubUserId(), subRelate.getCreatedTime(), DateUtil.offsetMonth(subRelate.getCreatedTime(), months))).orElse(BigDecimal.ZERO);
  1145. if (subOrderMoney.compareTo(thisLevel.getTargetAmount()) < 0) {
  1146. subWaitingMapper.update(null, Wrappers.lambdaUpdate(UserDistributeSubWaiting.class)
  1147. .set(UserDistributeSubWaiting::getSendStatus, UserDistributeSubWaiting.Status.close)
  1148. .eq(UserDistributeSubWaiting::getSendStatus, UserDistributeSubWaiting.Status.waiting)
  1149. .eq(UserDistributeSubWaiting::getId, wait.getId()));
  1150. }
  1151. });
  1152. }
  1153. }
  1154. }
  1155. }
  1156. /**
  1157. * 退款 分销提成积分扣除
  1158. */
  1159. public void deductDsPoints(OrderDon orderDon) {
  1160. if (orderDon.getIsDistribute()) {
  1161. DistributeWaitingSendPoints distributeWaitingSendPoints = distributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(DistributeWaitingSendPoints.class).eq(DistributeWaitingSendPoints::getOrderId, orderDon.getId()).eq(DistributeWaitingSendPoints::getIsVip,Boolean.FALSE).last("limit 1"));
  1162. if (distributeWaitingSendPoints != null) {
  1163. BigDecimal money = orderDon.getMoney();
  1164. BigDecimal refundMoney = orderDon.getRefundMoney();
  1165. //已发送 发送中 部分 全额退款
  1166. DistributeWaitingSendPoints.Status sendStatus = distributeWaitingSendPoints.getSendStatus();
  1167. BigDecimal points = distributeWaitingSendPoints.getPoints();
  1168. if (sendStatus == DistributeWaitingSendPoints.Status.waiting) {
  1169. //实物设备退款就清0
  1170. if (refundMoney.compareTo(money) == 0 || orderDon.getGoodsId() == 15) {
  1171. //待发送状态 全额退款
  1172. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  1173. distributeWaitingSendPoints.setRefundPoints(points);
  1174. distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
  1175. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1176. return;
  1177. }
  1178. Integer thisGoodsRate = distributeWaitingSendPoints.getRate();
  1179. if (thisGoodsRate == null || thisGoodsRate == 0) {
  1180. thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
  1181. }
  1182. if (thisGoodsRate > 0) {
  1183. BigDecimal refundRate = refundMoney.divide(money, 2, RoundingMode.DOWN);
  1184. //退掉比例的提成
  1185. BigDecimal needSubPoints = points.multiply(refundRate);
  1186. distributeWaitingSendPoints.setRefundPoints(needSubPoints);
  1187. //剩余积分
  1188. BigDecimal remainPoints = points.subtract(needSubPoints);
  1189. distributeWaitingSendPoints.setPoints(remainPoints);
  1190. //原先获取积分也扣除
  1191. if (distributeWaitingSendPoints.getOriPoints().compareTo(BigDecimal.ZERO) > 0) {
  1192. BigDecimal oriNeedSubPoints = distributeWaitingSendPoints.getOriPoints().multiply(refundRate);
  1193. distributeWaitingSendPoints.setOriPoints(distributeWaitingSendPoints.getOriPoints().subtract(oriNeedSubPoints));
  1194. }
  1195. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1196. }
  1197. } else if (sendStatus == DistributeWaitingSendPoints.Status.success) {
  1198. //已发送的提成 部分退款 全额退款 需要扣除用户积分
  1199. //扣除固定推广者积分
  1200. //实物设备退款就清0
  1201. if (refundMoney.compareTo(money) == 0 || orderDon.getGoodsId() == 15) {
  1202. userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), points);
  1203. distributeWaitingSendPoints.setRefundPoints(points);
  1204. distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
  1205. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  1206. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1207. return;
  1208. }
  1209. Integer thisGoodsRate = distributeWaitingSendPoints.getRate();
  1210. if (thisGoodsRate == null || thisGoodsRate == 0) {
  1211. thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
  1212. }
  1213. if (thisGoodsRate > 0) {
  1214. BigDecimal refundRate = refundMoney.divide(money, 2, RoundingMode.DOWN);
  1215. //退掉比例的提成
  1216. BigDecimal needSubPoints = points.multiply(refundRate);
  1217. userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), needSubPoints);
  1218. //部分退款
  1219. distributeWaitingSendPoints.setRefundPoints(needSubPoints);
  1220. distributeWaitingSendPoints.setPoints(points.subtract(needSubPoints));
  1221. //原先获取积分也扣除
  1222. if (distributeWaitingSendPoints.getOriPoints().compareTo(BigDecimal.ZERO) > 0) {
  1223. BigDecimal oriNeedSubPoints = distributeWaitingSendPoints.getOriPoints().multiply(refundRate);
  1224. distributeWaitingSendPoints.setOriPoints(distributeWaitingSendPoints.getOriPoints().subtract(oriNeedSubPoints));
  1225. }
  1226. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1227. }
  1228. }
  1229. }
  1230. }
  1231. }
  1232. @Override
  1233. public void refundPriceDiffer(OrderRefundReq orderRefundReq) throws Exception {
  1234. Long orderId = orderRefundReq.getOrderId();
  1235. OrderDon orderDon = orderDonMapper.selectById(orderId);
  1236. if (orderDon == null) {
  1237. throw BusinessRuntimeException.getInstance("订单不存在");
  1238. }
  1239. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  1240. throw BusinessRuntimeException.getInstance("该订单是0元订单,无法补差价");
  1241. }
  1242. if (Constant.noOrderAllStatus.contains(orderDon.getStatus().name())) {
  1243. throw BusinessRuntimeException.getInstance("订单不是已支付状态");
  1244. }
  1245. //默认补差价余额
  1246. String refundType = Optional.ofNullable(orderRefundReq.getRefundType()).orElse("balance");
  1247. BigDecimal refundMoney = orderRefundReq.getRefundMoney();
  1248. BigDecimal orderRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  1249. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  1250. if (refundMoney.add(orderRefundMoney).add(orderDonRefundBalance).compareTo(orderDon.getRealMoney()) >= 0) {
  1251. throw BusinessRuntimeException.getInstance("补差价已达到该订单付款金额");
  1252. }
  1253. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  1254. GoodsDonSku sku = null;
  1255. if (orderDon.getSkuId() != null) {
  1256. sku = skuMapper.selectById(orderDon.getSkuId());
  1257. }
  1258. orderDon.setRefundDesc("补差价");
  1259. String outNo = StrUtil.EMPTY;
  1260. if ("money".equals(refundType)) {
  1261. if (refundMoney == null || refundMoney.compareTo(BigDecimal.ZERO) <= 0) {
  1262. throw BusinessRuntimeException.getInstance("请输入正确的差价金额");
  1263. }
  1264. if (refundMoney.compareTo(orderDon.getMoney()) >= 0) {
  1265. throw BusinessRuntimeException.getInstance("补差价金额应不大于订单金额");
  1266. }
  1267. //退款
  1268. orderRefundReq.setIsDiffer(true);
  1269. outNo = orderRefundService.centerRefund(orderRefundReq, orderDon);
  1270. orderDon.setRefundMoney(orderRefundMoney.add(refundMoney));
  1271. orderDonMapper.updateById(orderDon);
  1272. //补差价金额 扣除对应分销提成金额
  1273. orderDon.setRefundMoney(refundMoney);
  1274. deductDsPoints(orderDon);
  1275. //店铺分销提成金额扣除
  1276. yhShopDistributeService.deductDsMoney(orderDon);
  1277. } else {
  1278. BigDecimal refundBalance = refundMoney;
  1279. if (refundBalance == null || refundBalance.compareTo(BigDecimal.ZERO) <= 0 || refundBalance.compareTo(orderDon.getMoney()) > 0) {
  1280. throw BusinessRuntimeException.getInstance("请输入正确的差价金额");
  1281. }
  1282. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.price_differ, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.price_differ.getDesc(), true);
  1283. orderDon.setRefundBalance(orderDonRefundBalance.add(refundBalance));
  1284. orderDonMapper.updateById(orderDon);
  1285. }
  1286. orderRefundService.refundRecord(orderDon, refundMoney, orderRefundReq.getOperator(), goodsDon, sku, outNo, refundType, null);
  1287. }
  1288. @Override
  1289. @Transactional(rollbackFor = Throwable.class)
  1290. public void clearBalanceToRefundMoney(OrderBalanceRefundReq refundReq) throws Exception {
  1291. Long refundOrderId = refundReq.getRefundOrderId();
  1292. BigDecimal refundMoney = refundReq.getRefundMoney();
  1293. RefundOrderDon refundOrderDon = refundOrderDonMapper.selectById(refundOrderId);
  1294. if (!"balance".equals(refundOrderDon.getRefundMethod())) {
  1295. throw BusinessRuntimeException.getInstance("该记录不是余额退款类型");
  1296. }
  1297. Long orderId = refundOrderDon.getOrderId();
  1298. OrderDon orderDon = orderDonMapper.selectById(orderId);
  1299. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  1300. throw BusinessRuntimeException.getInstance("该记录对应的订单无实际支付金额");
  1301. }
  1302. if (refundOrderDon.getIsClearBalance()) {
  1303. throw BusinessRuntimeException.getInstance("该笔退款余额记录已退款");
  1304. }
  1305. BigDecimal refundFee = refundOrderDon.getRefundFee();
  1306. //默认退全部余额
  1307. if (refundMoney != null) {
  1308. refundFee = refundMoney;
  1309. }
  1310. BigDecimal money = orderDon.getMoney();
  1311. //若退款余额 大于退款金额 将退款余额至为 退款金额
  1312. if (refundFee.compareTo(money) > 0) {
  1313. refundFee = money;
  1314. }
  1315. User user = userMapper.selectById(orderDon.getUserId());
  1316. if (user.getBalance().compareTo(refundFee) < 0) {
  1317. throw BusinessRuntimeException.getInstance("用户余额不足,无法扣除对应退款余额");
  1318. }
  1319. int update = userMapper.update(null, Wrappers.lambdaUpdate(User.class)
  1320. .set(User::getBalance, user.getBalance().subtract(refundFee))
  1321. .eq(User::getId, user.getId())
  1322. .eq(User::getBalance, user.getBalance()));
  1323. if (update == 0) {
  1324. throw BusinessRuntimeException.getInstance("扣除用户退款余额失败,请重试...");
  1325. }
  1326. OrderRefundReq orderRefundReq = new OrderRefundReq();
  1327. orderRefundReq.setOrderId(orderId);
  1328. orderRefundReq.setRefundMoney(refundFee);
  1329. orderRefundReq.setRefundType("money");
  1330. String outNo = orderRefundService.centerRefund(orderRefundReq, orderDon);
  1331. orderDon.setRefundBalance(orderDon.getRefundBalance().subtract(refundFee));
  1332. BigDecimal orderRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  1333. orderDon.setRefundMoney(orderRefundMoney.add(refundFee));
  1334. orderDonMapper.updateById(orderDon);
  1335. refundOrderDon.setOutRefundNo(outNo);
  1336. refundOrderDon.setIsClearBalance(true);
  1337. refundOrderDonMapper.updateById(refundOrderDon);
  1338. }
  1339. /**
  1340. * 寻找该车队空余车位
  1341. */
  1342. public GroupsRelation getRelationThisTrips(Long userId, Long groupsId, Integer retryNum) {
  1343. //寻找快满编车队进行占座
  1344. GroupsRelation relation = relationMapper.selectRandomOneRelationByGroupsId(groupsId);
  1345. if (relation == null) {
  1346. throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  1347. }
  1348. Long relationId = relation.getId();
  1349. if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
  1350. if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  1351. retryNum++;
  1352. return getRelationThisTrips(userId, groupsId, retryNum);
  1353. }
  1354. int count = groupsMapper.decrAvailableNum(relation.getGroupsId());
  1355. if (count == 0) {
  1356. log.error("车位异常 groupId:{}", groupsId);
  1357. groupsMapper.updateAvailableNum(groupsId);
  1358. throw new BusinessRuntimeException("车位异常");
  1359. }
  1360. return relation;
  1361. }
  1362. private GroupsRelation getChatGPTOutsideRelation(Long userId, Long groupsId, Integer relationNum, Integer retryNum) {
  1363. //寻找快满编车队额外座位
  1364. GroupsRelation relation = relationMapper.selectOutsideRelationByGroupsId(groupsId, relationNum);
  1365. if (relation == null) {
  1366. relation = new GroupsRelation();
  1367. relation.setStatus(GroupsRelation.Status.outside);
  1368. relation.setUserId(userId);
  1369. relation.setGroupsId(groupsId);
  1370. GroupsRelation maxNumRelation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getGroupsId, groupsId).orderByDesc(GroupsRelation::getNum).last("limit 1"));
  1371. relation.setNum(maxNumRelation.getNum() + 1);
  1372. relationMapper.insert(relation);
  1373. return relation;
  1374. }
  1375. Long relationId = relation.getId();
  1376. if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
  1377. if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  1378. retryNum++;
  1379. return getChatGPTOutsideRelation(userId, groupsId, relationNum, retryNum);
  1380. }
  1381. return relation;
  1382. }
  1383. private void checkMirrorRenewSku(OrderDon orderDon) {
  1384. Long skuId = orderDon.getSkuId();
  1385. Long orderId = orderDon.getId();
  1386. OrderDonRenewRecord orderDonRenewRecord = orderDonRenewRecordMapper.selectOne(Wrappers.lambdaQuery(OrderDonRenewRecord.class)
  1387. .eq(OrderDonRenewRecord::getOrderId, orderId)
  1388. .last("limit 1"));
  1389. if (orderDonRenewRecord != null) {
  1390. //gpt
  1391. if (orderDon.getGoodsId() == 18) {
  1392. ChatgptUser chatgptUser = chatgptUserMapper.selectOne(Wrappers.lambdaQuery(ChatgptUser.class)
  1393. .eq(ChatgptUser::getRelationId, orderDon.getRelationId())
  1394. .last("limit 1"));
  1395. Long presentRenewSkuId = chatgptUser.getRenewSkuId();
  1396. if (presentRenewSkuId != null) {
  1397. //存在不同升级套餐
  1398. GoodsDonSku presentRenewSku = skuMapper.selectById(presentRenewSkuId);
  1399. if (!ObjectUtil.equal(presentRenewSkuId, skuId)) {
  1400. throw BusinessRuntimeException.getInstance("请先退掉用户目前续费升级的{0}规格", presentRenewSku.getSpecVal());
  1401. }
  1402. }
  1403. }
  1404. //claude pro
  1405. if (orderDon.getGoodsId() == 75) {
  1406. ClaudeUser claudeUser = claudeUserMapper.selectOne(Wrappers.lambdaQuery(ClaudeUser.class)
  1407. .eq(ClaudeUser::getRelationId, orderDon.getRelationId())
  1408. .last("limit 1"));
  1409. Long presentRenewSkuId = claudeUser.getRenewSkuId();
  1410. if (presentRenewSkuId != null) {
  1411. //存在不同升级套餐
  1412. GoodsDonSku presentRenewSku = skuMapper.selectById(presentRenewSkuId);
  1413. if (!ObjectUtil.equal(presentRenewSkuId, skuId)) {
  1414. throw BusinessRuntimeException.getInstance("请先退掉用户目前续费升级的{0}规格", presentRenewSku.getSpecVal());
  1415. }
  1416. }
  1417. }
  1418. }
  1419. }
  1420. private void clearExtraRelation(OrderDon orderDon) {
  1421. List<UserPayEquipmentReceiveBenefitsRecord> userPayEquipmentReceiveBenefitsRecords = receiveBenefitsRecordMapper.selectList(Wrappers.lambdaQuery(UserPayEquipmentReceiveBenefitsRecord.class)
  1422. .eq(UserPayEquipmentReceiveBenefitsRecord::getRealOrderId, orderDon.getId()));
  1423. userPayEquipmentReceiveBenefitsRecords.forEach(record -> {
  1424. Long skuId = record.getSkuId();
  1425. List<GroupsRelation> relations = relationMapper.selectExtraRelation(orderDon.getUserId(), skuId, record.getRelationId());
  1426. relations.forEach(relation -> {
  1427. //不是优惠加购
  1428. Integer count = orderDiscountPlusPurchaseSkuRelationMapper.selectCount(Wrappers.lambdaQuery(OrderDiscountPlusPurchaseSkuRelation.class)
  1429. .eq(OrderDiscountPlusPurchaseSkuRelation::getUserId, relation.getUserId())
  1430. .apply("JSON_CONTAINS(relation_ids,'" + relation.getId() + "')"));
  1431. if (count == 0) {
  1432. log.info("非优惠加购订单,直接清除userId:{}车票:{}", relation.getUserId(), relation.getId());
  1433. relationClearService.clearTicket(relation, UserTicketClearedRecord.Source.manual);
  1434. }
  1435. });
  1436. });
  1437. }
  1438. /**
  1439. * 扣除用户镜像店铺提成
  1440. */
  1441. private void deductUserMirrorShopMoney(OrderDon orderDon) {
  1442. UserMirrorShopDistributeWaitingSendPoints distributeWaitingSendPoints = userMirrorShopDistributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(UserMirrorShopDistributeWaitingSendPoints.class)
  1443. .eq(UserMirrorShopDistributeWaitingSendPoints::getOrderId, orderDon.getId())
  1444. .last("limit 1"));
  1445. if (distributeWaitingSendPoints != null) {
  1446. BigDecimal money = orderDon.getMoney();
  1447. BigDecimal refundMoney = orderDon.getRefundMoney();
  1448. //已发送 发送中 部分 全额退款
  1449. UserMirrorShopDistributeWaitingSendPoints.Status sendStatus = distributeWaitingSendPoints.getSendStatus();
  1450. BigDecimal take_money = distributeWaitingSendPoints.getMoney();
  1451. if (sendStatus == UserMirrorShopDistributeWaitingSendPoints.Status.waiting) {
  1452. if (refundMoney.compareTo(money) == 0) {
  1453. //待发送状态 全额退款
  1454. distributeWaitingSendPoints.setSendStatus(UserMirrorShopDistributeWaitingSendPoints.Status.close);
  1455. distributeWaitingSendPoints.setRefundMoney(take_money);
  1456. distributeWaitingSendPoints.setMoney(BigDecimal.ZERO);
  1457. userMirrorShopDistributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1458. return;
  1459. }
  1460. Integer rate = distributeWaitingSendPoints.getRate();
  1461. if (rate > 0) {
  1462. BigDecimal needDeductMoney = refundMoney.multiply(BigDecimal.valueOf(rate).divide(BigDecimal.valueOf(100)));
  1463. distributeWaitingSendPoints.setRefundMoney(needDeductMoney);
  1464. //剩余积分
  1465. distributeWaitingSendPoints.setMoney(take_money.subtract(needDeductMoney));
  1466. userMirrorShopDistributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1467. }
  1468. } else if (sendStatus == UserMirrorShopDistributeWaitingSendPoints.Status.success) {
  1469. //已发送的提成 部分退款 全额退款 需要扣除用户积分
  1470. //扣除固定推广者积分
  1471. if (refundMoney.compareTo(money) == 0) {
  1472. //扣除店铺主 已有的提成金额
  1473. userBenefitsService.deductUserMirrorShopTakeMoney(orderDon.getId(), distributeWaitingSendPoints.getShopUserId(), take_money);
  1474. distributeWaitingSendPoints.setRefundMoney(take_money);
  1475. distributeWaitingSendPoints.setMoney(BigDecimal.ZERO);
  1476. distributeWaitingSendPoints.setSendStatus(UserMirrorShopDistributeWaitingSendPoints.Status.close);
  1477. userMirrorShopDistributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1478. return;
  1479. }
  1480. Integer rate = distributeWaitingSendPoints.getRate();
  1481. if (rate > 0) {
  1482. BigDecimal needDeductMoney = refundMoney.multiply(BigDecimal.valueOf(rate).divide(BigDecimal.valueOf(100)));
  1483. //扣除店铺主 已有的提成金额
  1484. userBenefitsService.deductUserMirrorShopTakeMoney(orderDon.getId(), distributeWaitingSendPoints.getShopUserId(), needDeductMoney);
  1485. //部分退款
  1486. distributeWaitingSendPoints.setRefundMoney(needDeductMoney);
  1487. distributeWaitingSendPoints.setMoney(take_money.subtract(needDeductMoney));
  1488. userMirrorShopDistributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  1489. }
  1490. }
  1491. }
  1492. }
  1493. /**
  1494. * 清除多余车票
  1495. */
  1496. private void clearOtherChangeTicket(Long userId, Long relationId, GroupsRelation newRelation, Long skuId) {
  1497. UserTicketClearedRecord userTicketClearedRecord = userTicketClearedRecordMapper.selectOne(Wrappers.lambdaQuery(UserTicketClearedRecord.class)
  1498. .eq(UserTicketClearedRecord::getUserId, userId)
  1499. .eq(UserTicketClearedRecord::getRelationId, relationId)
  1500. .eq(UserTicketClearedRecord::getSource, UserTicketClearedRecord.Source.change_ticket)
  1501. .orderByDesc(UserTicketClearedRecord::getId)
  1502. .last("limit 1"));
  1503. if (userTicketClearedRecord != null) {
  1504. Long newRelationId = userTicketClearedRecord.getNewRelationId();
  1505. List<GroupsRelation> others = relationMapper.selectList(Wrappers.lambdaQuery(GroupsRelation.class)
  1506. .ne(GroupsRelation::getId, newRelationId)
  1507. .eq(GroupsRelation::getUserId, userId)
  1508. .eq(GroupsRelation::getStartTime, newRelation.getStartTime())
  1509. .eq(GroupsRelation::getExpiryTime, newRelation.getExpiryTime()));
  1510. others.forEach(r -> {
  1511. Long groupsId = r.getGroupsId();
  1512. GroupsTrips groupsTrips = groupsMapper.selectById(groupsId);
  1513. //排除 非同规格车票
  1514. if (!skuId.equals(groupsTrips.getSkuId())) {
  1515. return;
  1516. }
  1517. Long rid = r.getId();
  1518. Integer selectCount = orderDonMapper.selectCount(Wrappers.lambdaQuery(OrderDon.class)
  1519. .eq(OrderDon::getUserId, userId)
  1520. .eq(OrderDon::getRelationId, rid)
  1521. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus));
  1522. if (selectCount == 0) {
  1523. //不是优惠加购
  1524. Integer count = orderDiscountPlusPurchaseSkuRelationMapper.selectCount(Wrappers.lambdaQuery(OrderDiscountPlusPurchaseSkuRelation.class)
  1525. .eq(OrderDiscountPlusPurchaseSkuRelation::getUserId, userId)
  1526. .apply("JSON_CONTAINS(relation_ids,'" + rid + "')"));
  1527. if (count == 0) {
  1528. log.info("清除用户:{}多余车票", userId);
  1529. relationClearService.clearTicket(r, UserTicketClearedRecord.Source.manual);
  1530. }
  1531. }
  1532. });
  1533. }
  1534. }
  1535. /**
  1536. * 车队退款 自动上架
  1537. */
  1538. private void setUpIfEmpty(Long goodsId, Long relationId) {
  1539. if (goodsId == Constant.HBO_GO_GOODS_ID) {
  1540. GroupsRelation relation = relationMapper.selectById(relationId);
  1541. if (relation == null) {
  1542. return;
  1543. }
  1544. GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
  1545. if (groupsTrips == null) {
  1546. return;
  1547. }
  1548. if (groupsTrips.getStatus() == GroupsTrips.Status.down) {
  1549. log.info("HBO GO车队:{}存在退款,自动上架", groupsTrips.getId());
  1550. groupsMapper.update(null, Wrappers.lambdaUpdate(GroupsTrips.class)
  1551. .set(GroupsTrips::getStatus, GroupsTrips.Status.validity)
  1552. .eq(GroupsTrips::getId, groupsTrips.getId()));
  1553. }
  1554. }
  1555. }
  1556. }