CmsOrderDonServiceImpl.java 79 KB

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