CmsOrderDonServiceImpl.java 77 KB

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