CmsOrderDonServiceImpl.java 58 KB

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