CmsOrderDonServiceImpl.java 74 KB

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