CmsOrderDonServiceImpl.java 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  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. //是否是GPT镜像规格
  436. delGptUser(orderDon.getGoodsId(), orderDon.getRelationId());
  437. if (plusPurchaseSkuRelation != null && plus_relationList != null) {
  438. plus_relationList.remove(relationId);
  439. plus_relationList.add(newRelation.getId());
  440. plusPurchaseSkuRelation.setRelationIds(plus_relationList.toString());
  441. orderDiscountPlusPurchaseSkuRelationMapper.updateById(plusPurchaseSkuRelation);
  442. }
  443. if (source != null && source == UserTicketClearedRecord.Source.abnormal) {
  444. //将用户异常订单关闭
  445. workOrderMapper.update(null, Wrappers.lambdaUpdate(WorkOrder.class)
  446. .set(WorkOrder::getStatus, WorkOrder.Status.close)
  447. .eq(WorkOrder::getStatus, WorkOrder.Status.waiting)
  448. .eq(WorkOrder::getUserId, userId)
  449. .eq(WorkOrder::getRelationId, relationId));
  450. }
  451. if (orderDon.getMoney() != null && orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  452. //是否是实物权益车票
  453. UserPayEquipmentReceiveBenefitsRecord receiveBenefitsRecord = receiveBenefitsRecordMapper.selectOne(Wrappers.lambdaQuery(UserPayEquipmentReceiveBenefitsRecord.class)
  454. .eq(UserPayEquipmentReceiveBenefitsRecord::getTicketOrderId, orderDon.getId())
  455. .eq(UserPayEquipmentReceiveBenefitsRecord::getRelationId, relationId).last("limit 1"));
  456. if (receiveBenefitsRecord != null) {
  457. receiveBenefitsRecord.setRelationId(newRelation.getId());
  458. receiveBenefitsRecordMapper.updateById(receiveBenefitsRecord);
  459. }
  460. }
  461. if ((newRelation.getStartTime() == null || newRelation.getExpiryTime() == null)) {
  462. List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.hasPayment));
  463. if (orderDonList.isEmpty()) {
  464. orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class)
  465. .eq(OrderDon::getUserId, userId)
  466. .eq(OrderDon::getRelationId, relationId)
  467. .eq(OrderDon::getStatus, OrderDon.Status.complete)
  468. .orderByDesc(OrderDon::getId)
  469. .last("limit 1"));
  470. }
  471. if (groups.getStatus() == GroupsTrips.Status.waiting) {
  472. orderDonList.forEach(hasPaymentOrder -> {
  473. hasPaymentOrder.setRelationId(newRelation.getId());
  474. orderDonMapper.updateById(hasPaymentOrder);
  475. });
  476. relationMapper.updateById(newRelation);
  477. return;
  478. }
  479. orderDonList.forEach((hasPaymentOrder) -> {
  480. //如果续费增加时间,如果首次则设置当前时间为初始时间
  481. Date expiryTime = Optional.ofNullable(newRelation.getExpiryTime()).orElse(new Date());
  482. GoodsDonSku donSku = skuMapper.selectById(hasPaymentOrder.getSkuId());
  483. Date newDate;
  484. if (donSku.getDays() != null && donSku.getDays() > 0) {
  485. newDate = DateUtil.offsetDay(expiryTime, donSku.getDays() * hasPaymentOrder.getNum());
  486. } else {
  487. newDate = DateUtil.offset(expiryTime, DateField.MONTH, donSku.getMonths() * hasPaymentOrder.getNum());
  488. }
  489. newRelation.setExpiryTime(newDate);
  490. newRelation.setStartTime(newRelation.getStartTime() == null ? new Date() : null);
  491. relationMapper.updateById(newRelation);
  492. hasPaymentOrder.setStatus(OrderDon.Status.complete);
  493. hasPaymentOrder.setRelationId(newRelation.getId());
  494. orderDonMapper.updateById(hasPaymentOrder);
  495. });
  496. return;
  497. }
  498. List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.complete));
  499. orderDonList.forEach(completeOrder->{
  500. completeOrder.setRelationId(newRelation.getId());
  501. orderDonMapper.updateById(completeOrder);
  502. });
  503. log.info("userId:{}更换车票,原座位号relationId:{}======>新座位号newRelationId:{}", newRelation.getUserId(), relationId, newRelation.getId());
  504. relationMapper.updateById(newRelation);
  505. //更换车票 调整GPT相关规格新车队 上车数
  506. GoodsDonSku sku = goodsDonSkuMapper.selectById(groups.getSkuId());
  507. groupRelationFrontService.adjustGroupsParkingTime(newRelation.getId(), sku);
  508. }
  509. public String zfbRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
  510. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) <=0){
  511. return StrUtil.EMPTY;
  512. }
  513. AlipayTradeRefundResponse response;
  514. //支付宝退款
  515. AlipayClient alipayClient = AliPayClientFactory.getAlipayClient(Optional.ofNullable(orderDon.getShopId()).orElse(ShopConfig.ZFB_DEFAULT_APP_ID));
  516. AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
  517. AlipayTradeRefundModel model = new AlipayTradeRefundModel();
  518. //支付宝交易号
  519. model.setTradeNo(orderDon.getTransactionId());
  520. model.setRefundAmount(refundReq.getRefundMoney().divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_EVEN).toString());
  521. model.setQueryOptions(List.of("gmt_refund_pay"));
  522. long time = System.currentTimeMillis();
  523. //退款订单号
  524. String outRefundNo = Codec.DoDigest.custom()
  525. .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
  526. .setStringData(time + String.valueOf(orderDon.getId()))
  527. .toHexString();
  528. //退款请求号
  529. model.setOutRequestNo(outRefundNo);
  530. request.setBizModel(model);
  531. String shopId = orderDon.getShopId();
  532. ShopConfig shopConfig = shopConfigMapper.selectOne(Wrappers.lambdaQuery(ShopConfig.class).eq(ShopConfig::getAppId, orderDon.getShopId()));
  533. if (shopId != null && shopConfig != null && shopConfig.getIsCert()) {
  534. response = alipayClient.certificateExecute(request);
  535. } else {
  536. response = alipayClient.execute(request);
  537. }
  538. if (!response.isSuccess()) throw BusinessRuntimeException.getInstance("退款失败,e:{0}", response.getSubMsg());
  539. // AliPayRefundRep aliPayRefundRep = Jsons.parseObject(response.getBody(), AliPayRefundRep.class);
  540. // AliPayRefundRep.AlipayTradeRefundResponse res = aliPayRefundRep.getResponse();
  541. // orderDon.setRefundMoney(res.getRefundFee().multiply(BigDecimal.valueOf(100)));
  542. return outRefundNo;
  543. }
  544. /**
  545. * 校验订单是否符合退款操作
  546. */
  547. private void checkOrderRefund(OrderDon orderDon, GoodsDon goodsDon, GoodsDonSku sku, OrderRefundReq refundReq) {
  548. if (orderDon == null) {
  549. throw BusinessRuntimeException.getInstance("订单不存在");
  550. }
  551. BigDecimal orderDonRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  552. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  553. String refundType = refundReq.getRefundType();
  554. if (orderDon.getType() == OrderDon.Type.BALANCE && !OrderDon.Type.BALANCE.getType().equals(refundType)) {
  555. throw BusinessRuntimeException.getInstance("余额支付的订单不支持金额退款");
  556. }
  557. if (OrderDon.Status.refund == orderDon.getStatus()) {
  558. throw BusinessRuntimeException.getInstance("该订单已退款");
  559. }
  560. if (OrderDon.Status.noPayment == orderDon.getStatus() || OrderDon.Status.close == orderDon.getStatus()) {
  561. throw BusinessRuntimeException.getInstance("订单{0}状态不支持退款", orderDon.getStatus());
  562. }
  563. if (goodsDon.getType() == 1 && sku != null) {
  564. //虚拟原订单是否已过期
  565. Integer months = sku.getMonths();
  566. Integer days = sku.getDays();
  567. Integer num = orderDon.getNum();
  568. DateTime now = DateTime.now();
  569. DateTime endTime;
  570. if (days != null && days > 0) {
  571. endTime = DateUtil.offsetDay(orderDon.getCreatedTime(), days * num);
  572. } else {
  573. endTime = DateUtil.offsetMonth(orderDon.getCreatedTime(), months * num);
  574. }
  575. if (now.isAfter(endTime)) {
  576. throw BusinessRuntimeException.getInstance("该订单车票已过期");
  577. }
  578. if (orderDon.getOrderType() == 1) {
  579. //是否有其他付款订单是否过期
  580. OrderDon otherOrder = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
  581. .eq(OrderDon::getRelationId, orderDon.getRelationId())
  582. .eq(OrderDon::getUserId, orderDon.getUserId())
  583. .ne(OrderDon::getId, orderDon.getId())
  584. .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
  585. .eq(OrderDon::getOrderType, 2)
  586. .orderByDesc(OrderDon::getId)
  587. .last("limit 1"));
  588. if (otherOrder != null) {
  589. throw BusinessRuntimeException.getInstance("该笔订单存在续费订单,请先退掉续费订单");
  590. }
  591. }
  592. }
  593. BigDecimal refundMoney = refundReq.getRefundMoney();
  594. BigDecimal money = orderDon.getMoney();
  595. //余额退款
  596. if (OrderDon.Type.BALANCE.getType().equals(refundType)) {
  597. BigDecimal balance = orderDon.getBalance();
  598. refundMoney = orderDonRefundBalance.add(refundMoney);
  599. if (OrderDon.Type.BALANCE == orderDon.getType() && refundMoney.compareTo(balance) > 0) {
  600. throw BusinessRuntimeException.getInstance("退款余额大于订单支付余额");
  601. }
  602. if (OrderDon.Type.BALANCE != orderDon.getType() && refundMoney.compareTo(money) > 0) {
  603. throw BusinessRuntimeException.getInstance("退款余额大于订单支付金额");
  604. }
  605. orderDon.setRefundBalance(refundMoney);
  606. orderDon.setRefundMoney(BigDecimal.ZERO);
  607. } else {
  608. //退金额
  609. refundMoney = orderDonRefundMoney.add(refundMoney);
  610. if (refundMoney.compareTo(money) > 0) {
  611. throw BusinessRuntimeException.getInstance("退款金额大于订单支付金额");
  612. }
  613. orderDon.setRefundMoney(refundMoney);
  614. }
  615. //礼品卡是否已使用
  616. GiftCardUserRecord giftCardUserRecord = null;
  617. if (goodsDon.getSpecialType() != null && goodsDon.getSpecialType() == GoodsDon.SpecialType.giftCard) {
  618. giftCardUserRecord = giftCardUserRecordMapper.selectOne(Wrappers.lambdaQuery(GiftCardUserRecord.class)
  619. .eq(GiftCardUserRecord::getOrderId, orderDon.getId()).last("limit 1"));
  620. if (giftCardUserRecord != null && giftCardUserRecord.getIsUsed()) {
  621. throw BusinessRuntimeException.getInstance("该礼品卡已使用无法退款");
  622. }
  623. }
  624. if (!redisService.setNx(String.format("%s", refundReq.getOrderId()), refundReq.getOrderId(), 10l)) {
  625. throw BusinessRuntimeException.getInstance("请勿重复点击,正在退款中..");
  626. }
  627. //礼品卡购买状态
  628. if (giftCardUserRecord != null) {
  629. giftCardUserRecord.setIsPay(false);
  630. giftCardUserRecordMapper.updateById(giftCardUserRecord);
  631. }
  632. }
  633. /**
  634. * 退款后 处理关联
  635. */
  636. public void commonRefund(OrderDon orderDon, BigDecimal refundMoney, String operator, GoodsDon goodsDon, GoodsDonSku sku, String outNo, String refundType, Boolean isOnly, BigDecimal refundBalance, String chatImg) {
  637. TASK_POOL.execute(() -> {
  638. orderRefundService.refundRecord(orderDon, refundMoney, operator, goodsDon, sku, outNo, refundType, chatImg);
  639. //退款一次
  640. goodsDonStockService.upStockRelate(null, orderDon.getId(), "refund");
  641. try {
  642. //虚物订单退款,清出车队,车票变为已过期
  643. orderCommonService.clearUnrealGoodsDetail(orderDon, goodsDon.getType(), sku);
  644. } catch (Exception e) {
  645. log.error("清除车票错误:{}", StringUtil.getErrorText(e));
  646. }
  647. //若存在优惠券使用,退还优惠券
  648. if (orderDon.getCouponUserId() != 0) {
  649. couponFontService.updateOrderDonCouponStatus(orderDon);
  650. }
  651. //退等比例
  652. if (isOnly != null && isOnly) {
  653. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.refund, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  654. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  655. orderDon.setRefundBalance(orderDonRefundBalance.add(refundBalance));
  656. }
  657. //若存在余额支付,退还余额
  658. if (isOnly == null && orderDon.getBalance().compareTo(BigDecimal.ZERO) > 0) {
  659. userBenefitsService.addUserBalance(orderDon.getUserId(), orderDon.getBalance(), UserBalanceSourceRecord.Source.refund, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  660. }
  661. try {
  662. marketFrontService.subSpecificChanceNum(orderDon.getUserId(), orderDon.getId(), orderDon.getGoodsId(), orderDon.getUpdateTime());
  663. if (goodsDon.getType() == 2) {
  664. equipmentDistributeService.subDistributeBenefitsChance(orderDon.getUserId(), orderDon.getId());
  665. //扣除用户自身实物权益
  666. userRealOrderBenefitsService.deductUserRealGoodsBenefits(orderDon.getId());
  667. }
  668. } catch (Exception e) {
  669. log.error("wx减少抽奖机会错误,orderId:{},error:{}", orderDon.getId(), e);
  670. }
  671. if (OrderDon.Type.BALANCE.getType().equals(refundType)) {
  672. if (isOnly == null && orderDon.getMoney().compareTo(BigDecimal.ZERO) > 0) {
  673. userBenefitsService.addUserBalance(orderDon.getUserId(), orderDon.getRefundBalance(), UserBalanceSourceRecord.Source.refund, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.refund.getDesc(), true);
  674. }
  675. } else {
  676. //余额退款不需要扣除积分
  677. //分销提成积分扣除
  678. deductDsPoints(orderDon);
  679. //店铺 分销提成金额扣除
  680. yhShopDistributeService.deductDsMoney(orderDon);
  681. }
  682. if (orderDon.getIsFixedDistribute()) {
  683. //商务提成 因订单退款去掉
  684. UserDistributeBusinessOrderDonRecord record = businessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(UserDistributeBusinessOrderDonRecord.class)
  685. .eq(UserDistributeBusinessOrderDonRecord::getOrderId, orderDon.getId())
  686. .eq(UserDistributeBusinessOrderDonRecord::getStatus, UserDistributeBusinessOrderDonRecord.Status.success)
  687. .last("limit 1"));
  688. if (record != null) {
  689. record.setStatus(UserDistributeBusinessOrderDonRecord.Status.refund);
  690. businessOrderDonRecordMapper.updateById(record);
  691. }
  692. }
  693. //店铺商务提成
  694. if (orderDon.getYhsId() != null && orderDon.getYhsId() > 0) {
  695. YhShopUserDistributeBusinessOrderDonRecord shop_record = yhShopBusinessOrderDonRecordMapper.selectOne(Wrappers.lambdaQuery(YhShopUserDistributeBusinessOrderDonRecord.class)
  696. .eq(YhShopUserDistributeBusinessOrderDonRecord::getOrderId, orderDon.getId())
  697. .eq(YhShopUserDistributeBusinessOrderDonRecord::getStatus, YhShopUserDistributeBusinessOrderDonRecord.Status.success)
  698. .last("limit 1"));
  699. if (shop_record != null) {
  700. shop_record.setStatus(YhShopUserDistributeBusinessOrderDonRecord.Status.refund);
  701. yhShopBusinessOrderDonRecordMapper.updateById(shop_record);
  702. }
  703. }
  704. //是否是优惠加购关联订单
  705. if (orderDon.getIsDp()) {
  706. OrderDiscountPlusPurchaseSkuRelation discountPlusPurchaseSkuRelation = orderDiscountPlusPurchaseSkuRelationMapper.selectOne(Wrappers.lambdaQuery(OrderDiscountPlusPurchaseSkuRelation.class)
  707. .eq(OrderDiscountPlusPurchaseSkuRelation::getOrderId, orderDon.getId()).last("limit 1"));
  708. if (discountPlusPurchaseSkuRelation != null) {
  709. String relationIdsStr = discountPlusPurchaseSkuRelation.getRelationIds();
  710. if (StrUtil.isNotBlank(relationIdsStr)) {
  711. try {
  712. List<Long> relationIds = Jsons.parseList(relationIdsStr, Long.class);
  713. List<GroupsRelation> groupsRelations = relationMapper.selectList(Wrappers.lambdaQuery(GroupsRelation.class)
  714. .in(GroupsRelation::getId, relationIds));
  715. log.info("优惠加购订单orderId:{}退款,清除相关车票relation_ids:{}", orderDon.getId(), relationIds);
  716. groupsRelations.forEach(relation -> relationClearService.clearTicket(relation, UserTicketClearedRecord.Source.dp));
  717. } catch (Exception e) {
  718. }
  719. }
  720. String plusOrderIds = discountPlusPurchaseSkuRelation.getPlusOrderIds();
  721. if (StrUtil.isNotBlank(plusOrderIds)) {
  722. try {
  723. log.info("关闭优惠加购orderId:{}关联实物订单", orderDon.getId());
  724. List<Long> plusOrderIdList = Jsons.parseList(plusOrderIds, Long.class);
  725. List<OrderDon> relate_orderDons = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class)
  726. .in(OrderDon::getId, plusOrderIdList)
  727. .notIn(OrderDon::getStatus, Constant.noOrderStatus));
  728. relate_orderDons.forEach(relate_o -> {
  729. //扣除用户自身实物权益
  730. userRealOrderBenefitsService.deductUserRealGoodsBenefits(relate_o.getId());
  731. });
  732. orderDonMapper.update(null, Wrappers.lambdaUpdate(OrderDon.class)
  733. .set(OrderDon::getStatus, OrderDon.Status.refund)
  734. .in(OrderDon::getId, plusOrderIdList)
  735. .ne(OrderDon::getStatus, OrderDon.Status.refund));
  736. } catch (Exception e) {
  737. }
  738. }
  739. }
  740. }
  741. //同步车票退款 重购记录
  742. TASK_POOL.execute(() -> {
  743. GroupsRelationExpiryRecord groupsRelationExpiryRecord = groupsRelationExpiryRecordService.getOne(Wrappers.lambdaQuery(GroupsRelationExpiryRecord.class)
  744. .in(GroupsRelationExpiryRecord::getReBuyOrderId, orderDon.getId())
  745. .eq(GroupsRelationExpiryRecord::getRelationId, orderDon.getRelationId()).last("limit 1"));
  746. if (groupsRelationExpiryRecord == null) {
  747. log.info("订单orderId:{}退款,同步是否有重购记录不是直接续费车票", orderDon.getId());
  748. List<GroupsRelationExpiryRecord> groupsRelationExpiryRecords = groupsRelationExpiryRecordService.list(Wrappers.lambdaQuery(GroupsRelationExpiryRecord.class)
  749. .in(GroupsRelationExpiryRecord::getReBuyOrderId, orderDon.getId()));
  750. log.info("订单orderId:{}退款,重购记录不是直接续费车票大小:{}", groupsRelationExpiryRecords.size());
  751. if (CollUtil.isNotEmpty(groupsRelationExpiryRecords)) {
  752. groupsRelationExpiryRecords.forEach(data -> {
  753. data.setIsReBuy(false);
  754. });
  755. groupsRelationExpiryRecordService.saveOrUpdateBatch(groupsRelationExpiryRecords);
  756. }
  757. }
  758. if (groupsRelationExpiryRecord != null) {
  759. groupsRelationExpiryRecord.setIsReBuy(false);
  760. groupsRelationExpiryRecordService.saveOrUpdate(groupsRelationExpiryRecord);
  761. }
  762. });
  763. //是否是礼品卡 现金支付订单
  764. BigDecimal gcCash = orderDon.getGcCash();
  765. if (gcCash != null && gcCash.compareTo(BigDecimal.ZERO) > 0) {
  766. giftCardOrderUseRecordService.returnGiftCardCash(orderDon.getId());
  767. }
  768. //是否是GPT镜像规格
  769. delGptUser(orderDon.getGoodsId(), orderDon.getRelationId());
  770. //是否是分销订单
  771. //处理下级渠道分销提成
  772. handleSubRewards(orderDon);
  773. });
  774. }
  775. //处理下级渠道分销提成
  776. public void handleSubRewards(OrderDon orderDon) {
  777. //是否是分销订单
  778. //处理下级渠道分销提成
  779. if (orderDon.getIsDistribute()) {
  780. UserDistributeSub subRelate = userDistributeSubMapper.getSubRelate(orderDon.getUserId());
  781. if (subRelate != null) {
  782. List<UserDistributeSubWaiting> subWaitings = subWaitingMapper.selectList(Wrappers.lambdaQuery(UserDistributeSubWaiting.class)
  783. .eq(UserDistributeSubWaiting::getSubUserId, subRelate.getSubUserId())
  784. .eq(UserDistributeSubWaiting::getSendStatus, UserDistributeSubWaiting.Status.waiting));
  785. if (CollUtil.isNotEmpty(subWaitings)) {
  786. List<UserDistributeSubRewards> userDistributeSubRewards = userDistributeSubRewardsMapper.selectList(null);
  787. Map<Integer, List<UserDistributeSubRewards>> rewardLevelMap = userDistributeSubRewards.stream().collect(Collectors.groupingBy(UserDistributeSubRewards::getLevel));
  788. subWaitings.forEach(wait -> {
  789. List<UserDistributeSubRewards> thisLevelList = rewardLevelMap.get(wait.getLevel());
  790. if (thisLevelList == null) {
  791. return;
  792. }
  793. UserDistributeSubRewards thisLevel = thisLevelList.get(0);
  794. Integer months = thisLevel.getMonths();
  795. BigDecimal subOrderMoney = Optional.ofNullable(orderDonMapper.selectSubChannelOrderMoney(wait.getSubUserId(), subRelate.getCreatedTime(), DateUtil.offsetMonth(subRelate.getCreatedTime(), months))).orElse(BigDecimal.ZERO);
  796. if (subOrderMoney.compareTo(thisLevel.getTargetAmount()) < 0) {
  797. subWaitingMapper.update(null, Wrappers.lambdaUpdate(UserDistributeSubWaiting.class)
  798. .set(UserDistributeSubWaiting::getSendStatus, UserDistributeSubWaiting.Status.close)
  799. .eq(UserDistributeSubWaiting::getSendStatus, UserDistributeSubWaiting.Status.waiting)
  800. .eq(UserDistributeSubWaiting::getId, wait.getId()));
  801. }
  802. });
  803. }
  804. }
  805. }
  806. }
  807. /**
  808. * 退款 分销提成积分扣除
  809. */
  810. public void deductDsPoints(OrderDon orderDon) {
  811. if (orderDon.getIsDistribute()) {
  812. DistributeWaitingSendPoints distributeWaitingSendPoints = distributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(DistributeWaitingSendPoints.class).eq(DistributeWaitingSendPoints::getOrderId, orderDon.getId()).last("limit 1"));
  813. if (distributeWaitingSendPoints != null) {
  814. BigDecimal money = orderDon.getMoney();
  815. BigDecimal refundMoney = orderDon.getRefundMoney();
  816. //已发送 发送中 部分 全额退款
  817. DistributeWaitingSendPoints.Status sendStatus = distributeWaitingSendPoints.getSendStatus();
  818. BigDecimal points = distributeWaitingSendPoints.getPoints();
  819. if (sendStatus == DistributeWaitingSendPoints.Status.waiting) {
  820. //实物设备退款就清0
  821. if (refundMoney.compareTo(money) == 0 || orderDon.getGoodsId() == 15) {
  822. //待发送状态 全额退款
  823. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  824. distributeWaitingSendPoints.setRefundPoints(points);
  825. distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
  826. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  827. return;
  828. }
  829. Integer thisGoodsRate = distributeWaitingSendPoints.getRate();
  830. if (thisGoodsRate == null || thisGoodsRate == 0) {
  831. thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
  832. }
  833. if (thisGoodsRate > 0) {
  834. BigDecimal needSubPoints = refundMoney.multiply(BigDecimal.valueOf(thisGoodsRate).divide(BigDecimal.valueOf(100))).multiply(BigDecimal.valueOf(10));
  835. if (needSubPoints.compareTo(points) > 0) {
  836. //全扣除
  837. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  838. needSubPoints = points;
  839. }
  840. distributeWaitingSendPoints.setRefundPoints(needSubPoints);
  841. //剩余积分
  842. BigDecimal remainPoints = points.subtract(needSubPoints);
  843. distributeWaitingSendPoints.setPoints(remainPoints);
  844. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  845. }
  846. } else if (sendStatus == DistributeWaitingSendPoints.Status.success) {
  847. //已发送的提成 部分退款 全额退款 需要扣除用户积分
  848. //扣除固定推广者积分
  849. //实物设备退款就清0
  850. if (refundMoney.compareTo(money) == 0 || orderDon.getGoodsId() == 15) {
  851. userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), points);
  852. distributeWaitingSendPoints.setRefundPoints(points);
  853. distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
  854. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  855. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  856. return;
  857. }
  858. Integer thisGoodsRate = distributeWaitingSendPoints.getRate();
  859. if (thisGoodsRate == null || thisGoodsRate == 0) {
  860. thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
  861. }
  862. if (thisGoodsRate > 0) {
  863. BigDecimal needSubPoints = refundMoney.multiply(BigDecimal.valueOf(thisGoodsRate).divide(BigDecimal.valueOf(100))).multiply(BigDecimal.valueOf(10));
  864. if (needSubPoints.compareTo(points) > 0) {
  865. //全扣除
  866. distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
  867. needSubPoints = points;
  868. }
  869. userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), needSubPoints);
  870. //部分退款
  871. distributeWaitingSendPoints.setRefundPoints(needSubPoints);
  872. distributeWaitingSendPoints.setPoints(points.subtract(needSubPoints));
  873. distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
  874. }
  875. }
  876. }
  877. }
  878. }
  879. @Override
  880. public void refundPriceDiffer(OrderRefundReq orderRefundReq) throws Exception {
  881. Long orderId = orderRefundReq.getOrderId();
  882. OrderDon orderDon = orderDonMapper.selectById(orderId);
  883. if (orderDon == null) {
  884. throw BusinessRuntimeException.getInstance("订单不存在");
  885. }
  886. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  887. throw BusinessRuntimeException.getInstance("该订单是0元订单,无法补差价");
  888. }
  889. if (Constant.noOrderAllStatus.contains(orderDon.getStatus().name())) {
  890. throw BusinessRuntimeException.getInstance("订单不是已支付状态");
  891. }
  892. //默认补差价余额
  893. String refundType = Optional.ofNullable(orderRefundReq.getRefundType()).orElse("balance");
  894. BigDecimal refundMoney = orderRefundReq.getRefundMoney();
  895. BigDecimal orderRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  896. BigDecimal orderDonRefundBalance = Optional.ofNullable(orderDon.getRefundBalance()).orElse(BigDecimal.ZERO);
  897. if (refundMoney.add(orderRefundMoney).add(orderDonRefundBalance).compareTo(orderDon.getRealMoney()) >= 0) {
  898. throw BusinessRuntimeException.getInstance("补差价已达到该订单付款金额");
  899. }
  900. GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
  901. GoodsDonSku sku = null;
  902. if (orderDon.getSkuId() != null) {
  903. sku = skuMapper.selectById(orderDon.getSkuId());
  904. }
  905. orderDon.setRefundDesc("补差价");
  906. String outNo = StrUtil.EMPTY;
  907. if ("money".equals(refundType)) {
  908. if (refundMoney == null || refundMoney.compareTo(BigDecimal.ZERO) <= 0) {
  909. throw BusinessRuntimeException.getInstance("请输入正确的差价金额");
  910. }
  911. if (refundMoney.compareTo(orderDon.getMoney()) >= 0) {
  912. throw BusinessRuntimeException.getInstance("补差价金额应不大于订单金额");
  913. }
  914. //退款
  915. outNo = orderRefundService.centerRefund(orderRefundReq, orderDon);
  916. orderDon.setRefundMoney(orderRefundMoney.add(refundMoney));
  917. orderDonMapper.updateById(orderDon);
  918. //补差价金额 扣除对应分销提成金额
  919. orderDon.setRefundMoney(refundMoney);
  920. deductDsPoints(orderDon);
  921. //店铺分销提成金额扣除
  922. yhShopDistributeService.deductDsMoney(orderDon);
  923. } else {
  924. BigDecimal refundBalance = refundMoney;
  925. if (refundBalance == null || refundBalance.compareTo(BigDecimal.ZERO) <= 0 || refundBalance.compareTo(orderDon.getMoney()) > 0) {
  926. throw BusinessRuntimeException.getInstance("请输入正确的差价金额");
  927. }
  928. userBenefitsService.addUserBalance(orderDon.getUserId(), refundBalance, UserBalanceSourceRecord.Source.price_differ, orderDon.getYhsId(), orderDon.getId(), goodsDon.getTitle() + UserBalanceSourceRecord.Source.price_differ.getDesc(), true);
  929. orderDon.setRefundBalance(orderDonRefundBalance.add(refundBalance));
  930. orderDonMapper.updateById(orderDon);
  931. }
  932. orderRefundService.refundRecord(orderDon, refundMoney, orderRefundReq.getOperator(), goodsDon, sku, outNo, refundType, null);
  933. }
  934. @Override
  935. @Transactional(rollbackFor = Throwable.class)
  936. public void clearBalanceToRefundMoney(OrderBalanceRefundReq refundReq) throws Exception {
  937. Long refundOrderId = refundReq.getRefundOrderId();
  938. BigDecimal refundMoney = refundReq.getRefundMoney();
  939. RefundOrderDon refundOrderDon = refundOrderDonMapper.selectById(refundOrderId);
  940. if (!"balance".equals(refundOrderDon.getRefundMethod())) {
  941. throw BusinessRuntimeException.getInstance("该记录不是余额退款类型");
  942. }
  943. Long orderId = refundOrderDon.getOrderId();
  944. OrderDon orderDon = orderDonMapper.selectById(orderId);
  945. if (orderDon.getMoney().compareTo(BigDecimal.ZERO) == 0) {
  946. throw BusinessRuntimeException.getInstance("该记录对应的订单无实际支付金额");
  947. }
  948. if (refundOrderDon.getIsClearBalance()) {
  949. throw BusinessRuntimeException.getInstance("该笔退款余额记录已退款");
  950. }
  951. BigDecimal refundFee = refundOrderDon.getRefundFee();
  952. //默认退全部余额
  953. if (refundMoney != null) {
  954. refundFee = refundMoney;
  955. }
  956. BigDecimal money = orderDon.getMoney();
  957. //若退款余额 大于退款金额 将退款余额至为 退款金额
  958. if (refundFee.compareTo(money) > 0) {
  959. refundFee = money;
  960. }
  961. User user = userMapper.selectById(orderDon.getUserId());
  962. if (user.getBalance().compareTo(refundFee) < 0) {
  963. throw BusinessRuntimeException.getInstance("用户余额不足,无法扣除对应退款余额");
  964. }
  965. int update = userMapper.update(null, Wrappers.lambdaUpdate(User.class)
  966. .set(User::getBalance, user.getBalance().subtract(refundFee))
  967. .eq(User::getId, user.getId())
  968. .eq(User::getBalance, user.getBalance()));
  969. if (update == 0) {
  970. throw BusinessRuntimeException.getInstance("扣除用户退款余额失败,请重试...");
  971. }
  972. OrderRefundReq orderRefundReq = new OrderRefundReq();
  973. orderRefundReq.setOrderId(orderId);
  974. orderRefundReq.setRefundMoney(refundFee);
  975. orderRefundReq.setRefundType("money");
  976. String outNo = orderRefundService.centerRefund(orderRefundReq, orderDon);
  977. orderDon.setRefundBalance(orderDon.getRefundBalance().subtract(refundFee));
  978. BigDecimal orderRefundMoney = Optional.ofNullable(orderDon.getRefundMoney()).orElse(BigDecimal.ZERO);
  979. orderDon.setRefundMoney(orderRefundMoney.add(refundFee));
  980. orderDonMapper.updateById(orderDon);
  981. refundOrderDon.setOutRefundNo(outNo);
  982. refundOrderDon.setIsClearBalance(true);
  983. refundOrderDonMapper.updateById(refundOrderDon);
  984. }
  985. /**
  986. * 寻找该车队空余车位
  987. */
  988. public GroupsRelation getRelationThisTrips(Long userId, Long groupsId, Integer retryNum) {
  989. //寻找快满编车队进行占座
  990. GroupsRelation relation = relationMapper.selectRandomOneRelationByGroupsId(groupsId);
  991. if (relation == null) {
  992. throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  993. }
  994. Long relationId = relation.getId();
  995. if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
  996. if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  997. retryNum++;
  998. return getRelationThisTrips(userId, groupsId, retryNum);
  999. }
  1000. int count = groupsMapper.decrAvailableNum(relation.getGroupsId());
  1001. if (count == 0) {
  1002. log.error("车位异常 groupId:{}", groupsId);
  1003. groupsMapper.updateAvailableNum(groupsId);
  1004. throw new BusinessRuntimeException("车位异常");
  1005. }
  1006. return relation;
  1007. }
  1008. private GroupsRelation getChatGPTOutsideRelation(Long userId, Long groupsId, Integer relationNum, Integer retryNum) {
  1009. //寻找快满编车队额外座位
  1010. GroupsRelation relation = relationMapper.selectOutsideRelationByGroupsId(groupsId, relationNum);
  1011. if (relation == null) {
  1012. relation = new GroupsRelation();
  1013. relation.setStatus(GroupsRelation.Status.outside);
  1014. relation.setUserId(userId);
  1015. relation.setGroupsId(groupsId);
  1016. GroupsRelation maxNumRelation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getGroupsId, groupsId).orderByDesc(GroupsRelation::getNum).last("limit 1"));
  1017. relation.setNum(maxNumRelation.getNum() + 1);
  1018. relationMapper.insert(relation);
  1019. return relation;
  1020. }
  1021. Long relationId = relation.getId();
  1022. if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
  1023. if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
  1024. retryNum++;
  1025. return getChatGPTOutsideRelation(userId, groupsId, relationNum, retryNum);
  1026. }
  1027. return relation;
  1028. }
  1029. /**
  1030. * 删除gptUser
  1031. */
  1032. public void delGptUser(Long goodsId, Long relationId) {
  1033. //gpt镜像
  1034. if (goodsId != null && goodsId == 18) {
  1035. Integer selectCount = chatgptUserMapper.selectCount(Wrappers.lambdaQuery(ChatgptUser.class)
  1036. .eq(ChatgptUser::getRelationId, relationId));
  1037. if (selectCount > 0) {
  1038. chatgptUserMapper.delete(Wrappers.lambdaQuery(ChatgptUser.class)
  1039. .eq(ChatgptUser::getRelationId, relationId));
  1040. }
  1041. }
  1042. }
  1043. }