CmsOrderDonServiceImpl.java 76 KB

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