CmsOrderDonServiceImpl.java 62 KB

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