| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666 |
- package com.cyksj.service.mange.impl;
- import cn.hutool.core.date.DateField;
- import cn.hutool.core.date.DateTime;
- import cn.hutool.core.date.DateUtil;
- import cn.hutool.core.lang.Assert;
- import cn.hutool.core.util.StrUtil;
- import com.alipay.api.AlipayClient;
- import com.alipay.api.domain.AlipayTradeRefundModel;
- import com.alipay.api.request.AlipayTradeRefundRequest;
- import com.alipay.api.response.AlipayTradeRefundResponse;
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
- import com.cyksj.common.constant.Constant;
- import com.cyksj.common.exception.BusinessRuntimeException;
- import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
- import com.cyksj.common.util.*;
- import com.cyksj.config.WeChatConfig;
- import com.cyksj.config.zfb.AliPayClientFactory;
- import com.cyksj.dto.RedisKey;
- import com.cyksj.mapper.*;
- import com.cyksj.mapper.channel.ShopConfigMapper;
- import com.cyksj.mapper.manage.cms.CmsUserMapper;
- import com.cyksj.mapper.manage.distribute.DistributeWaitingSendPointsMapper;
- import com.cyksj.mapper.manage.distribute.UserDistributeMapper;
- import com.cyksj.mapper.stock.GoodsSkuStockRelateMapper;
- import com.cyksj.model.entity.*;
- import com.cyksj.model.excel.ExcelOrderDonInfo;
- import com.cyksj.model.manage.request.ReqSetLogisticsPost;
- import com.cyksj.model.request.ChangeRelationReq;
- import com.cyksj.model.request.ClickOutReq;
- import com.cyksj.model.request.OrderRefundReq;
- import com.cyksj.redis.RedisService;
- import com.cyksj.service.coupon.CouponFontService;
- import com.cyksj.service.distribute.equipment.EquipmentDistributeService;
- import com.cyksj.service.mange.CmsOrderDonService;
- import com.cyksj.service.mange.stock.GoodsDonStockService;
- import com.cyksj.service.market.MarketFrontService;
- import com.cyksj.service.order.OrderCommonService;
- import com.cyksj.service.order.UserRealOrderBenefitsService;
- import com.cyksj.service.relation.GroupRelationClearService;
- import com.cyksj.service.template.TemplateCommonService;
- import com.cyksj.service.user.UserBenefitsService;
- import com.cyksj.service.wechat.WeChatService;
- import lombok.RequiredArgsConstructor;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.dao.DuplicateKeyException;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import java.math.BigDecimal;
- import java.math.RoundingMode;
- import java.util.Date;
- import java.util.List;
- import java.util.Map;
- import java.util.Optional;
- /**
- * @author chan
- * @date 2021/10/25 下午10:14
- */
- @Service
- @Slf4j
- @RequiredArgsConstructor
- public class CmsOrderDonServiceImpl extends ServiceImpl<OrderDonMapper,OrderDon> implements CmsOrderDonService {
- private final OrderDonTransportMapper transportMapper;
- private final OrderDonWaybillMapper orderDonWaybillMapper;
- private final GoodsSkuStockRelateMapper skuStockRelateMapper;
- private final GoodsDonStockService goodsDonStockService;
- private final TemplateCommonService templateCommonService;
- private final GoodsDonSkuMapper goodsDonSkuMapper;
- private final UserRealOrderBenefitsService userRealOrderBenefitsService;
- private final UserRelationKickOutRecordMapper kickOutRecordMapper;
- private final CmsUserMapper cmsUserMapper;
- private final OrderCommonService orderCommonService;
- private final GoodsDonMapper goodsDonMapper;
- private final RedisService redisService;
- private final UserBenefitsService userBenefitsService;
- private final DistributeWaitingSendPointsMapper distributeWaitingSendPointsMapper;
- private final RefundOrderDonMapper refundOrderDonMapper;
- private final UserDistributeMapper userDistributeMapper;
- private final OrderDonMapper orderDonMapper;
- private final MarketFrontService marketFrontService;
- private final EquipmentDistributeService equipmentDistributeService;
- private final CouponFontService couponFontService;
- private final WeChatService weChatService;
- private final WeChatConfig weChatConfig;
- private final ShopConfigMapper shopConfigMapper;
- private final GroupRelationClearService relationClearService;
- private final GroupsRelationMapper relationMapper;
- private final GroupsMapper groupsMapper;
- private final GoodsDonSkuMapper skuMapper;
- private static final GlobalThreadPoolTaskExecutor TASK_POOL = GlobalThreadPoolTaskExecutor.getInstance();
- @Override
- public List<ExcelOrderDonInfo> exportOrderInfo(Long promotionId, String start, String end) {
- return this.getBaseMapper().exportOrderInfo(promotionId,start,end);
- }
- @Override
- public OrderDonTransport getTransport(Long orderId) {
- return transportMapper.selectOne(Wrappers.lambdaQuery(OrderDonTransport.class).eq(OrderDonTransport::getOrderId, orderId));
- }
- @Transactional(rollbackFor = Throwable.class)
- @Override
- public OrderDonWaybill setWaybill(ReqSetLogisticsPost reqSetLogisticsPost) {
- OrderDonWaybill orderDonWaybill = Optional.ofNullable(orderDonWaybillMapper.selectOne(Wrappers.lambdaQuery(OrderDonWaybill.class).eq(OrderDonWaybill::getOrderId, reqSetLogisticsPost.getOrderId()))).orElse(new OrderDonWaybill());
- orderDonWaybill.setCodeCn(reqSetLogisticsPost.getCodeCn());
- orderDonWaybill.setTrackingNumber(reqSetLogisticsPost.getTrackingNumber());
- orderDonWaybill.setOrderId(reqSetLogisticsPost.getOrderId());
- orderDonWaybill.setRemark(reqSetLogisticsPost.getRemark());
- OrderDon orderDon = getById(orderDonWaybill.getOrderId());
- if(orderDonWaybill.getId() == null){
- try {
- orderDonWaybillMapper.insert(orderDonWaybill);
- } catch (DuplicateKeyException e) {
- return orderDonWaybill;
- }
- orderDon.setStatus(OrderDon.Status.transport);
- updateById(orderDon);
- //发放实物购买权益
- Boolean isReceivedAll = true;
- GoodsDonSku sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
- if (sku != null) {
- if (sku.getIsBenefits()) {
- if (StrUtil.isNotEmpty(sku.getBenefitsList())) {
- try {
- List<GoodsDonSku> goodsDonSkus = Jsons.parseList(sku.getBenefitsList(), GoodsDonSku.class);
- //自购实物 获取权益
- isReceivedAll = userRealOrderBenefitsService.getPayRealGoodsBenefits(orderDon.getUserId(), orderDon.getId(), goodsDonSkus);
- } catch (Exception e) {
- }
- }
- }
- }
- final Boolean flag = isReceivedAll;
- //库存扣减逻辑
- List<GoodsSkuStockRelate> relateList = skuStockRelateMapper.selectList(Wrappers.lambdaQuery(GoodsSkuStockRelate.class).eq(GoodsSkuStockRelate::getSkuId,orderDon.getSkuId()));
- if(!relateList.isEmpty()){
- relateList.forEach((relate)->{
- goodsDonStockService.upStockRelate(relate.getStockId(),orderDon.getId(),"transport");
- });
- }
- //发送微信模板消息
- TASK_POOL.execute(()->{
- try {
- log.info("发送发货通知至{}用户", orderDon.getUserId());
- templateCommonService.sendTransportMsgNotify(orderDon, reqSetLogisticsPost, flag);
- } catch (Exception e) {
- log.error("发送发货通知至{}用户失败:{}", orderDon.getUserId(), e);
- }
- });
- }else {
- if (orderDon.getStatus() == OrderDon.Status.hasPayment) {
- orderDon.setStatus(OrderDon.Status.transport);
- updateById(orderDon);
- }
- orderDonWaybillMapper.updateById(orderDonWaybill);
- }
- return orderDonWaybill;
- }
- @Override
- public void kickOutRelationId(long adminId, ClickOutReq req) {
- Long orderId = req.getOrderId();
- OrderDon orderDon = getById(orderId);
- if (orderDon != null && !orderDon.getIsKickOut()) {
- try {
- UserRelationKickOutRecord kickOutRecord = new UserRelationKickOutRecord();
- kickOutRecord.setUserId(orderDon.getUserId());
- kickOutRecord.setRelationId(orderDon.getRelationId());
- kickOutRecord.setGoodsId(orderDon.getGoodsId());
- kickOutRecord.setSkuId(orderDon.getSkuId());
- kickOutRecord.setReason(req.getReason());
- kickOutRecord.setImg(req.getImg());
- kickOutRecord.setRemark(req.getRemark());
- kickOutRecord.setOrderId(orderDon.getId());
- kickOutRecord.setOrderNo(orderDon.getOrderNo());
- Optional.ofNullable(cmsUserMapper.selectById(adminId)).ifPresent(cmsUser -> kickOutRecord.setOperator(cmsUser.getNickname()));
- kickOutRecordMapper.insert(kickOutRecord);
- orderDon.setIsKickOut(true);
- updateById(orderDon);
- GoodsDon goodsDon = goodsDonMapper.selectById(orderDon.getGoodsId());
- GoodsDonSku goodsDonSku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
- //清除车票
- orderCommonService.clearUnrealGoodsDetail(orderDon, goodsDon.getType(), goodsDonSku.getMonths());
- } catch (DuplicateKeyException e) {
- }
- }
- }
- @Override
- @Transactional(rollbackFor = Throwable.class)
- public void unifiedRefund(OrderRefundReq refundReq) throws Exception {
- OrderDon orderDon = orderDonMapper.selectById(refundReq.getOrderId());
- GoodsDonSku sku = goodsDonSkuMapper.selectById(orderDon.getSkuId());
- GoodsDon goodsDon = goodsDonMapper.selectById(sku.getGoodsId());
- if (StrUtil.isEmpty(refundReq.getRefundType())) {
- refundReq.setRefundType("money");
- }
- String refundType = refundReq.getRefundType();
- //校验订单是否符合退款
- checkOrderRefund(orderDon, goodsDon, sku, 2, refundReq);
- OrderDon.Type type = orderDon.getType();
- String outNo = StrUtil.EMPTY;
- if (type == OrderDon.Type.WeChat && !refundType.equals(OrderDon.Type.BALANCE.getType())) {
- outNo = wxRefund(refundReq, orderDon);
- }
- if (type == OrderDon.Type.ALI_PAY && !refundType.equals(OrderDon.Type.BALANCE.getType())) {
- outNo = zfbRefund(refundReq, orderDon);
- }
- orderDon.setRefundDesc(refundReq.getRefundDesc());
- //记录退款信息
- commonRefund(orderDon, goodsDon, sku, outNo, refundType);
- //修改订单状态
- orderDon.setStatus(OrderDon.Status.refund);
- orderDonMapper.updateById(orderDon);
- }
- public String wxRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
- if (orderDon.getMoney().compareTo(BigDecimal.ZERO) <=0){
- return StrUtil.EMPTY;
- }
- long time = System.currentTimeMillis();
- //退款订单号
- String outRefundNo = Codec.DoDigest.custom()
- .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
- .setStringData(time + String.valueOf(orderDon.getId()))
- .toHexString();
- weChatService.refundWxOrder(weChatConfig.getAppid(),
- Optional.ofNullable(orderDon.getShopId()).orElse(ShopConfig.WX_DEFAULT_APP_ID),
- orderDon.getTransactionId(),
- outRefundNo,
- orderDon.getMoney(),
- refundReq.getRefundMoney(),
- weChatConfig.getDomain() + "manage/order/wx/refund/notify");
- //记录退款信息
- return outRefundNo;
- }
- @Override
- public void wxRefundNotify(Map<String, String> map) throws Exception {
- // 对退款数据 解密
- String md5Key = Codec.DoDigest.custom().setAlgorithm(Codec.DoDigest.Algorithm.MD5).setStringData(shopConfigMapper.getByAppId(map.get("mch_id")).getSecret()).toHexString();
- String reqInfoXml = Codec.DoCipher.custom().setAlgorithm(Codec.DoCipher.Trans.AES_ECB_PKCS7Padding).setBase64Data(map.get("req_info")).setStringKey(md5Key).ofDecrypt().toText();
- log.info("=== 退款数据解密: \n {}", reqInfoXml);
- Map<String, String> reqInfoMap = Xmls.toMap(reqInfoXml);
- // 退款失败
- if (StrUtil.equals("CHANGE", reqInfoMap.get("refund_status"))) {
- throw BusinessRuntimeException.getInstance("退款异常.");
- } else if (StrUtil.equals("REFUNDCLOSE", reqInfoMap.get("refund_status"))) {
- throw BusinessRuntimeException.getInstance("退款关闭.");
- }
- /* 此处处理业务逻辑 */
- String outRefundNo = reqInfoMap.get("out_refund_no");
- String transactionId = reqInfoMap.get("transaction_id");
- String refundFee = reqInfoMap.get("refund_fee");
- OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getTransactionId, transactionId).last("limit 1"));
- if (orderDon == null) {
- log.error("退款回调,transactionId:{}订单不存在", transactionId);
- return;
- }
- log.info("微信退款: 退款单号[{}] 退款成功.", outRefundNo);
- }
- @Override
- @Transactional(rollbackFor = Throwable.class)
- public void changeRelation(ChangeRelationReq req) {
- Long relationId = req.getRelationId();
- Long groupId = req.getGroupsId();
- UserTicketClearedRecord.Source source = req.getSource();
- if (source == null) source = UserTicketClearedRecord.Source.change_ticket;
- GroupsRelation relation = relationMapper.selectById(relationId);
- Assert.notNull(relation, "车票已不存在");
- Long userId = relation.getUserId();
- OrderDon orderDon = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
- .eq(OrderDon::getUserId, userId)
- .eq(OrderDon::getRelationId, relationId)
- .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
- .last("limit 1"));
- Assert.notNull(orderDon, "订单不存在");
- //获取新车队
- LambdaQueryWrapper<GroupsTrips> queryWrapper = Wrappers.lambdaQuery(GroupsTrips.class)
- .eq(GroupsTrips::getSkuId, orderDon.getSkuId())
- .eq(GroupsTrips::getId, groupId)
- .ne(GroupsTrips::getId, relation.getGroupsId())
- .ne(GroupsTrips::getStatus, GroupsTrips.Status.down)
- .last("limit 1");
- GroupsTrips groups = groupsMapper.selectOne(queryWrapper);
- if (groups == null) throw BusinessRuntimeException.getInstance("车队不存在或已下架");
- if (orderDon.getGoodsId() != 18 && groups.getAvailableNum() <= 0) {
- throw BusinessRuntimeException.getInstance("该新车位人员已满");
- }
- //获取新车队车位
- GroupsRelation newRelation;
- if (orderDon.getGoodsId() == 18 && groups.getAvailableNum() == 0) {
- //GPT车队 额外增加车位 并不让上车
- newRelation = getChatGPTOutsideRelation(orderDon.getUserId(), groupId, 1);
- } else {
- newRelation = getRelationThisTrips(orderDon.getUserId(), groupId, 1);
- }
- newRelation.setUserId(relation.getUserId());
- newRelation.setStartTime(relation.getStartTime());
- newRelation.setExpiryTime(relation.getExpiryTime());
- newRelation.setCustomerService(relation.getCustomerService());
- if (newRelation.getStatus() != GroupsRelation.Status.outside) {
- newRelation.setStatus(GroupsRelation.Status.validity);
- }
- //清除原先车票
- relation.setNewRelationId(newRelation.getId());
- relationClearService.clearTicket(relation, source);
- if ((newRelation.getStartTime() == null || newRelation.getExpiryTime() == null)) {
- List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.hasPayment));
- if (groups.getStatus() == GroupsTrips.Status.waiting) {
- orderDonList.forEach(hasPaymentOrder -> {
- hasPaymentOrder.setRelationId(newRelation.getId());
- orderDonMapper.updateById(hasPaymentOrder);
- });
- relationMapper.updateById(newRelation);
- return;
- }
- orderDonList.forEach((hasPaymentOrder) -> {
- //如果续费增加时间,如果首次则设置当前时间为初始时间
- Date expiryTime = Optional.ofNullable(newRelation.getExpiryTime()).orElse(new Date());
- GoodsDonSku donSku = skuMapper.selectById(hasPaymentOrder.getSkuId());
- Date newDate = DateUtil.offset(expiryTime, DateField.MONTH, donSku.getMonths() * hasPaymentOrder.getNum());
- newRelation.setExpiryTime(newDate);
- newRelation.setStartTime(newRelation.getStartTime() == null ? new Date() : null);
- relationMapper.updateById(newRelation);
- hasPaymentOrder.setStatus(OrderDon.Status.complete);
- hasPaymentOrder.setRelationId(newRelation.getId());
- orderDonMapper.updateById(hasPaymentOrder);
- });
- return;
- }
- List<OrderDon> orderDonList = orderDonMapper.selectList(Wrappers.lambdaQuery(OrderDon.class).eq(OrderDon::getUserId, userId).eq(OrderDon::getRelationId, relationId).eq(OrderDon::getStatus, OrderDon.Status.complete));
- orderDonList.forEach(completeOrder->{
- completeOrder.setRelationId(newRelation.getId());
- orderDonMapper.updateById(completeOrder);
- });
- redisService.del(RedisKey.GROUPS_RELATION_NUM_KEY + newRelation.getId());
- relationMapper.updateById(newRelation);
- }
- public String zfbRefund(OrderRefundReq refundReq, OrderDon orderDon) throws Exception {
- if (orderDon.getMoney().compareTo(BigDecimal.ZERO) <=0){
- return StrUtil.EMPTY;
- }
- AlipayTradeRefundResponse response;
- //支付宝退款
- AlipayClient alipayClient = AliPayClientFactory.getAlipayClient(Optional.ofNullable(orderDon.getShopId()).orElse(ShopConfig.ZFB_DEFAULT_APP_ID));
- AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
- AlipayTradeRefundModel model = new AlipayTradeRefundModel();
- //支付宝交易号
- model.setTradeNo(orderDon.getTransactionId());
- model.setRefundAmount(refundReq.getRefundMoney().divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_EVEN).toString());
- model.setQueryOptions(List.of("gmt_refund_pay"));
- long time = System.currentTimeMillis();
- //退款订单号
- String outRefundNo = Codec.DoDigest.custom()
- .setAlgorithm(Codec.DoDigest.Algorithm.MD5)
- .setStringData(time + String.valueOf(orderDon.getId()))
- .toHexString();
- //退款请求号
- model.setOutRequestNo(outRefundNo);
- request.setBizModel(model);
- String shopId = orderDon.getShopId();
- ShopConfig shopConfig = shopConfigMapper.selectOne(Wrappers.lambdaQuery(ShopConfig.class).eq(ShopConfig::getAppId, orderDon.getShopId()));
- if (shopId != null && shopConfig != null && shopConfig.getIsCert()) {
- response = alipayClient.certificateExecute(request);
- } else {
- response = alipayClient.execute(request);
- }
- if (!response.isSuccess()) throw BusinessRuntimeException.getInstance("退款失败,e:{0}", response.getSubMsg());
- // AliPayRefundRep aliPayRefundRep = Jsons.parseObject(response.getBody(), AliPayRefundRep.class);
- // AliPayRefundRep.AlipayTradeRefundResponse res = aliPayRefundRep.getResponse();
- // orderDon.setRefundMoney(res.getRefundFee().multiply(BigDecimal.valueOf(100)));
- return outRefundNo;
- }
- /**
- * 校验订单是否符合退款操作
- */
- private void checkOrderRefund(OrderDon orderDon, GoodsDon goodsDon, GoodsDonSku sku, Integer orderPayType, OrderRefundReq refundReq) {
- if (orderDon == null) {
- throw BusinessRuntimeException.getInstance("订单不存在");
- }
- String refundType = refundReq.getRefundType();
- if (orderDon.getType() == OrderDon.Type.BALANCE && !OrderDon.Type.BALANCE.getType().equals(refundType)) {
- throw BusinessRuntimeException.getInstance("余额支付的订单不支持金额退款");
- }
- if (orderDon.getType() != OrderDon.Type.BALANCE && orderDon.getType() != OrderDon.Type.WeChat && orderPayType == 1) {
- throw BusinessRuntimeException.getInstance("该订单不是微信支付的订单");
- }
- if (orderDon.getType() != OrderDon.Type.BALANCE && orderDon.getType() != OrderDon.Type.ALI_PAY && orderPayType == 2) {
- throw BusinessRuntimeException.getInstance("该订单不是支付宝支付的订单");
- }
- if (OrderDon.Status.refund == orderDon.getStatus()) {
- throw BusinessRuntimeException.getInstance("该订单已退款");
- }
- if (OrderDon.Status.noPayment == orderDon.getStatus() || OrderDon.Status.close == orderDon.getStatus()) {
- throw BusinessRuntimeException.getInstance("订单{0}状态不支持退款", orderDon.getStatus());
- }
- if (goodsDon.getType() == 1) {
- //虚拟原订单是否已过期
- Integer months = sku.getMonths();
- Integer num = orderDon.getNum();
- DateTime now = DateTime.now();
- DateTime endTime = DateUtil.offsetMonth(orderDon.getCreatedTime(), months * num);
- if (now.isAfter(endTime)) {
- throw BusinessRuntimeException.getInstance("该订单车票已过期");
- }
- if (orderDon.getOrderType() == 1) {
- //是否有其他付款订单是否过期
- OrderDon otherOrder = orderDonMapper.selectOne(Wrappers.lambdaQuery(OrderDon.class)
- .eq(OrderDon::getRelationId, orderDon.getRelationId())
- .eq(OrderDon::getUserId, orderDon.getUserId())
- .ne(OrderDon::getId, orderDon.getId())
- .notIn(OrderDon::getStatus, Constant.noOrderAllStatus)
- .eq(OrderDon::getOrderType, 2)
- .orderByDesc(OrderDon::getId)
- .last("limit 1"));
- if (otherOrder != null) {
- throw BusinessRuntimeException.getInstance("该笔订单存在续费订单,请先退掉续费订单");
- }
- }
- }
- BigDecimal refundMoney = refundReq.getRefundMoney();
- BigDecimal money = orderDon.getMoney();
- //余额退款
- if (OrderDon.Type.BALANCE.getType().equals(refundType)) {
- BigDecimal balance = orderDon.getBalance();
- if (OrderDon.Type.BALANCE == orderDon.getType() && refundMoney.compareTo(balance) > 0) {
- throw BusinessRuntimeException.getInstance("退款余额大于订单支付余额");
- }
- if (OrderDon.Type.BALANCE != orderDon.getType() && refundMoney.compareTo(money) > 0) {
- throw BusinessRuntimeException.getInstance("退款余额大于订单支付金额");
- }
- orderDon.setRefundBalance(refundMoney);
- orderDon.setRefundMoney(BigDecimal.ZERO);
- } else {
- //退金额
- if (refundMoney.compareTo(money) > 0) {
- throw BusinessRuntimeException.getInstance("退款金额大于订单支付金额");
- }
- orderDon.setRefundMoney(refundMoney);
- }
- if (!redisService.setNx(String.format("%s", refundReq.getOrderId()), refundReq.getOrderId(), 10l)) {
- throw BusinessRuntimeException.getInstance("请勿重复点击,正在退款中..");
- }
- }
- /**
- * 退款后 处理关联
- */
- public void commonRefund(OrderDon orderDon, GoodsDon goodsDon, GoodsDonSku sku, String outNo, String refundType) {
- TASK_POOL.execute(() -> {
- refundRecord(orderDon, goodsDon, sku, outNo, refundType);
- //退款一次
- goodsDonStockService.upStockRelate(null, orderDon.getId(), "refund");
- try {
- //虚物订单退款,清出车队,车票变为已过期
- orderCommonService.clearUnrealGoodsDetail(orderDon, goodsDon.getType(), sku.getMonths());
- } catch (Exception e) {
- log.error("清除车票错误:{}", StringUtil.getErrorText(e));
- }
- //若存在优惠券使用,退还优惠券
- if (orderDon.getCouponUserId() != 0) {
- couponFontService.updateOrderDonCouponStatus(orderDon);
- }
- //若存在余额支付,退还余额
- if (orderDon.getBalance().compareTo(BigDecimal.ZERO) > 0) {
- userBenefitsService.addUserBalance(orderDon.getUserId(), orderDon.getBalance());
- }
- try {
- marketFrontService.subSpecificChanceNum(orderDon.getUserId(), orderDon.getId(), orderDon.getGoodsId(), orderDon.getUpdateTime());
- if (goodsDon.getType() == 2) {
- equipmentDistributeService.subDistributeBenefitsChance(orderDon.getUserId(), orderDon.getId());
- //扣除用户自身实物权益
- userRealOrderBenefitsService.deductUserRealGoodsBenefits(orderDon.getId());
- }
- } catch (Exception e) {
- log.error("wx减少抽奖机会错误,orderId:{},error:{}", orderDon.getId(), e);
- }
- if (OrderDon.Type.BALANCE.getType().equals(refundType)) {
- if (orderDon.getMoney().compareTo(BigDecimal.ZERO) > 0) {
- userBenefitsService.addUserBalance(orderDon.getUserId(), orderDon.getRefundBalance());
- //退款余额时,记录
- userBenefitsService.recordBalanceBySource(orderDon.getUserId(), orderDon.getRefundBalance(), UserBalanceSourceRecord.Source.clear_valid);
- }
- } else {
- //余额退款不需要扣除积分
- //分销提成积分扣除
- deductDsPoints(orderDon);
- }
- });
- }
- /**
- * 退款 分销提成积分扣除
- */
- public void deductDsPoints(OrderDon orderDon) {
- if (orderDon.getIsDistribute()) {
- DistributeWaitingSendPoints distributeWaitingSendPoints = distributeWaitingSendPointsMapper.selectOne(Wrappers.lambdaQuery(DistributeWaitingSendPoints.class).eq(DistributeWaitingSendPoints::getOrderId, orderDon.getId()).last("limit 1"));
- if (distributeWaitingSendPoints != null) {
- BigDecimal money = orderDon.getMoney();
- BigDecimal refundMoney = orderDon.getRefundMoney();
- //已发送 发送中 部分 全额退款
- DistributeWaitingSendPoints.Status sendStatus = distributeWaitingSendPoints.getSendStatus();
- BigDecimal points = distributeWaitingSendPoints.getPoints();
- if (sendStatus == DistributeWaitingSendPoints.Status.waiting) {
- if (refundMoney.compareTo(money) == 0) {
- //待发送状态 全额退款
- distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
- distributeWaitingSendPoints.setRefundPoints(points);
- distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
- distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
- return;
- }
- Integer thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
- if (thisGoodsRate > 0) {
- BigDecimal needSubPoints = refundMoney.multiply(BigDecimal.valueOf(thisGoodsRate).divide(BigDecimal.valueOf(100))).multiply(BigDecimal.valueOf(10));
- distributeWaitingSendPoints.setRefundPoints(needSubPoints);
- //剩余积分
- distributeWaitingSendPoints.setPoints(points.subtract(needSubPoints));
- distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
- }
- } else if (sendStatus == DistributeWaitingSendPoints.Status.success) {
- //已发送的提成 部分退款 全额退款 需要扣除用户积分
- //扣除固定推广者积分
- if (refundMoney.compareTo(money) == 0) {
- userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), points);
- distributeWaitingSendPoints.setRefundPoints(points);
- distributeWaitingSendPoints.setPoints(BigDecimal.ZERO);
- distributeWaitingSendPoints.setSendStatus(DistributeWaitingSendPoints.Status.close);
- distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
- return;
- }
- Integer thisGoodsRate = Optional.ofNullable(userDistributeMapper.getDistributeGoodsRateByUidAndGid(orderDon.getUserId(), orderDon.getGoodsId())).orElse(0);
- if (thisGoodsRate > 0) {
- BigDecimal needSubPoints = refundMoney.multiply(BigDecimal.valueOf(thisGoodsRate).divide(BigDecimal.valueOf(100))).multiply(BigDecimal.valueOf(10));
- userBenefitsService.deductDistributePoints(orderDon.getId(), distributeWaitingSendPoints.getSharedId(), needSubPoints);
- //部分退款
- distributeWaitingSendPoints.setRefundPoints(needSubPoints);
- distributeWaitingSendPoints.setPoints(points.subtract(needSubPoints));
- distributeWaitingSendPointsMapper.updateById(distributeWaitingSendPoints);
- }
- }
- }
- }
- }
- /**
- * 记录退款信息
- */
- private void refundRecord(OrderDon orderDon, GoodsDon goodsDon, GoodsDonSku sku, String outRefundNo, String refundType) {
- RefundOrderDon refund = new RefundOrderDon();
- refund.setOrderId(orderDon.getId());
- refund.setOutRefundNo(outRefundNo);
- refund.setTotalFee(orderDon.getMoney());
- refund.setRefundDesc(orderDon.getRefundDesc());
- //退款金额
- refund.setRefundFee(orderDon.getRefundMoney());
- refund.setUserId(orderDon.getUserId());
- refund.setGoodsId(orderDon.getGoodsId());
- refund.setGoodsTitle(goodsDon == null ? null : goodsDon.getTitle());
- refund.setSkuId(orderDon.getSkuId());
- refund.setSpecVal(sku == null ? null : String.format("%s%s", sku.getSpecVal(), sku.getPrice().divide(BigDecimal.valueOf(100))));
- refund.setRefundMethod(orderDon.getType().name());
- refund.setGoodsType(goodsDon == null ? 0 : goodsDon.getType());
- //退款方式
- if (StrUtil.isNotBlank(refundType) && refundType.equals(OrderDon.Type.BALANCE.getType())) {
- refund.setRefundMethod(refundType);
- refund.setRefundFee(orderDon.getRefundBalance());
- }
- refundOrderDonMapper.insert(refund);
- }
- /**
- * 寻找该车队空余车位
- */
- public GroupsRelation getRelationThisTrips(Long userId, Long groupsId, Integer retryNum) {
- //寻找快满编车队进行占座
- GroupsRelation relation = relationMapper.selectRandomOneRelationByGroupsId(groupsId);
- if (relation == null) {
- throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
- }
- Long relationId = relation.getId();
- if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
- if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
- retryNum++;
- getRelationThisTrips(userId, groupsId, retryNum);
- }
- int count = groupsMapper.decrAvailableNum(relation.getGroupsId());
- if (count == 0) {
- log.error("车位异常 groupId:{}", groupsId);
- groupsMapper.updateAvailableNum(groupsId);
- throw new BusinessRuntimeException("车位异常");
- }
- return relation;
- }
- private GroupsRelation getChatGPTOutsideRelation(Long userId, Long groupsId, Integer retryNum) {
- //寻找快满编车队额外座位
- GroupsRelation relation = relationMapper.selectOutsideRelationByGroupsId(groupsId);
- if (relation == null) {
- relation = new GroupsRelation();
- relation.setStatus(GroupsRelation.Status.outside);
- relation.setUserId(userId);
- relation.setGroupsId(groupsId);
- GroupsRelation maxNumRelation = relationMapper.selectOne(Wrappers.lambdaQuery(GroupsRelation.class).eq(GroupsRelation::getGroupsId, groupsId).orderByDesc(GroupsRelation::getNum).last("limit 1"));
- relation.setNum(maxNumRelation.getNum() + 1);
- relationMapper.insert(relation);
- return relation;
- }
- Long relationId = relation.getId();
- if (!redisService.setNx(RedisKey.GROUPS_RELATION_NUM_KEY + relationId, userId, 60 * 5L)) {
- if (retryNum == 7) throw BusinessRuntimeException.getInstance("该车队人员已满,请选择另一车队");
- retryNum++;
- getChatGPTOutsideRelation(userId, groupsId, retryNum);
- }
- return relation;
- }
- }
|