ANDRU-PC\Andru
2023-09-07 9198b5480be4f109410a3654d6681674920e7633
提交 | 用户 | age
4dc6e5 1 package com.hx.phip.service.order.impl;
Z 2
3 import com.alibaba.fastjson.JSON;
42a0e7 4 import com.alibaba.fastjson.JSONArray;
9d4e6f 5 import com.alibaba.fastjson.JSONObject;
4dc6e5 6 import com.hx.common.service.CommonService;
a2fbbf 7 import com.hx.exception.TipsException;
4dc6e5 8 import com.hx.mybatisTool.SqlSentence;
f13adb 9 import com.hx.phiappt.common.*;
575cd4 10 import com.hx.phiappt.constants.tool.PerformanceInfoTool;
9198b5 11 import com.hx.phiappt.constants.tool.TimerHandleTool;
f23452 12 import com.hx.phiappt.constants.tool.clubEquity.ClubEquityTool;
9d4e6f 13 import com.hx.phiappt.model.*;
edf5ea 14 import com.hx.phiappt.model.activity.ActivityAction;
Z 15 import com.hx.phiappt.model.activity.ActivityRule;
e3b9cc 16 import com.hx.phiappt.model.consume.ConsumeNotify;
e118d7 17 import com.hx.phiappt.model.consume.ConsumePay;
c38ec7 18 import com.hx.phiappt.model.coupon.CouponOrderDiscountLog;
46bedb 19 import com.hx.phiappt.model.order.*;
071df8 20 import com.hx.phiappt.model.performance.PerformanceInfo;
36bc5e 21 import com.hx.phiappt.model.refund.*;
a2fbbf 22 import com.hx.phiappt.model.user.UserCard;
431d07 23 import com.hx.phiappt.model.user.UserProjectItem;
c9e2be 24 import com.hx.phiappt.model.userMoney.UserMoneyUnclaimed;
e3b9cc 25 import com.hx.phiappt.vo.refund.RefundCashItemVo;
C 26 import com.hx.phiappt.vo.refund.RefundCashVo;
f23452 27 import com.hx.phip.config.BotoxClubConfig;
4dc6e5 28 import com.hx.phip.config.CustomParameter;
Z 29 import com.hx.phip.dao.mapper.*;
4df03d 30 import com.hx.phip.service.CreateNoService;
4dc6e5 31 import com.hx.phip.service.PaymentMethodService;
7c75e2 32 import com.hx.phip.service.consume.ConsumeNotifyRefundService;
4dc6e5 33 import com.hx.phip.service.order.OrderRefundService;
Z 34 import com.hx.phip.service.refund.RefundRecordItemService;
35 import com.hx.phip.service.refund.RefundRecordMethodService;
36 import com.hx.phip.service.refund.RefundRecordService;
26ebce 37 import com.hx.phip.service.userLevel.UserLevelRuleService;
4dc6e5 38 import com.hx.phip.tool.CreateNo;
e3b9cc 39 import com.hx.phip.tool.payment.ConsumeTool;
fd7281 40 import com.hx.phip.tool.refund.OrderRefundCancelTool;
a1c527 41 import com.hx.phip.tool.refund.PartialRefundUtil;
C 42 import com.hx.phip.tool.refund.PaymentCountTool;
a036dc 43 import com.hx.phip.tool.refund.RefundTool;
253802 44 import com.hx.phip.util.api.*;
4df03d 45 import com.hx.phip.vo.order.payment.PayMethodVo;
C 46 import com.hx.phip.vo.order.refund.DistributionRedundMethodVo;
47 import com.hx.phip.vo.order.refund.DistributionRedundVo;
9d4e6f 48 import com.hx.resultTool.Result;
4dc6e5 49 import com.hx.util.StringUtils;
254bde 50 import com.hz.crm.dto.order.refund.RefundAmountModelDto;
Z 51 import com.hz.crm.dto.order.refund.RefundDto;
52 import com.hz.crm.dto.order.refund.RefundReturnDto;
4dc6e5 53 import com.hz.crm.feign.FOderService;
b9b969 54 import com.hz.his.dto.aduit.AduitDto;
42a0e7 55 import com.hz.his.dto.marketing.OrderPartRefundDto;
Z 56 import com.hz.his.dto.marketing.PartRefundPayDto;
57 import com.hz.his.dto.marketing.RefundProjectDto;
c38ec7 58 import com.hz.his.dto.order.*;
f23452 59 import com.hz.his.feign.service.dcp.SUserTagInfoService;
4dc6e5 60 import com.hz.his.feign.service.marketing.MOrderService;
fd7281 61 import com.hz.his.vo.order.refund.RefundCancelVo;
4df03d 62 import com.platform.entity.ThirtApplication;
4dc6e5 63 import com.platform.exception.PlatTipsException;
Z 64 import com.platform.resultTool.PlatformCode;
65 import com.platform.resultTool.PlatformResult;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
9d4e6f 68 import org.springframework.beans.BeanUtils;
4dc6e5 69 import org.springframework.stereotype.Service;
Z 70 import org.springframework.transaction.annotation.Transactional;
71
72 import javax.annotation.Resource;
73 import java.math.BigDecimal;
118d96 74 import java.math.RoundingMode;
25d452 75 import java.util.*;
da4ad2 76 import java.util.stream.Collectors;
4dc6e5 77
Z 78 /**
832331 79  * @author  CJH
4df03d 80  * 重构与2023-03-20
4dc6e5 81  */
Z 82 @Transactional
83 @Service
84 public class OrderRefundServiceImpl implements OrderRefundService {
85
4df03d 86     /**log4j日志*/
C 87     private static final Logger logger = LoggerFactory.getLogger(OrderRefundServiceImpl.class.getName());
4dc6e5 88     @Resource
Z 89     private OrdersTotalMapper ordersTotalMapper;
90     @Resource
91     private OrderItemMapper orderItemMapper;
fd7281 92     @Resource
C 93     private RefundRecordMapper refundRecordMapper;
4dc6e5 94     @Resource
Z 95     private OrderItemSonMapper orderItemSonMapper;
96     @Resource
7c75e2 97     private ConsumeNotifyRefundService consumeNotifyRefundService;
26ebce 98     @Resource
A 99     private UserLevelRuleService userLevelRuleService;
4dc6e5 100
Z 101     @Resource
102     private CommonService commonService;
103
104     @Resource
105     private FOderService fOderService;
106
107     @Resource
108     private SystemParameterMapper systemParameterMapper;
109     @Resource
110     private RefundRecordService refundRecordService;
111     @Resource
112     private PaymentMethodService paymentMethodService;
113     @Resource
114     private RefundRecordMethodService refundRecordMethodService;
115     @Resource
116     private RefundRecordItemService refundRecordItemService;
117     @Resource
cd66da 118     private RefundRecordItemSourceMapper refundRecordItemSourceMapper;
Z 119     @Resource
4dc6e5 120     private CustomParameter customParameter;
Z 121     @Resource
122     private MOrderService mOrderService;
c38ec7 123
Z 124     @Resource
125     private CouponOrderDiscountLogMapper couponOrderDiscountLogMapper;
36bc5e 126     @Resource
Z 127     private RefundRecordCouponMapper refundRecordCouponMapper;
a2fbbf 128     @Resource
Z 129     private CardEquityMapper cardEquityMapper;
95147d 130     @Resource
4df03d 131     private RefundMapper refundMapper;
C 132     @Resource
133     private CreateNoService createNoService;
e3b9cc 134     @Resource
f23452 135     private SUserTagInfoService sUserTagInfoService;
W 136     @Resource
137     private BotoxClubConfig botoxClubConfig;
118d96 138
a2fbbf 139     /**
Z 140      * 获取退款页面详情
118d96 141      * @param ordersTotal 订单
4df03d 142      * @return 可退款数量详情
a2fbbf 143      */
Z 144     @Override
118d96 145     public List<Map<String, Object>> refundDetails(OrdersTotal ordersTotal) {
ae6ff7 146
a2fbbf 147         SqlSentence sqlSentence = new SqlSentence();
Z 148         Map<String, Object> sqlMap = new HashMap<>();
149         sqlSentence.setM(sqlMap);
118d96 150
a2fbbf 151         sqlMap.put("isDel", BaseEntity.NO);
118d96 152         sqlMap.put("orderId", ordersTotal.getId());
a2fbbf 153         //一级子订单
ae6ff7 154         sqlSentence.sqlSentence("SELECT * FROM order_item WHERE  orderId = #{m.orderId} AND isDel = #{m.isDel}",sqlMap);
a2fbbf 155         List<OrderItem> orderItemList = orderItemMapper.selectList(sqlSentence);
Z 156
157         List<Map<String, Object>> orderItems = new ArrayList<>();
158
159         for (OrderItem orderItem : orderItemList) {
160             //判断这个项目能不能显示处理
161             switch (orderItem.getType()) {
162                 case OrderItemConstants.TYPE_PROJECT:
4df03d 163                     handleOrderItemIsProject(orderItems,orderItem);
a2fbbf 164                     break;
Z 165                 case OrderItemConstants.TYPE_RETAIL:
4df03d 166                     handleOrderItemIsRetail(orderItems,orderItem);
a2fbbf 167                     break;
55dbe8 168                 case OrderItemConstants.TYPE_DRUG:
4df03d 169                     handleOrderItemIsRetail(orderItems, orderItem);
55dbe8 170                     break;
a2fbbf 171                 case OrderItemConstants.TYPE_CARD:
4df03d 172                     handleOrderItemIsCard(orderItems, orderItem);
a2fbbf 173                     break;
Z 174                 case OrderItemConstants.TYPE_PROMOTION:
4df03d 175                     handleOrderItemIsPromotion(orderItems, orderItem);
a2fbbf 176                     break;
Z 177                 case OrderItemConstants.CARD_BAG:
4df03d 178                     handleOrderItemIsCardBag(orderItems, orderItem);
89b4d7 179                     break;
F 180                 case OrderItemConstants.TYPE_COUPON:
181                     handleOrderItemIsRetail(orderItems,orderItem);
a2fbbf 182                     break;
Z 183                 default:
184                     break;
185             }
186         }
187         return orderItems;
188     }
da4ad2 189     /**
Z 190      * 处理一级是项目的
191      */
4df03d 192     public void handleOrderItemIsProject(List<Map<String, Object>> orderItems, OrderItem orderItem) {
118d96 193         //获取用户项目
ae6ff7 194         UserProjectItem userProjectItem = PartialRefundUtil.getUserProject(orderItem.getId(),commonService);
118d96 195         if(userProjectItem == null){
C 196             throw new TipsException("用户项目获取失败!");
a2fbbf 197         }
118d96 198
C 199         orderItems.add(itemRefandDataPackage(orderItem,null,userProjectItem,null));
200     }
201
202     /**订单子项退款信息封装*/
203     public Map<String,Object> itemRefandDataPackage(OrderItem orderItem,OrderItemSon orderItemSon,UserProjectItem userProjectItem,List<UserCard> userCardList){
204
205         Map<String,Object> itemData = new HashMap<>();
206         if(orderItemSon != null){
207             itemData.put("id",orderItemSon.getId());
208             itemData.put("type",orderItemSon.getType());
209             itemData.put("goodsName",orderItemSon.getGoodsName());
210             itemData.put("curPrice",orderItemSon.getCurPrice());
211             itemData.put("specs",orderItemSon.getSpecs());
212             itemData.put("buyNum",orderItemSon.getBuyNum());
213             itemData.put("hasReNum",orderItemSon.getHasReNum());
214             itemData.put("notUsedNum",orderItemSon.getBuyNum()-orderItemSon.getHasReNum());
215         }else{
216             itemData.put("id",orderItem.getId());
217             itemData.put("type",orderItem.getType());
218             itemData.put("goodsName",orderItem.getGoodsName());
219             itemData.put("curPrice",orderItem.getCurPrice());
220             itemData.put("specs",orderItem.getSpecs());
221             itemData.put("buyNum",orderItem.getBuyNum());
222             itemData.put("hasReNum",orderItem.getHasReNum());
223             itemData.put("notUsedNum",orderItem.getBuyNum()-orderItem.getHasReNum());
a2fbbf 224         }
118d96 225
C 226         if(userProjectItem != null){
227             itemData.put("notUsedNum",userProjectItem.getNotUsedNum());
a2fbbf 228         }
118d96 229         if(userCardList != null){
C 230             itemData.put("notUsedNum",userCardList.size());
a2fbbf 231         }
118d96 232         return itemData;
a2fbbf 233     }
Z 234
da4ad2 235     /**
Z 236      * 处理一级是商品的
237      */
4df03d 238     public void handleOrderItemIsRetail(List<Map<String, Object>> orderItems, OrderItem orderItem) {
118d96 239         orderItems.add(itemRefandDataPackage(orderItem,null,null,null));
a2fbbf 240     }
Z 241
da4ad2 242     /**
Z 243      * 处理一级是卡项的
244      */
4df03d 245     public void handleOrderItemIsCard(List<Map<String, Object>> orderItems,OrderItem orderItem) {
C 246
247         SqlSentence sqlSentence = new SqlSentence();
248         Map<String,Object> sqlMap = new HashMap<>();
a2fbbf 249
118d96 250         //获取用户卡项
160c33 251         List<UserCard> userCardList = PartialRefundUtil.getRefundCard(orderItem.getId(),UserProjectConstants.EFF_STATUS_YES,commonService);
a2fbbf 252
118d96 253         //信息封装
C 254         Map<String,Object> itemData = itemRefandDataPackage(orderItem,null,null,userCardList);
a2fbbf 255
ae6ff7 256         //获取卡项的详细条目
118d96 257         sqlMap.put("commonId",orderItem.getCommonId());
4df03d 258         sqlSentence.sqlSentence(" SELECT groupName,shareMoney FROM card_equity WHERE cardItemId = #{m.commonId} ",sqlMap);
118d96 259         List<Map<String, Object>> cardEquitys = cardEquityMapper.selectListMap(sqlSentence);
ae6ff7 260
118d96 261         itemData.put("list", cardEquitys);
C 262         orderItems.add(itemData);
a2fbbf 263
Z 264     }
265
da4ad2 266     /**
Z 267      * 处理一级是促销的
268      */
4df03d 269     public void handleOrderItemIsPromotion(List<Map<String, Object>> orderItems, OrderItem orderItem) {
a2fbbf 270
4df03d 271         SqlSentence sqlSentence = new SqlSentence();
C 272         Map<String,Object> sqlMap = new HashMap<>();
273
274         //封装参数
118d96 275         Map<String,Object> itemData = itemRefandDataPackage(orderItem,null,null,null);
a2fbbf 276
118d96 277         //获取二级子订单
a2fbbf 278         sqlMap.put("orderItemId", orderItem.getId());
4df03d 279         sqlSentence.sqlSentence("SELECT * FROM order_item_source WHERE orderItemId = #{m.orderItemId} AND isDel = 0 ",sqlMap);
a2fbbf 280         List<OrderItemSon> orderItemSonList = orderItemSonMapper.selectList(sqlSentence);
4df03d 281         System.out.println("orderItemSonList:"+JSON.toJSONString(orderItemSonList));
a2fbbf 282         if (orderItemSonList == null) {
Z 283             return;
284         }
118d96 285
a2fbbf 286         List<Map<String, Object>> promotionList = new ArrayList<>();
Z 287
288         for (OrderItemSon orderItemSon : orderItemSonList) {
289             //判断这个项目能不能显示处理
290             switch (orderItemSon.getType()) {
291                 case OrderGoodsConstants.TYPE_PROJECT:
4df03d 292                     handleOrderItemSonIsProject(promotionList, orderItemSon);
a2fbbf 293                     break;
c02e62 294                 case OrderItemConstants.TYPE_RETAIL:
4df03d 295                     handleOrderItemSonIsRetail(promotionList, orderItemSon);
a2fbbf 296                     break;
Z 297                 default:
298                     break;
299             }
300         }
301
118d96 302         itemData.put("list", promotionList);
C 303         orderItems.add(itemData);
a2fbbf 304     }
da4ad2 305     /**
Z 306      * 处理一级是卡包
307      */
4df03d 308     public void handleOrderItemIsCardBag(List<Map<String, Object>> orderItems, OrderItem orderItem) {
C 309         SqlSentence sqlSentence = new SqlSentence();
310         Map<String,Object> sqlMap = new HashMap<>();
a2fbbf 311
118d96 312         Map<String,Object> itemData = itemRefandDataPackage(orderItem,null,null,null);
a2fbbf 313
Z 314         //二级子订单
315         sqlMap.put("orderItemId", orderItem.getId());
4df03d 316         sqlSentence.sqlSentence("SELECT * FROM order_item_source WHERE orderItemId= #{m.orderItemId} and  isDel = 0 ",sqlMap);
a2fbbf 317         List<OrderItemSon> orderItemSonList = orderItemSonMapper.selectList(sqlSentence);
Z 318         if (orderItemSonList == null) {
319             return;
320         }
321         List<Map<String, Object>> promotionList = new ArrayList<>();
322
323         for (OrderItemSon orderItemSon : orderItemSonList) {
324             //判断这个项目能不能显示处理
325             switch (orderItemSon.getType()) {
326                 case OrderGoodsConstants.TYPE_PROJECT:
4df03d 327                     handleOrderItemSonIsProject(promotionList, orderItemSon);
a2fbbf 328                     break;
c02e62 329                 case OrderItemConstants.TYPE_RETAIL:
4df03d 330                     handleOrderItemSonIsRetail(promotionList, orderItemSon);
a2fbbf 331                     break;
Z 332                 default:
333                     break;
334             }
335         }
336
118d96 337         itemData.put("list", promotionList);
C 338         orderItems.add(itemData);
a2fbbf 339     }
Z 340
da4ad2 341     /**
Z 342      * 处理二级是项目的
343      */
4df03d 344     public void handleOrderItemSonIsProject(List<Map<String, Object>> promotionList, OrderItemSon orderItemSon) {
C 345
118d96 346         //获取用户项目
ae6ff7 347         UserProjectItem userProjectItem = PartialRefundUtil.getUserProject(orderItemSon.getId(),commonService);
118d96 348         if(userProjectItem == null){
ae6ff7 349             throw new TipsException("用户项目获取失败[24]!");
118d96 350         }
C 351         Map<String,Object> itemData = itemRefandDataPackage(null,orderItemSon,userProjectItem,null);
a2fbbf 352
118d96 353         promotionList.add(itemData);
a2fbbf 354     }
Z 355
da4ad2 356
Z 357     /**
358      * 处理二级是商品的
359      */
4df03d 360     public void handleOrderItemSonIsRetail(List<Map<String, Object>> promotionList, OrderItemSon orderItemSon) {
118d96 361         promotionList.add(itemRefandDataPackage(null,orderItemSon,null,null));
a2fbbf 362     }
Z 363
364     /**
ae6ff7 365      * 退款选择退款数量组装金额信息,退款里面这个非常重要
4df03d 366      * @param orderRefundDto 退款数量信息
C 367      * @return 退款金额信息
a2fbbf 368      */
Z 369     @Override
118d96 370     public OrderRefundDto nextStep(OrdersTotal ordersTotal,OrderRefundDto orderRefundDto) {
25d452 371         logger.info("退款选择退款数量组装金额信息入参:{}", JSON.toJSONString(orderRefundDto));
a2fbbf 372
c04e8a 373         //子单退款
C 374         List<OrderItemRefundDto> refundList = orderRefundDto.getRefundList();
375         //支付方式退款数据整合
376         List<OrderPayMethodDto> refundPayMethods = new ArrayList<>();
a036dc 377         //可退款总金额
a2fbbf 378         BigDecimal totalAmount = BigDecimal.ZERO;
a036dc 379         //可退款总积分
C 380         BigDecimal totalIntegral = BigDecimal.ZERO;
a2fbbf 381
c04e8a 382         if (OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())) {
C 383             ///////充值订单退款
8b5222 384             refundPayMethods = rechargeRefundWay(ordersTotal);
C 385             for (OrderPayMethodDto orderPayMethodDto : refundPayMethods) {
a036dc 386                 if(PayMethodTypeConstants.PAY_INTEGRAL.equals(orderPayMethodDto.getPayMethodNo())){
C 387                     totalIntegral = totalIntegral.add(orderPayMethodDto.getPayTotal());
388                 }else{
389                     totalAmount = totalAmount.add(orderPayMethodDto.getPayTotal()).setScale(2,RoundingMode.HALF_UP);
390                 }
8b5222 391             }
c04e8a 392         }else{
C 393             //////其他订单类型
394             //整合支付方式退款金额
395             Map<String,OrderPayMethodDto> orderPayMethodDtoMap = new HashMap<>();
396             OrderPayMethodDto orderPayMethodDto;
118d96 397
4df03d 398             DistributionRedundVo distributionRedundVo;
C 399             OrderItem orderItem;
89b4d7 400
c04e8a 401             //计算每个条目需要退多少钱
C 402             for (OrderItemRefundDto orderItemRefundDto : refundList) {
4df03d 403                 if(StringUtils.isEmpty(orderItemRefundDto.getOrderItemId())){
C 404                     throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款项标识必填");
405                 }
406                 orderItem = orderItemMapper.selectOneByKey(orderItemRefundDto.getOrderItemId());
407                 if (orderItem == null) {
408                     throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款项标识错误");
409                 }
410                 if(!orderItem.getOrderId().equals(ordersTotal.getId())){
411                     throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到退款项[012]");
412                 }
2a45d4 413
c04e8a 414                 //判断这个项目能不能显示处理
4df03d 415                 switch (orderItem.getType()) {
c04e8a 416                     case OrderItemConstants.TYPE_PROJECT:
4df03d 417                         distributionRedundVo = itemOneRefund(orderItem,orderItemRefundDto);
c04e8a 418                         break;
C 419                     case OrderItemConstants.TYPE_RETAIL:
4df03d 420                         distributionRedundVo = itemOneRefund(orderItem,orderItemRefundDto);
c04e8a 421                         break;
C 422                     case OrderItemConstants.TYPE_DRUG:
4df03d 423                         distributionRedundVo = itemOneRefund(orderItem,orderItemRefundDto);
c04e8a 424                         break;
C 425                     case OrderItemConstants.TYPE_CARD:
4df03d 426                         distributionRedundVo = itemOneRefund(orderItem,orderItemRefundDto);
c04e8a 427                         break;
C 428                     case OrderItemConstants.TYPE_PROMOTION:
4df03d 429                         distributionRedundVo = nextStepIsPromotion(orderItem,orderItemRefundDto);
c04e8a 430                         break;
C 431                     case OrderItemConstants.CARD_BAG:
4df03d 432                         distributionRedundVo = nextStepIsPromotion(orderItem,orderItemRefundDto);
89b4d7 433                         break;
20d569 434                     case OrderItemConstants.TYPE_COUPON:
89b4d7 435                         distributionRedundVo = itemOneRefund(orderItem,orderItemRefundDto);
c04e8a 436                         break;
C 437                     default:
4df03d 438                         throw new TipsException("未知商品类型[008]!");
c04e8a 439                 }
4df03d 440
C 441                 //数据填充
442                 orderItemRefundDto.setApproveRefundTotal(distributionRedundVo.getRefundTotal());
443                 orderItemRefundDto.setType(distributionRedundVo.getGoodsType());
444                 orderItemRefundDto.setGoodsName(distributionRedundVo.getGoodsName());
445
a036dc 446                 //可退款金额计算
4df03d 447                 totalAmount = totalAmount.add(distributionRedundVo.getRefundTotal()).setScale(2,RoundingMode.HALF_UP);
a036dc 448                 //可退款积分计算
C 449                 totalIntegral = totalIntegral.add(distributionRedundVo.getRefundIntegral());
4df03d 450
C 451                 //整合可退款方式金额
452                 for(DistributionRedundMethodVo refundPaymentMethodVo:distributionRedundVo.getDistributionRedundMethodVoList()){
c04e8a 453                     orderPayMethodDto = orderPayMethodDtoMap.computeIfAbsent(refundPaymentMethodVo.getNumberNo(),
4df03d 454                             k->new OrderPayMethodDto(refundPaymentMethodVo.getNumberNo(),refundPaymentMethodVo.getName(),BigDecimal.ZERO,refundPaymentMethodVo.getIsMoneyPay(),refundPaymentMethodVo.getIsExecute()));
c04e8a 455                     orderPayMethodDto.setPayTotal(orderPayMethodDto.getPayTotal().add(refundPaymentMethodVo.getRefundTotal()).setScale(2,RoundingMode.HALF_UP));
C 456                 }
457             }
458
459             for(Map.Entry<String, OrderPayMethodDto> entry : orderPayMethodDtoMap.entrySet()) {
460                 refundPayMethods.add(entry.getValue());
c9e2be 461             }
a2fbbf 462         }
c9e2be 463
c04e8a 464         //支付方式
ae6ff7 465         orderRefundDto.setPayMethodList(refundPayMethods);
7f9228 466         //可退总金额
ae6ff7 467         orderRefundDto.setTotalAmount(totalAmount);
a036dc 468         //可退总积分
C 469         orderRefundDto.setTotalIntegral(totalIntegral);
7f9228 470         //优惠券
C 471         List<OrderCouponRefunDto> couponList = nextStepIsCoupon(ordersTotal.getId());
472         orderRefundDto.setPayCouponList(couponList);
473
ae6ff7 474         return orderRefundDto;
a2fbbf 475     }
da4ad2 476
c04e8a 477     /**获取充值单的退款方式金额*/
8b5222 478     public List<OrderPayMethodDto> rechargeRefundWay(OrdersTotal ordersTotal){
c9e2be 479
ae6ff7 480         //获取总支付方式
2a45d4 481         List<PayMethodVo> payMethodVoList = refundMapper.getConsumePayGroupByNumberNo(ordersTotal.getId());
542dc1 482
c04e8a 483         List<OrderPayMethodDto> consumeList = new ArrayList<>();
da4ad2 484         OrderPayMethodDto orderPayMethodDto;
c04e8a 485         //充值订单只能全退
ae6ff7 486         for (PayMethodVo payMethodVo:payMethodVoList) {
542dc1 487             //支付方式可退金额
da4ad2 488             orderPayMethodDto=new OrderPayMethodDto();
ae6ff7 489             orderPayMethodDto.setPayMethodNo(payMethodVo.getNumberNo());
C 490             orderPayMethodDto.setPayMethodName(payMethodVo.getName());
491             orderPayMethodDto.setRefundNumberNo(payMethodVo.getNumberNo());
492             orderPayMethodDto.setRefundNumberName(payMethodVo.getName());
493             orderPayMethodDto.setPayTotal(payMethodVo.getSurplusTotal());
da4ad2 494             orderPayMethodDto.setMoney(orderPayMethodDto.getPayTotal());
Z 495             consumeList.add(orderPayMethodDto);
254bde 496         }
542dc1 497         return consumeList;
a2fbbf 498     }
c04e8a 499
da4ad2 500     /**
Z 501      * 判断是否有使用优惠卷
502      */
503     public List<OrderCouponRefunDto> nextStepIsCoupon(String orderId) {
a2fbbf 504         SqlSentence sqlSentence = new SqlSentence();
Z 505         Map<String, Object> sqlMap = new HashMap<>();
4df03d 506
a2fbbf 507         sqlMap.put("isDel", BaseEntity.NO);
Z 508         sqlMap.put("orderId", orderId);
7f9228 509         sqlMap.put("status", BaseEntity.NO);
C 510         sqlSentence.sqlSentence("SELECT id,title FROM coupon_order_discount_log WHERE orderId=#{m.orderId} AND status = #{m.status} AND isDel=  #{m.isDel} ",sqlMap);
da4ad2 511         List<CouponOrderDiscountLog> couponOrderDiscountLogs = couponOrderDiscountLogMapper.selectList(sqlSentence);
Z 512         //拼接返回参数
513         List<OrderCouponRefunDto> consumeList=new ArrayList<>();
514         OrderCouponRefunDto orderCouponRefunDto;
515         for (CouponOrderDiscountLog couponOrderDiscountLog : couponOrderDiscountLogs) {
516             orderCouponRefunDto=new OrderCouponRefunDto();
517             orderCouponRefunDto.setOrderCouponId(couponOrderDiscountLog.getId());
518             orderCouponRefunDto.setOrderCouponTitle(couponOrderDiscountLog.getTitle());
519             consumeList.add(orderCouponRefunDto);
520         }
521
522         return consumeList;
a2fbbf 523     }
Z 524
da4ad2 525     /**
c04e8a 526      * 一级子单计算可退款金额
C 527      * @param orderItemRefundDto 封装的方法
528      * @return 退款金额
da4ad2 529      */
4df03d 530     public DistributionRedundVo itemOneRefund(OrderItem orderItem,OrderItemRefundDto orderItemRefundDto) {
c04e8a 531
C 532         if(orderItemRefundDto.getRefundNum() == null) {
533             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请填写退款数量!");
534         }
535         if(orderItemRefundDto.getRefundNum() < 1) {
542dc1 536             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款数量不能小于1");
c04e8a 537         }
C 538
539         ////算数量,退款用
540         //总数量
541         Integer buyNum;
542         //剩余数量
543         Integer surplusNum;
544
4df03d 545         if(OrderItemConstants.TYPE_PROJECT.equals(orderItem.getType())){
c04e8a 546             //////项目
ae6ff7 547             UserProjectItem userProjectItem = PartialRefundUtil.getUserProject(orderItem.getId(),commonService);
c04e8a 548             if(userProjectItem == null){
C 549                 throw new TipsException("用户项目获取失败!");
550             }
551             buyNum = userProjectItem.getUsedTotal();
552             surplusNum = userProjectItem.getNotUsedNum();
4df03d 553             if(orderItemRefundDto.getRefundNum() > surplusNum){
5fc368 554                 throw new TipsException("退款数量与可退数量不符[01]!");
4df03d 555             }
C 556             //替换成子单的剩余数量
557             surplusNum = orderItem.getUsedTotal() - orderItem.getHasReNum();
558         }else if(OrderItemConstants.TYPE_CARD.equals(orderItem.getType())){
c04e8a 559             ///////卡项
C 560             //获取可退款的卡项次数
160c33 561             List<UserCard> userCardList = PartialRefundUtil.getRefundCard(orderItem.getId(),UserProjectConstants.EFF_STATUS_YES,commonService);
c04e8a 562             buyNum = orderItem.getBuyNum();
C 563             surplusNum = userCardList.size();
1da3b3 564             if(orderItemRefundDto.getRefundNum() > surplusNum){
5fc368 565                 throw new TipsException("退款数量与可退数量不符[02]!");
1da3b3 566             }
949373 567             //替换成子单的剩余数量,2023-06-15因为做用户卡包退款原因,先屏掉这个
C 568             //surplusNum = orderItem.getBuyNum() - orderItem.getHasReNum();
118d96 569         }else{
c04e8a 570             buyNum = orderItem.getBuyNum();
1da3b3 571             //替换成子单的剩余数量
c04e8a 572             surplusNum = orderItem.getBuyNum() - orderItem.getHasReNum();
C 573         }
574         if(orderItemRefundDto.getRefundNum() > surplusNum){
5fc368 575             throw new TipsException("退款数量与可退数量不符[03]!");
118d96 576         }
2a0d69 577
ae6ff7 578         //获取该子单的支付方式,相同的支付方式求和返回
2a45d4 579         List<PayMethodVo> payMethodVoList = refundMapper.getConsumePayOneGroupByNumberNo(orderItem.getId());
c04e8a 580
dd4c9b 581         //获取该子单已退的总金额
a036dc 582         RefundRecordItem refundRecordItem = RefundTool.getOneAlreadyRefundTotal(orderItem.getId(),orderItem.getType(),commonService);
c04e8a 583
4df03d 584         //计算退款方式金额
a036dc 585         DistributionRedundVo distributionRedundVo = PaymentCountTool.countMakeWay(orderItem.getId(),orderItem.getActualTotal(),refundRecordItem.getOccupyRefundTotal()
C 586                 ,refundRecordItem.getOccupyRefundIntegral(),buyNum,surplusNum,null,orderItemRefundDto.getRefundNum(),payMethodVoList,commonService);
1869f3 587
4df03d 588         distributionRedundVo.setGoodsType(orderItem.getType());
C 589         distributionRedundVo.setGoodsName(orderItem.getGoodsName());
c04e8a 590
4df03d 591         return distributionRedundVo;
a2fbbf 592     }
Z 593
dd4c9b 594
da4ad2 595     /**
c04e8a 596      * 二级子单计算可退款金额
C 597      * @param orderItemSourceRefundDto 封装的方法
598      * @param goodsType 子单的商品类型
599      * @return 退款金额
da4ad2 600      */
4df03d 601     public DistributionRedundVo itemTwoRefund(OrderItemSon orderItemSon,OrderItemSourceRefundDto orderItemSourceRefundDto,String goodsType) {
c04e8a 602
C 603         if(orderItemSourceRefundDto.getRefundNum() == null) {
604             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请填写退款数量!");
605         }
606         if(orderItemSourceRefundDto.getRefundNum() < 1) {
542dc1 607             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款数量不能小于1");
a2fbbf 608         }
Z 609
1da3b3 610         ////算数量
C 611         //总数量
612         Integer buyNum;
613         //剩余数量
614         Integer surplusNum;
118d96 615
a036dc 616         UserProjectItem userProjectItem;
c04e8a 617         if(OrderItemConstants.TYPE_PROJECT.equals(goodsType)){
C 618             //获取用户项目
ae6ff7 619             userProjectItem = PartialRefundUtil.getUserProject(orderItemSon.getId(),commonService);
c04e8a 620             if(userProjectItem == null){
C 621                 throw new TipsException("用户项目获取失败!");
622             }
623             buyNum = userProjectItem.getUsedTotal();
624             surplusNum = userProjectItem.getNotUsedNum();
1da3b3 625             if(orderItemSourceRefundDto.getRefundNum() > surplusNum){
5fc368 626                 throw new TipsException("退款数量与可退数量不符[04]!");
c04e8a 627             }
1da3b3 628             //替换成子单
C 629             surplusNum = orderItemSon.getUsedTotal() - orderItemSon.getHasReNum();
630         }else{
631             buyNum = orderItemSon.getBuyNum();
632             surplusNum = orderItemSon.getBuyNum() - orderItemSon.getHasReNum();
c04e8a 633         }
1da3b3 634
c04e8a 635         if(orderItemSourceRefundDto.getRefundNum() > surplusNum){
5fc368 636             throw new TipsException("退款数量与可退数量不符[05]!");
c04e8a 637         }
C 638
639         //获取该子单的支付方式,相同的支付方式算和返回
2a45d4 640         List<PayMethodVo> payMethodVoList = refundMapper.getConsumePayTwoGroupByNumberNo(orderItemSon.getId());
c04e8a 641
a036dc 642         //获取该子单已退的总金额
8eea74 643         RefundRecordItemSource refundRecordItemSource = RefundTool.getTwoAlreadyRefundTotal(orderItemSon.getId(),commonService);
a036dc 644
4df03d 645         //计算退款方式金额
a036dc 646         DistributionRedundVo distributionRedundVo = PaymentCountTool.countMakeWay(orderItemSon.getId(),orderItemSon.getActualTotal(),refundRecordItemSource.getOccupyRefundTotal()
C 647                 ,refundRecordItemSource.getOccupyRefundIntegral(),buyNum,surplusNum,null,orderItemSourceRefundDto.getRefundNum(),payMethodVoList,commonService);
648
4df03d 649         distributionRedundVo.setGoodsType(orderItemSon.getType());
C 650         distributionRedundVo.setGoodsName(orderItemSon.getGoodsName());
651         return distributionRedundVo;
a2fbbf 652     }
Z 653
da4ad2 654     /**
Z 655      * 一级是促销
656      */
4df03d 657     public DistributionRedundVo nextStepIsPromotion(OrderItem orderItem,OrderItemRefundDto orderItemRefundDto) {
c04e8a 658
a2fbbf 659         List<OrderItemSourceRefundDto> orderItemSourceRefundDtos = orderItemRefundDto.getOrderItemSourceRefundDtos();
Z 660         if (orderItemSourceRefundDtos == null) {
542dc1 661             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款数量不能小于1");
d1b8f5 662         }
c04e8a 663
d1b8f5 664         //2022-12-29 荣爷说因为优惠卷超过了金额,数据库是负数,所以退款取0
Z 665         if(orderItem.getActualTotal().compareTo(BigDecimal.ZERO)<1){
666             orderItem.setActualTotal(BigDecimal.ZERO);
a2fbbf 667         }
Z 668
4df03d 669         //返回结构
C 670         DistributionRedundVo distributionRedundVo = new DistributionRedundVo();
c04e8a 671
4df03d 672         //整合当前一级子单的退款金额数据,key值:支付方式编号
C 673         Map<String,DistributionRedundMethodVo> refundPaymentMethodVoMap = new HashMap<>();
674         DistributionRedundMethodVo refundPaymentMethodVo;
675
676         DistributionRedundVo distributionRedundVoSon;
a2fbbf 677         for (OrderItemSourceRefundDto orderItemSourceRefundDto : orderItemSourceRefundDtos) {
4df03d 678             if(StringUtils.isEmpty(orderItemSourceRefundDto.getOrderItemSonId())){
C 679                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款项标识必填[54]");
a2fbbf 680             }
c04e8a 681
4df03d 682             OrderItemSon orderItemSon = orderItemSonMapper.selectOneByKey(orderItemSourceRefundDto.getOrderItemSonId());
C 683             if (orderItemSon == null) {
684                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款项标识错误[54]");
685             }
686
687             if (!orderItemSon.getOrderItemId().equals(orderItem.getId())) {
688                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到退款项[54]");
689             }
690
691             switch (orderItemSon.getType()) {
692                 case OrderGoodsConstants.TYPE_PROJECT:
693                     distributionRedundVoSon = itemTwoRefund(orderItemSon,orderItemSourceRefundDto,orderItemSourceRefundDto.getType());
694                     break;
695                 case OrderItemConstants.TYPE_RETAIL:
696                     distributionRedundVoSon = itemTwoRefund(orderItemSon,orderItemSourceRefundDto,orderItemSourceRefundDto.getType());
697                     break;
698                 case OrderItemConstants.TYPE_DRUG:
699                     distributionRedundVoSon = itemTwoRefund(orderItemSon,orderItemSourceRefundDto,orderItemSourceRefundDto.getType());
700                     break;
701                 default:
702                     throw new TipsException("未知商品类型[098]!");
703             }
704
705             //数据填充
706             orderItemSourceRefundDto.setType(distributionRedundVoSon.getGoodsType());
707             orderItemSourceRefundDto.setGoodsName(distributionRedundVoSon.getGoodsName());
708             orderItemSourceRefundDto.setApproveRefundTotal(distributionRedundVoSon.getRefundTotal());
709
710             //返回结构金额填充
711             distributionRedundVo.setRefundTotal(distributionRedundVo.getRefundTotal().add(distributionRedundVoSon.getRefundTotal()).setScale(2,RoundingMode.HALF_UP));
712             distributionRedundVo.setRefundCash(distributionRedundVo.getRefundCash().add(distributionRedundVoSon.getRefundCash()).setScale(2,RoundingMode.HALF_UP));
713             distributionRedundVo.setRefundExecute(distributionRedundVo.getRefundExecute().add(distributionRedundVoSon.getRefundExecute()).setScale(2,RoundingMode.HALF_UP));
714
c04e8a 715             //整合退款金额
4df03d 716             for(DistributionRedundMethodVo paymentMethodVo:distributionRedundVoSon.getDistributionRedundMethodVoList()){
c04e8a 717                 //整合金额,上级用到
C 718                 refundPaymentMethodVo = refundPaymentMethodVoMap.computeIfAbsent(paymentMethodVo.getNumberNo()
4df03d 719                         ,k-> new DistributionRedundMethodVo(paymentMethodVo.getNumberNo(),paymentMethodVo.getName(),BigDecimal.ZERO,paymentMethodVo.getIsMoneyPay(),paymentMethodVo.getIsExecute()));
c04e8a 720                 refundPaymentMethodVo.setRefundTotal(refundPaymentMethodVo.getRefundTotal().add(paymentMethodVo.getRefundTotal()).setScale(2,RoundingMode.HALF_UP));
C 721             }
722
a2fbbf 723         }
4df03d 724
C 725         //返回结构数据填充
726         distributionRedundVo.setGoodsName(orderItem.getGoodsName());
727         distributionRedundVo.setGoodsType(orderItem.getType());
a2fbbf 728
c04e8a 729         //整合退款金额的数据
4df03d 730         List<DistributionRedundMethodVo> distributionPayList = new ArrayList<>();
C 731         for(Map.Entry<String,DistributionRedundMethodVo> entry : refundPaymentMethodVoMap.entrySet()){
c04e8a 732             distributionPayList.add(entry.getValue());
C 733         }
4df03d 734         distributionRedundVo.setDistributionRedundMethodVoList(distributionPayList);
c04e8a 735
4df03d 736         return distributionRedundVo;
a2fbbf 737     }
Z 738
739     /**
25d452 740      * 确认退款处理退款逻辑
478fa9 741      * @param orderRefundDto 退款数据结构
C 742      * @return 结构
a2fbbf 743      */
4dc6e5 744     @Override
4df03d 745     public PlatformResult partRefund(OrdersTotal ordersTotal, OrderRefundDto orderRefundDto, ThirtApplication thirtApplication) {
25d452 746         logger.info("退款打印参数:{}", JSON.toJSONString(orderRefundDto));
c04e8a 747
C 748         if(OrderTotalConstants.PAY_STATUS_SUC != ordersTotal.getPayStatus()){
749             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单未支付!");
750         }
751         if(OrderTotalConstants.STATUS_PAY != ordersTotal.getStatus()
752                 && OrderTotalConstants.STATUS_WAIT_RECEIVE != ordersTotal.getStatus()
753                 && OrderTotalConstants.STATUS_DONE != ordersTotal.getStatus()){
754             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单不是已支付状态!");
4dc6e5 755         }
da4ad2 756
c04e8a 757         if(OrderTotalConstants.STATUS_REFUND_NONE != ordersTotal.getRefundStatus() &&
C 758                 OrderTotalConstants.STATUS_REFUND_PART != ordersTotal.getRefundStatus()){
759             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单退款状态不正确!");
da4ad2 760         }
c04e8a 761
C 762         //先优先改成申请退款中
da4ad2 763         SqlSentence sqlSentence = new SqlSentence();
Z 764         Map<String,Object> map=new HashMap<>();
4df03d 765
da4ad2 766         map.put("refundStatus",OrderTotalConstants.STATUS_REFUND_APPLY);
0a9391 767         map.put("isSyncOrder", BaseEntity.NO);
da4ad2 768         map.put("id",ordersTotal.getId());
4df03d 769         sqlSentence.sqlSentence(" refundStatus=#{m.refundStatus},isSyncOrder=#{m.isSyncOrder}  WHERE id=#{m.id}   AND refundStatus IN('"+OrderTotalConstants.STATUS_REFUND_NONE+"','"+OrderTotalConstants.STATUS_REFUND_PART+"')  ",map);
C 770         if(ordersTotalMapper.updateWhere(sqlSentence) != 1){
771             throw new TipsException("操作失败,当前订单退款状态不能再次发起退款!");
5425ba 772         }
4dc6e5 773
ae6ff7 774         //校验参数和获取系统参数,非常重要
4df03d 775         orderRefundDto = parameterVerification(ordersTotal,orderRefundDto);
4dc6e5 776
4df03d 777         return handlePartRefund(ordersTotal,orderRefundDto,thirtApplication);
4dc6e5 778     }
4df03d 779
da4ad2 780     /**
832331 781      * 退款校验参数,拼接参数
da4ad2 782      */
832331 783     @Override
C 784     public OrderRefundDto  parameterVerification(OrdersTotal ordersTotal, OrderRefundDto orderRefundDto){
2a45d4 785
C 786         if(orderRefundDto.getRefundPayMethod() == null){
787             throw new TipsException("退款方式结构不能空");
788         }
c04e8a 789
da4ad2 790         //怕被获取到项目信息收到被改了项目价格,重新去获取一下项目价格
4df03d 791         orderRefundDto =  nextStep(ordersTotal,orderRefundDto);
b9b969 792
8b5222 793         //可退款支付格式,key值:支付编号
4df03d 794         Map<String,OrderPayMethodDto> orderPayMethodDtoMap = new HashMap<>();
8b5222 795         for (OrderPayMethodDto orderPayMethodDto : orderRefundDto.getPayMethodList()) {
4df03d 796             orderPayMethodDtoMap.put(orderPayMethodDto.getPayMethodNo(),orderPayMethodDto);
da4ad2 797         }
4df03d 798
C 799         //填写退款的总金额
800         BigDecimal refundTotal = BigDecimal.ZERO;
801
802         //校验金额
803         OrderPayMethodDto payMethodDto;
804         //遍历系统获取到的可退款方式
8b5222 805         OrderPayMethodDto orderPayMethodDto;
C 806         for (int i = orderRefundDto.getRefundPayMethod().size()-1; i>=0 ;i--) {
807             orderPayMethodDto = orderRefundDto.getRefundPayMethod().get(i);
4df03d 808             //获取是传值过来的金额数据
C 809             payMethodDto = orderPayMethodDtoMap.get(orderPayMethodDto.getPayMethodNo());
810             if(payMethodDto == null){
811                 throw new TipsException("未找到["+orderPayMethodDto.getPayMethodName()+"]支付方式!");
812             }
ae6ff7 813             //判断退款方式
8b5222 814             PaymentMethod refundMethod = paymentMethodService.selectNumberNoUncheckUp(orderPayMethodDto.getRefundNumberNo());
ae6ff7 815             if(refundMethod==null){
C 816                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该转换方式:"+orderPayMethodDto.getRefundNumberName()+"["+orderPayMethodDto.getRefundNumberNo()+"]");
817             }
8b5222 818             if(orderPayMethodDto.getMoney() == null){
4df03d 819                 throw new TipsException("["+orderPayMethodDto.getPayMethodName()+"]退款金额必填!");
C 820             }
8b5222 821             if(orderPayMethodDto.getMoney().compareTo(BigDecimal.ZERO) < 0){
4df03d 822                 throw new TipsException("["+orderPayMethodDto.getPayMethodName()+"]退款金额错误!");
C 823             }
8b5222 824             if (orderPayMethodDto.getMoney().compareTo(payMethodDto.getPayTotal()) > 0){
4df03d 825                 throw new TipsException("当前退款方式["+orderPayMethodDto.getPayMethodName()+"]金额超出可退金额!");
C 826             }
8b5222 827             //退款金额是0元,去掉退款方式
C 828             if(orderPayMethodDto.getMoney().compareTo(BigDecimal.ZERO) == 0){
829                 orderRefundDto.getRefundPayMethod().remove(i);
830             }
29ff38 831
C 832             //特殊的退款判断
d0ca72 833             RefundTool.paymemtCheck(orderPayMethodDto.getPayMethodNo(),orderPayMethodDto.getRefundNumberNo());
29ff38 834
8b5222 835             orderPayMethodDto.setPayMethodName(payMethodDto.getPayMethodName());
C 836             orderPayMethodDto.setPayMethodNo(payMethodDto.getPayMethodNo());
837             orderPayMethodDto.setPayTotal(payMethodDto.getPayTotal());
4df03d 838
8b5222 839             refundTotal = refundTotal.add(orderPayMethodDto.getMoney()).setScale(2,RoundingMode.HALF_UP);
4df03d 840
C 841         }
842         orderRefundDto.setRefundTotal(refundTotal);
843
844         if(orderRefundDto.getRefundTotal().compareTo(orderRefundDto.getTotalAmount()) > 0){
8b5222 845             throw new TipsException("退款金额不能大于可退金额[004]!");
4df03d 846         }
da4ad2 847
Z 848         return orderRefundDto;
849     }
850
851     /**
852      * 处理退款详情
853      */
4df03d 854     public PlatformResult handlePartRefund(OrdersTotal ordersTotal,OrderRefundDto orderRefundDto,ThirtApplication thirtApplication){
46bedb 855
Z 856         //订单节点日志
857         OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
858         StringBuilder orderNodeBuilder = new StringBuilder();
859
04ce22 860         orderNodeBuilder.append("开始退款");
478fa9 861         orderNodeBuilder.append("-本次退款项目总金额:").append(orderRefundDto.getTotalAmount()).append(",客户选的退款方式总金额:").append(orderRefundDto.getRefundTotal());
da4ad2 862
4dc6e5 863         Map<String, String> operator = ApiOrderUtil.getOperator(commonService, orderRefundDto.getOperatorId());//获取操作人信息
Z 864         SqlSentence sqlSentence = new SqlSentence();
865         Map<String,Object> map=new HashMap<>();
866         sqlSentence.setM(map);
867         //退款总记录
46bedb 868         orderNodeBuilder.append("-处理退款总记录");
8eb9e6 869
fd7281 870         //保存退款信息,不是真正的退款,提前扣减用户资金
4df03d 871         RefundRecord refundRecord = insertRefundInfo(orderRefundDto,ordersTotal,orderNodeBuilder,thirtApplication);
c38ec7 872
9d4e6f 873         //判断已支付订单是否需要营销助手审批
Z 874         //记录取消日志
4df03d 875         CancelOrder cancelOrder = handleCancelOrder(ordersTotal,orderRefundDto);
9d4e6f 876
4df03d 877         if (orderRefundDto.getIsApproval().equals(BaseEntity.YES)){
4ebb90 878             //调用审批功能
4df03d 879             return handleApproval(ordersNodeLog,orderNodeBuilder,ordersTotal,cancelOrder,refundRecord);
9d4e6f 880         }
4df03d 881
C 882         //这里开始真正的退款到用户账户的
883         Map<String, Object> refund = handleRefundOrder(operator,refundRecord,ordersTotal,ordersNodeLog,orderNodeBuilder,cancelOrder);
9d4e6f 884         return PlatformResult.success(refund);
4df03d 885     }
C 886
887     /**保存退款信息
888      * 保存退款信息,并没有真正退款
889      */
832331 890     @Override
C 891     public RefundRecord insertRefundInfo(OrderRefundDto orderRefundDto, OrdersTotal ordersTotal
892             , StringBuilder orderNodeBuilder, ThirtApplication thirtApplication){
510678 893
C 894         //操作人
895         Employee employee = commonService.selectOneByKey(EmployeeMapper.class,orderRefundDto.getOperatorId());
896         if(employee == null){
897             throw new TipsException("操作人标识错误!");
898         }
4df03d 899
C 900         ///////退款总表数据填充
901         //生成退款编号
902         String totalCode = createNoService.createNo("R",System.currentTimeMillis()+"",8);
903         RefundRecord refundRecord=new RefundRecord(totalCode,ordersTotal.getShopId(),ordersTotal.getShopName(),orderRefundDto.getRefundTotal()
904                 , RefundStatus.STATUS_APPLY_REFUND,0, RefundSoruceConstants.TYPE_SOURCE_ORDER,orderRefundDto.getRemarks(),ordersTotal.getId(),ordersTotal.getUserId());
510678 905         //操作人信息
4df03d 906         refundRecord.setOperatorType(RefundRecord.OPERATOR_TYPE_EMPLOYEE);
C 907         refundRecord.setOperatorId(employee.getId());
510678 908         refundRecord.setOperatorNo(employee.getEmployeeNo());
4df03d 909         refundRecord.setOperatorName(employee.getCnName());
510678 910
C 911         refundRecord.setRefundOperationType(orderRefundDto.getRefundOperationType());
4df03d 912         /////退款的备注
C 913         refundRecord.setRemarks(orderRefundDto.getRemarks());
914         refundRecord.setRefundReason(orderRefundDto.getRefundReason());
915         refundRecord.setOperatorAppId(thirtApplication.getAppId());
916         refundRecord.setOperatorAppCode(thirtApplication.getAppIdCode());
917         refundRecord.setOperatorAppName(thirtApplication.getName());
918         refundRecordService.insert(refundRecord);
919
920         //退款方式处理
ae6ff7 921         if(orderRefundDto.getRefundPayMethod() !=null && orderRefundDto.getRefundPayMethod().size() > 0){
510678 922             handleRefundPayMethod(orderRefundDto,orderNodeBuilder,ordersTotal,refundRecord);
4df03d 923         }
C 924
925         //退款的子项处理
926         if(orderRefundDto.getRefundList()!=null && orderRefundDto.getRefundList().size()>0){
510678 927             insertRefundRecordItem(orderRefundDto,orderNodeBuilder,refundRecord);
4df03d 928         }
C 929         //回退的优惠卷处理
930         if(orderRefundDto.getCouponList() != null && orderRefundDto.getCouponList().size()>0){
931             handleOrderCouponRefunDto(orderRefundDto.getCouponList(),orderNodeBuilder,ordersTotal,refundRecord);
932         }
933
160383 934         //*******扣减赠送的账户资金,如果订单有老带新的赠送规则,那么如果申请退款,就优先把老带新的退回来*****
C 935         //获取老带新记录
936         oldBlingNewRefund(refundRecord,orderNodeBuilder,commonService);
4ebb90 937
C 938         //判断是否是充值订单,是的话先冻结储值金,就是扣掉,审批通过就不处理储值金了,不通过还原资金
939         if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
b3fdea 940             OrderRefundCancelTool.rechargeHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_EXECUTE,"申请退款",orderNodeBuilder,commonService);
4ebb90 941         }
C 942         //活动处理
b3fdea 943         OrderRefundCancelTool.activityRuleHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_EXECUTE,"申请退款",orderNodeBuilder,commonService);
160383 944
4df03d 945         return refundRecord;
edf5ea 946     }
Z 947
160383 948     /**老带新的订单退款,佣金处理*/
C 949     public void oldBlingNewRefund(RefundRecord refundRecord,StringBuilder orderNodeBuilder,CommonService commonService){
950
951         SqlSentence sqlSentence = new SqlSentence();
952         Map<String,Object> values = new HashMap<>();
953
954         //查找老带新记录,未删除且有效的,没有退回的
955         values.put("operationReason",OperationReasonConstants.OP_REASON_BRING_NEW_USER_GIFT);
956         values.put("orderId",refundRecord.getOrderId());
957         sqlSentence.sqlSentence("SELECT * FROM user_money_unclaimed mu WHERE mu.isDel = 0 AND mu.isValid = 1 AND mu.operationReason = #{m.operationReason}" +
958                 " AND mu.orderId = #{m.orderId} AND NOT EXISTS(SELECT * FROM refund_user_assets rua WHERE rua.isDel = 0 AND rua.status = 1" +
959                 " AND rua.amountStatus IN (1,3) AND rua.userMoneyUnclaimedId = mu.id)",values);
960         List<UserMoneyUnclaimed> userMoneyUnclaimedList = commonService.selectList(UserMoneyUnclaimedMapper.class,sqlSentence);
961         RefundUserAssets refundUserAssets;
962         UserMoney userMoney;
963         User user;
964         BigDecimal amount;
965         for (UserMoneyUnclaimed userMoneyUnclaimed:userMoneyUnclaimedList){
966             amount = BigDecimal.ZERO;
967             //生成记录
968             refundUserAssets = new RefundUserAssets();
969             refundUserAssets.setType(userMoneyUnclaimed.getOperationReason());
970             refundUserAssets.setStatus(RefundUserAssets.STATUS_NORMAL);
971             refundUserAssets.setAmountType(userMoneyUnclaimed.getFundType());
fd7281 972             refundUserAssets.setAmount(userMoneyUnclaimed.getOpNumber().negate());
160383 973             refundUserAssets.setOperatorId(refundRecord.getOperatorId());
C 974             refundUserAssets.setOperatorNo(refundRecord.getOperatorNo());
975             refundUserAssets.setOperatorName(refundRecord.getOperatorName());
976             refundUserAssets.setOrderId(refundRecord.getOrderId());
977             refundUserAssets.setRefundRecordId(refundRecord.getId());
978             refundUserAssets.setUserMoneyUnclaimedId(userMoneyUnclaimed.getId());
979             refundUserAssets.setUserId(userMoneyUnclaimed.getUserId());
980
981             user = commonService.selectOneByKey(UserMapper.class,refundUserAssets.getUserId());
982             orderNodeBuilder.append("-退款处理老带新,扣减用户:").append(user.getName()).append(",CIQ:").append(user.getCIQ()).append(",");
983             orderNodeBuilder.append(RefundUserAssets.amountTypeName(refundUserAssets.getAmountType())).append(refundUserAssets.getAmount());
984             if(userMoneyUnclaimed.getStatus() == UserMoneyUnclaimed.STATUS_WAI){
985                 refundUserAssets.setAmountStatus(RefundUserAssets.AMOUNT_STATUS_NOT_RECEIVE);
986                 //用户未领取,那么直接作废,作废是逻辑删除
987                 values.put("id",userMoneyUnclaimed.getId());
988                 values.put("status",UserMoneyUnclaimed.STATUS_WAI);
989                 sqlSentence.sqlUpdate("isDel = 1,isValid = 0 WHERE id = #{m.id} AND isDel = 0 AND isValid = 1 AND status = #{m.status}",values);
990                 if(commonService.updateWhere(UserMoneyUnclaimedMapper.class,sqlSentence) != 1){
991                     throw new TipsException("老带新资产记录状态已变化!");
992                 }
993
994                 orderNodeBuilder.append(",用户未领取,作废领取记录");
995             }else if(userMoneyUnclaimed.getStatus() == UserMoneyUnclaimed.STATUS_SUCCEED){
996                 //用户已经领取了,那么要扣掉,但是,要先判断用户是否够,如果不够,那么也生成记录,显示未操作资金
997                 values.clear();
998                 values.put("userId",userMoneyUnclaimed.getUserId());
999                 sqlSentence.sqlSentence("SELECT * FROM user_money WHERE isDel = 0 AND userId = #{m.userId}",values);
1000                 userMoney = commonService.selectOne(UserMoneyMapper.class,sqlSentence);
1001                 if(userMoneyUnclaimed.getFundType() == UserMoneyUnclaimed.FUND_TYPE_STORED_VALUE_FUND){
1002                     //储值金
1003                     if(userMoney.getStoredValueFund() != null){
1004                         amount = new BigDecimal(userMoney.getStoredValueFund());
1005                     }
1006                 }else if(userMoneyUnclaimed.getFundType() == UserMoneyUnclaimed.FUND_TYPE_VALUE_ADDED_FUND){
1007                     //增值金
1008                     if(userMoney.getValueAddedFund() != null){
1009                         amount = new BigDecimal(userMoney.getValueAddedFund());
1010                     }
1011                 }else if(userMoneyUnclaimed.getFundType() == UserMoneyUnclaimed.FUND_TYPE_INTEGRAL){
1012                     //预定金
1013                     if(userMoney.getDeposit() != null){
1014                         amount = new BigDecimal(userMoney.getDeposit());
1015                     }
1016                 }else if(userMoneyUnclaimed.getFundType() == UserMoneyUnclaimed.FUND_TYPE_DEPOSIT){
1017                     //积分
1018                     if(userMoney.getIntegral() != null){
1019                         amount = new BigDecimal(userMoney.getIntegral());
1020                     }
1021                 }else{
1022                     throw new TipsException("老带新资产记录金额类型未知!");
1023                 }
599080 1024                 if(amount.compareTo(refundUserAssets.getAmount().negate()) >= 0){
160383 1025                     //用户资产够减
C 1026                     orderNodeBuilder.append(",扣减成功");
1027                     refundUserAssets.setAmountStatus(RefundUserAssets.AMOUNT_STATUS_NORMAL);
1028                 }else {
1029                     orderNodeBuilder.append(",余额不足,扣减失败");
1030                     //用户资产不够减
1031                     refundUserAssets.setAmountStatus(RefundUserAssets.AMOUNT_STATUS_NOT);
1032                 }
1033             }else{
1034                 throw new TipsException("老带新资产记录状态错误!");
1035             }
1036
1037             if(refundUserAssets.getAmountStatus() == RefundUserAssets.AMOUNT_STATUS_NORMAL
1038                     || refundUserAssets.getAmountStatus() == RefundUserAssets.AMOUNT_STATUS_NOT_RECEIVE ){
1039                 //保存记录,正常扣减和未领取才去保存这个记录
1040                 commonService.insert(RefundUserAssetsMapper.class,refundUserAssets);
1041             }
1042
1043             //用户资金操作
1044             if(refundUserAssets.getAmountStatus() == RefundUserAssets.AMOUNT_STATUS_NORMAL){
1045                 UserMoneyUtil.setNewUserMoneyUnclaimed(refundUserAssets.getUserId(),refundRecord.getRemarks(),"退款:老带新资金回退",refundUserAssets.getOperatorId()
fd7281 1046                         ,refundRecord.getOrderId(),refundRecord.getOperatorAppCode(),refundUserAssets.getId(),refundUserAssets.getAmount(),refundUserAssets.getAmountType()
160383 1047                         ,OperationReasonConstants.OP_REASON_BRING_NEW_USER_GIFT_RETRUN,commonService,UserMoneyUnclaimed.YES);
C 1048             }
1049
1050         }
1051
1052     }
1053
1054     /**老带新的订单退款不通过或者作废,佣金处理*/
1055     public void oldBlingNewRefundFail(RefundRecord refundRecord,StringBuilder orderNodeBuilder,CommonService commonService) {
1056
1057         ////订单退款状态是没有退款才退回
1058         //获取回退记录
1059         SqlSentence sqlSentence = new SqlSentence();
1060         Map<String,Object> values = new HashMap<>();
1061         values.put("orderId",refundRecord.getOrderId());
1062         sqlSentence.sqlSentence("SELECT * FROM refund_user_assets rua WHERE rua.isDel = 0 AND rua.status = 1 AND rua.amountStatus IN(1,3) AND rua.orderId = #{m.orderId}",values);
1063         List<RefundUserAssets> refundUserAssetsList = commonService.selectList(RefundUserAssetsMapper.class,sqlSentence);
1064
1065         User user;
1066         for(RefundUserAssets refundUserAssets:refundUserAssetsList){
1067
1068             user = commonService.selectOneByKey(UserMapper.class,refundUserAssets.getUserId());
1069             orderNodeBuilder.append("-退款处理老带新,回退资金到用户:").append(user.getName()).append(",CIQ:").append(user.getCIQ()).append(",");
1070             orderNodeBuilder.append(RefundUserAssets.amountTypeName(refundUserAssets.getAmountType())).append(refundUserAssets.getAmount());
1071
1072             //是否有扣减用户资产
1073             if(refundUserAssets.getAmountStatus() == RefundUserAssets.AMOUNT_STATUS_NORMAL){
1074                 orderNodeBuilder.append(",增加成功");
1075                 UserMoneyUtil.setNewUserMoneyUnclaimed(refundUserAssets.getUserId(),refundRecord.getRemarks(),"退款作废:老带新资金回退作废",refundUserAssets.getOperatorId()
fd7281 1076                         ,refundRecord.getOrderId(),refundRecord.getOperatorAppCode(),refundUserAssets.getId(),refundUserAssets.getAmount().negate(),refundUserAssets.getAmountType()
160383 1077                         ,OperationReasonConstants.OP_REASON_BRING_NEW_USER_GIFT_RETRU_CANCEL,commonService,UserMoneyUnclaimed.YES);
C 1078             }else if(refundUserAssets.getAmountStatus() == RefundUserAssets.AMOUNT_STATUS_NOT_RECEIVE){
1079                 //用户未领取记录,还原
1080                 orderNodeBuilder.append(",用户未领取,作废的领取记录还原");
1081                 values.clear();
1082                 values.put("id",refundUserAssets.getUserMoneyUnclaimedId());
1083                 values.put("status",UserMoneyUnclaimed.STATUS_WAI);
1084                 sqlSentence.sqlUpdate("isDel = 0,isValid = 1 WHERE id = #{m.id} AND isDel = 1 AND isValid = 0 AND status = #{m.status}",values);
1085                 if(commonService.updateWhere(UserMoneyUnclaimedMapper.class,sqlSentence) != 1){
1086                     throw new TipsException("老带新资产记录状态已变化[作废]!");
1087                 }
1088             }
66d1dc 1089
C 1090             //记录作废
1091             values.clear();
1092             values.put("id",refundUserAssets.getId());
1093             values.put("status",RefundUserAssets.STATUS_CANCEL);
1094             values.put("oldStatus",RefundUserAssets.STATUS_NORMAL);
1095             sqlSentence.sqlSentence("status = #{m.status} WHERE id = #{m.id} AND status = #{m.oldStatus}",values);
1096             if(commonService.updateWhere(RefundUserAssetsMapper.class,sqlSentence) != 1){
1097                 throw new TipsException("老带新资产退款记录状态已变化[作废]!");
1098             }
160383 1099         }
C 1100
1101     }
1102
1103         /**
1104          * 退款-处理活动规则增值金和积分
1105          * @param commonService 映射对象
1106          * @param operationId 操作人标识
1107          * @param operationNme 操作人名称
1108          * @param sqlSentence 映射对象
1109          * @param map 映射对象
1110          * @param refundRecord 退款记录
1111          * @param ordersTotal 订单
1112          * @param optType 操作:"0"减 1加
1113          */
edf5ea 1114     private static void handActivityRule(CommonService commonService, String operationId, String operationNme, SqlSentence sqlSentence,
Z 1115                                          Map<String, Object> map, RefundRecord refundRecord, OrdersTotal ordersTotal, OrderInfo orderInfo,int optType) {
1116         if(orderInfo!=null && StringUtils.noNull(orderInfo.getActivityId())){
1117             ActivityRule activityRule=commonService.selectOneByKeyBlob(ActivityRuleMapper.class,orderInfo.getActivityId());
1118             if(activityRule!=null){
1119                 map.put("activityRuleId",activityRule.getId());
1120                 map.put("type", ActivityAction.TYPE_INTEGRAL);
1121                 map.put("type1",ActivityAction.TYPE_VALUEADDEDFUND);
1122                 map.put("type2",ActivityAction.TYPE_COUPON);
4df03d 1123                 sqlSentence.sqlSentence("select * from activity_action where activityRuleId=#{m.activityRuleId} and (type=#{m.type} or type=#{m.type1} or type=#{m.type2}) and isDel=0",map);
edf5ea 1124                 List<ActivityAction> activityActions = commonService.selectList(ActivityActionMapper.class, sqlSentence);
Z 1125                 if(activityActions!=null && activityActions.size()>0){
1126                     for (ActivityAction activityAction : activityActions) {
1127                         if(ActivityAction.TYPE_INTEGRAL.equals(activityAction.getType())){
1128                             //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
1129                             if(new BigDecimal(activityAction.getWorth()).negate().compareTo(BigDecimal.ZERO)!=0){
1130                                 UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),optType==0?"充值单:"+ordersTotal.getOrderNo()+" 申请退款,预扣除活动规则赠送储值金金额:"+activityAction.getWorth():"充值单:"+ordersTotal.getOrderNo()+" 申请退款,拒绝审批,返还赠送储值金预扣除金额:"+activityAction.getWorth(),operationId,refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),optType==0?new BigDecimal(activityAction.getWorth()).negate():new BigDecimal(activityAction.getWorth()), UserMoneyUnclaimed.FUND_TYPE_INTEGRAL,OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.YES);
1131                             }
1132                         }else if(ActivityAction.TYPE_VALUEADDEDFUND.equals(activityAction.getType())){
1133                             //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
1134                             if(new BigDecimal(activityAction.getWorth()).negate().compareTo(BigDecimal.ZERO)!=0){
1135                                 UserMoneyUtil.setNewUserMoneyUnclaimed(refundRecord.getUserId(),refundRecord.getRemarks(),optType==0?"充值单:"+ordersTotal.getOrderNo()+" 申请退款,预扣除活动规则赠送增值金金额:"+activityAction.getWorth():"充值单:"+ordersTotal.getOrderNo()+" 申请退款,拒绝审批,返还赠送增值金预扣除金额:"+activityAction.getWorth(),operationId,refundRecord.getOrderId(),ordersTotal.getAppIdCode(),refundRecord.getId(),optType==0?new BigDecimal(activityAction.getWorth()).negate():new BigDecimal(activityAction.getWorth()), UserMoneyUnclaimed.FUND_TYPE_VALUE_ADDED_FUND,OperationReasonConstants.OP_REASON_RECHARGE_REFUND,commonService,UserMoneyUnclaimed.YES);
1136                             }
1137                         }else if(ActivityAction.TYPE_COUPON.equals(activityAction.getType())){
1138                             map.put("oldValidState",optType==0?BaseEntity.YES:BaseEntity.NO);
1139                             map.put("newValidState",optType==0?BaseEntity.NO:BaseEntity.YES);
1140                             map.put("couponId",activityAction.getCrmCouponId());
1141                             map.put("commonId",ordersTotal.getId());
4df03d 1142                             sqlSentence.sqlSentence(" validState=#{m.newValidState} where couponId=#{m.couponId} and commonId=#{m.commonId} and validState=#{m.oldValidState} ",map);
edf5ea 1143                             commonService.updateWhere(CouponNumberMapper.class,sqlSentence);
Z 1144                         }
1145                     }
1146                 }
1147             }
1148         }
9d4e6f 1149     }
4df03d 1150
da4ad2 1151     /**
Z 1152      * 对接审批
1153      */
42a0e7 1154     public PlatformResult handleApproval(OrdersNodeLog ordersNodeLog,StringBuilder orderNodeBuilder,OrdersTotal ordersTotal,CancelOrder cancelOrder,RefundRecord refundRecord){
25d452 1155         orderNodeBuilder.append("-退款需要审批,开始对接营销中心");
42a0e7 1156
Z 1157
1158         OrderPartRefundDto orderPartRefundDto=new OrderPartRefundDto();
1159         OrdersTotalDto ordersTotalDto=new OrdersTotalDto();
1160         BeanUtils.copyProperties(ordersTotal, ordersTotalDto);
1161
1162         orderPartRefundDto.setOrdersTotalDto(ordersTotalDto);//填充主订单信息
1163
1164
1165         //填充操作人,用户的基本信息
1166         orderPartRefundDto.setOrdersTotalDto(ordersTotalDto);
1167         orderPartRefundDto.setOperatorId(cancelOrder.getOperatorId());
1168         orderPartRefundDto.setOpName(cancelOrder.getOperatorName());
1169         orderPartRefundDto.setShopId(cancelOrder.getShopId());
1170         orderPartRefundDto.setShopName(cancelOrder.getShopName());
1171         orderPartRefundDto.setRoleId(cancelOrder.getRoleId());
1172         orderPartRefundDto.setRoleUniqueStr(cancelOrder.getRoleStr());
117ee9 1173         if(StringUtils.noNull(refundRecord.getRemarks())){
C 1174             orderPartRefundDto.setRemark(refundRecord.getRemarks());
1175         }else{
1176             orderPartRefundDto.setRemark(cancelOrder.getOperatorName()+"退款,订单号:"+ordersTotal.getOrderNo());
1177         }
1178
42a0e7 1179         orderPartRefundDto.setUserId(ordersTotal.getUserId());
Z 1180
1181         //本次退款金额
1182         orderPartRefundDto.setRefundTotal(refundRecord.getRefundTotal());
1183
832331 1184         //------本次退款支付方式
42a0e7 1185         SqlSentence sqlSentence = new SqlSentence();
Z 1186         Map<String,Object> map=new HashMap<>();
4df03d 1187
42a0e7 1188         map.put("refundRecordId", refundRecord.getId());
4df03d 1189         sqlSentence.sqlSentence("SELECT refundNumberNo AS payMethodNo,refundName AS payMethodName,actualTotal as refundMoney,refundRecordId as payMethodId FROM refund_record_method " +
C 1190                 " WHERE refundRecordId=#{m.refundRecordId} ",map);
42a0e7 1191         List<Map<String, Object>> refundMethodList = commonService.selectListMap(RefundRecordMethodMapper.class,sqlSentence);
Z 1192         if(refundMethodList!=null && refundMethodList.size()!=0){
1193             JSONArray refundMethodArray=new JSONArray();
1194             refundMethodArray.addAll(refundMethodList);
1195             List<PartRefundPayDto> partRefundPayDtoList=refundMethodArray.toJavaList(PartRefundPayDto.class);
1196             orderPartRefundDto.setPartRefundPayDtoList(partRefundPayDtoList);
1197         }
832331 1198         //-----本次退款项目
42a0e7 1199         //退款一级项目
4df03d 1200         sqlSentence.sqlSentence("SELECT type AS projectType, commonId AS projectId, goodsNo AS projectNo, goodsName AS projectName, refundNum AS refundNum  " +
C 1201                 " FROM refund_record_item WHERE refundRecordId=#{m.refundRecordId} AND refundNum>0",map);
42a0e7 1202         List<Map<String, Object>> refundRecordItemList = commonService.selectListMap(RefundRecordItemMapper.class,sqlSentence);
Z 1203         JSONArray refundProjectDtoArray=new JSONArray();
1204         if(refundRecordItemList!=null && refundRecordItemList.size()!=0){
1205             refundProjectDtoArray.addAll(refundRecordItemList);
1206         }
1207         //退款二级项目
4df03d 1208         sqlSentence.sqlSentence("SELECT type AS projectType, commonId AS projectId, goodsNo AS projectNo, goodsName AS projectName, refundNum AS refundNum " +
C 1209                 " FROM refund_record_item_source   WHERE refundRecordId=#{m.refundRecordId} AND refundNum>0",map);
42a0e7 1210         List<Map<String, Object>> refundRecordItemSourceList = commonService.selectListMap(RefundRecordItemSourceMapper.class,sqlSentence);
Z 1211         if(refundRecordItemSourceList!=null && refundRecordItemSourceList.size()!=0){
1212             refundProjectDtoArray.addAll(refundRecordItemSourceList);
1213         }
1214         if(refundProjectDtoArray.size()>0){
1215             List<RefundProjectDto> refundProjectDtoList=refundProjectDtoArray.toJavaList(RefundProjectDto.class);
1216             orderPartRefundDto.setRefundProjectDtoList(refundProjectDtoList);
1217         }
1218
1219
25d452 1220         logger.info("调用营销中心审批退款入参:{}",JSONObject.toJSONString(orderPartRefundDto));
909b33 1221         Result result= mOrderService.applyPartRefund(orderPartRefundDto);
Z 1222 //        Result result= JSONObject.parseObject("{\"code\":\"100\",\"msg\":\"SUCCESS\",\"data\":{\"applyId\":\"6204eb10753511ed90ed525400b8510a\"}}",Result.class);
25d452 1223         logger.info("调用营销中心审批退款返回:{}",JSONObject.toJSONString(result));
42a0e7 1224         if (result != null) {
Z 1225             result.checkTips();
1226             JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(result.getData()));
1227             if(!object.isEmpty()){
1228                 String applyId = object.getString("applyId");
1229                 cancelOrder.setApplyId(applyId);
b9b969 1230                 cancelOrder.setRefundRecordId(refundRecord.getId());
42a0e7 1231                 commonService.updateAll(CancelOrderMapper.class,cancelOrder);
Z 1232
542dc1 1233                 ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_APPLY);
42a0e7 1234                 commonService.updateAll(OrdersTotalMapper.class,ordersTotal);
Z 1235
5425ba 1236 //                logger.info("调用营销中心成功,订单开始审核");
Z 1237                 orderNodeBuilder.append("-调用营销中心成功,订单开始审核");
42a0e7 1238                 ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_REFUND);
Z 1239                 ordersNodeLog.setContent(orderNodeBuilder.toString());
1240                 ordersNodeLog.setOrderId(ordersTotal.getId());
1241                 commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
1242
1243                 orderNodeBuilder.append("-调用营销中心成功,订单开始审核");
1244
1245                 return PlatformResult.success("订单正在审核中");
1246             }else{
1247                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求营销助手审批接口报错,data返回为空!");
1248             }
1249         } else {
1250             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求营销助手审批接口报错,返回为空!");
1251         }
1252     }
1253
da4ad2 1254     /**
Z 1255      * 记录退款订单记录日志
1256      */
832331 1257     @Override
C 1258     public CancelOrder handleCancelOrder(OrdersTotal ordersTotal, OrderRefundDto orderRefundDto){
9d4e6f 1259         //记录取消日志
Z 1260         CancelOrder cancelOrder=new CancelOrder();
1261         cancelOrder.setOrderId(ordersTotal.getId());
2a45d4 1262         if(StringUtils.noNull(orderRefundDto.getOperatorId())){
C 1263             Employee employee = commonService.selectOneByKey(EmployeeMapper.class,orderRefundDto.getOperatorId());
1264             if(employee==null){
1265                 throw new TipsException("操作人标识错误!");
1266             }
9d4e6f 1267             cancelOrder.setOperatorId(employee.getId());
Z 1268             cancelOrder.setOperatorName(employee.getCnName());
1269         }
1270
2a45d4 1271         if(StringUtils.noNull(orderRefundDto.getRoleId())){
C 1272             EmployeeRole employeeRole=commonService.selectOneByKey(EmployeeRoleMapper.class,orderRefundDto.getRoleId());
1273             if(employeeRole==null){
1274                 throw new TipsException("操作角色标识错误!");
1275             }
9d4e6f 1276             cancelOrder.setRoleId(employeeRole.getRoleTypeId());
Z 1277             cancelOrder.setRoleStr(employeeRole.getRoleUniqueStr());
1278             Shop shop=commonService.selectOneByKey(ShopMapper.class,employeeRole.getShopId());
1279             if(shop==null){
1280                 cancelOrder.setShopId(employeeRole.getShopId());
1281                 cancelOrder.setShopName("找不到对应的门店");
1282             }else {
1283                 cancelOrder.setShopId(shop.getId());
1284                 cancelOrder.setShopName(shop.getName());
1285             }
1286         }
2a45d4 1287
9d4e6f 1288         cancelOrder.setIsApproval(orderRefundDto.getIsApproval());
Z 1289         cancelOrder.setIsRefund(orderRefundDto.getIsRefund());
1290         cancelOrder.setPlatformSource(orderRefundDto.getPlatformSource());
1291         commonService.insert(CancelOrderMapper.class,cancelOrder);
1292
1293         return cancelOrder;
1294     }
e3fa0c 1295
da4ad2 1296     /**
Z 1297      * 处理退款方式记录表
1298      */
4df03d 1299     public List<RefundRecordMethod> handleRefundPayMethod(OrderRefundDto orderRefundDto,StringBuilder orderNodeBuilder,OrdersTotal ordersTotal,RefundRecord refundRecord){
69ed11 1300         orderNodeBuilder.append("-记录退款方式:");
e3fa0c 1301
510678 1302         //获取订单可退款方式,就是支付方式总表的信息,已经支付编号求和
2a45d4 1303         List<PayMethodVo> payMethodVoList = refundMapper.getConsumePayGroupByNumberNo(ordersTotal.getId());
e3fa0c 1304
510678 1305         //用map装载,后面根据支付编号直接获取便可
C 1306         Map<String, PayMethodVo> payMethodVoMap = payMethodVoList.stream().collect(Collectors.toMap(PayMethodVo::getNumberNo,(a) -> a));
e3fa0c 1307
4df03d 1308         List<RefundRecordMethod> refundRecordMethodList = new ArrayList<>();
e3fa0c 1309
4df03d 1310         PayMethodVo payMethodVo;
510678 1311         RefundRecordMethod refundRecordMethod;
4df03d 1312         for (OrderPayMethodDto orderPayMethodDto : orderRefundDto.getRefundPayMethod()) {
e3fa0c 1313
4df03d 1314             payMethodVo = payMethodVoMap.get(orderPayMethodDto.getPayMethodNo());
C 1315             //判断是不是在支付方式里面的
1316             if (payMethodVo == null){
510678 1317                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"可退支付方式未找到:"+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]");
da4ad2 1318             }
ae6ff7 1319             //判断支付方式
4df03d 1320             PaymentMethod payMethod = paymentMethodService.selectNumberNoUncheckUp(orderPayMethodDto.getPayMethodNo());
C 1321             if(payMethod == null){
1322                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到对应的支付:"+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]");
e3fa0c 1323             }
4df03d 1324             //判断退款方式
C 1325             PaymentMethod refundMethod = paymentMethodService.selectNumberNoUncheckUp(orderPayMethodDto.getRefundNumberNo());
e3fa0c 1326             if(refundMethod==null){
ae6ff7 1327                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到退款方式:"+orderPayMethodDto.getRefundNumberName()+"["+orderPayMethodDto.getRefundNumberNo()+"]");
4df03d 1328             }
C 1329             if(orderPayMethodDto.getMoney() == null){
ae6ff7 1330                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请填写退款方式["+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]"+"]金额");
C 1331             }
1332             //判断金额
1333             if(payMethodVo.getSurplusTotal().compareTo(orderPayMethodDto.getMoney()) < 0){
1334                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款金额错误:"+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]");
e3fa0c 1335             }
da4ad2 1336
510678 1337             ////退款方式数据填充
4df03d 1338             refundRecordMethod = new RefundRecordMethod();
ae6ff7 1339             refundRecordMethod.setType(refundRecord.getSourceType());
510678 1340             refundRecordMethod.setActualTotal(orderPayMethodDto.getMoney());
C 1341             //支付方式信息
4df03d 1342             refundRecordMethod.setNumberNo(payMethod.getNumberNo());
C 1343             refundRecordMethod.setPaymentMethodId(payMethod.getId());
1344             refundRecordMethod.setName(payMethod.getName());
1345             refundRecordMethod.setIsMoneyPay(payMethodVo.getIsMoneyPay());
1346             refundRecordMethod.setIsExecute(payMethodVo.getIsExecute());
510678 1347             //退款方式信息
4df03d 1348             refundRecordMethod.setRefundNumberNo(refundMethod.getNumberNo());
C 1349             refundRecordMethod.setRefundName(refundMethod.getName());
1350             refundRecordMethod.setRefundMethodId(refundMethod.getId());
510678 1351
4df03d 1352             refundRecordMethod.setIsMoneyPayRefund(refundMethod.getIsMoneyPay());
C 1353             refundRecordMethod.setIsExecuteRefund(refundMethod.getIsExecute());
2a45d4 1354             refundRecordMethod.setRefundRecordId(refundRecord.getId());
C 1355             refundRecordMethod.setOrderId(ordersTotal.getId());
473d29 1356             refundRecordMethod.setRemarks(orderPayMethodDto.getRemarks());
4df03d 1357
C 1358             refundRecordMethodService.insert(refundRecordMethod);
1359             refundRecordMethodList.add(refundRecordMethod);
e3fa0c 1360         }
4df03d 1361         return refundRecordMethodList;
e3fa0c 1362     }
4df03d 1363
da4ad2 1364     /**
Z 1365      * 退款记录子项
1366      */
510678 1367     public void insertRefundRecordItem(OrderRefundDto orderRefundDto,StringBuilder orderNodeBuilder,RefundRecord refundRecord){
e3fa0c 1368
431d07 1369         orderNodeBuilder.append("-记录退款详情");
542dc1 1370
ae6ff7 1371         //计算金额占比,客户选择退款总金额和可退总金额占比
4df03d 1372         BigDecimal percentage;
C 1373         if(orderRefundDto.getTotalAmount().compareTo(BigDecimal.ZERO) < 1){
1374             percentage = BigDecimal.ZERO;
1375         }else {
1376             percentage = orderRefundDto.getRefundTotal().divide(orderRefundDto.getTotalAmount(),15,RoundingMode.HALF_UP);
1377         }
542dc1 1378
ae6ff7 1379         //总退款金额,用于后面计算分摊金额
4df03d 1380         BigDecimal refundTotal = refundRecord.getRefundTotal();
C 1381
ae6ff7 1382         //后面设计分配金额问题,要进行升序排序,避免到最后不够
C 1383         List<OrderItemRefundDto> refundList = orderRefundDto.getRefundList();
1384         refundList = refundList.stream().sorted(Comparator.comparing(OrderItemRefundDto::getApproveRefundTotal)).collect(Collectors.toList());
4df03d 1385
C 1386         /////引用参数
1387         RefundRecordItem refundRecordItem;
de3024 1388         OrderItemRefundDto orderItemRefundDto;
4df03d 1389         OrderItem orderItem;
ae6ff7 1390         for(int i = 0;i < refundList.size();i++){
C 1391             orderItemRefundDto = refundList.get(i);
de3024 1392
4df03d 1393             orderItem = orderItemMapper.selectOneByKey(orderItemRefundDto.getOrderItemId());
C 1394             if(orderItem == null){
1395                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"子订单标识错误!");
de3024 1396             }
Z 1397
4df03d 1398             //////数据填充
C 1399             refundRecordItem = new RefundRecordItem();
1400             refundRecordItem.setType(orderItem.getType());
1401             refundRecordItem.setGoodsNo(orderItem.getGoodsNo());
2a45d4 1402             refundRecordItem.setGoodsName(orderItem.getGoodsName());
4df03d 1403             refundRecordItem.setSpecs(orderItem.getSpecs());
C 1404             refundRecordItem.setCommonId(orderItem.getCommonId());
2a45d4 1405             if(PartialRefundUtil.CONTAIN_SON_TYPE_SET.contains(orderItem.getType())){
C 1406                 refundRecordItem.setRefundNum(0);
1407             }else{
1408                 refundRecordItem.setRefundNum(orderItemRefundDto.getRefundNum());
1409             }
4df03d 1410             refundRecordItem.setRefundRecordId(refundRecord.getId());
C 1411             refundRecordItem.setOrderItemId(orderItem.getId());
1412             refundRecordItem.setOccupyRefundTotal(orderItemRefundDto.getApproveRefundTotal());
77f162 1413             ////退款备注
C 1414             if(StringUtils.isEmpty(orderItemRefundDto.getRemarks())){
1415                 orderItemRefundDto.setRemarks(refundRecord.getRemarks());
1416             }
1417             if(StringUtils.isEmpty(orderItemRefundDto.getRefundReason())){
2a45d4 1418                 orderItemRefundDto.setRefundReason(orderItemRefundDto.getRefundReason());
77f162 1419             }
8eb9e6 1420             refundRecordItem.setRemarks(orderItemRefundDto.getRemarks());
C 1421             refundRecordItem.setRefundReason(orderItemRefundDto.getRefundReason());
4df03d 1422
ae6ff7 1423             //////////分配退款金额
C 1424             if(i == refundList.size()-1){
4df03d 1425                 refundRecordItem.setRefundMoney(refundTotal);
C 1426             }else{
1427                 refundRecordItem.setRefundMoney(orderItemRefundDto.getApproveRefundTotal().multiply(percentage).setScale(2,RoundingMode.UP));
1428             }
1429             if(refundRecordItem.getRefundMoney().compareTo(orderItemRefundDto.getApproveRefundTotal()) > 0){
1430                 refundRecordItem.setRefundMoney(orderItemRefundDto.getApproveRefundTotal());
1431             }
ae6ff7 1432             //判断与未分配剩余金额
4df03d 1433             if(refundRecordItem.getRefundMoney().compareTo(refundTotal) > 0){
C 1434                 refundRecordItem.setRefundMoney(refundTotal);
1435             }
2a45d4 1436
C 1437             refundRecordItem.setRealRefundNum(refundRecordItem.getRefundNum());
01fbcb 1438             refundRecordItem.setRealRefundTotal(refundRecordItem.getRefundMoney());
2a45d4 1439
da4ad2 1440             refundRecordItemService.insert(refundRecordItem);
510678 1441             //减去已经分配的退款金额
ae6ff7 1442             refundTotal = refundTotal.subtract(refundRecordItem.getRefundMoney()).setScale(2,RoundingMode.HALF_UP);
2a45d4 1443             if(PartialRefundUtil.CONTAIN_SON_TYPE_SET.contains(orderItem.getType())){
C 1444                 //子单子项处理
1445                 insertRefundRecordItemTwo(refundRecordItem,refundRecord,orderItemRefundDto.getOrderItemSourceRefundDtos());
1446             }
12025c 1447
253802 1448             //虚拟商品退款时需校验一下,对应关联的优惠券码有没有被使用或
20d569 1449             if(OrderItemConstants.TYPE_COUPON.equals(orderItem.getType())){
F 1450                 OrderVirtualGoodsUtil.orderApplyRefundHandle(commonService, orderItem, orderItemRefundDto.getRefundNum(), refundRecord.getOperatorId(), refundRecord.getOperatorName(), "p-his申请订单退款作废");
12025c 1451             }
e3fa0c 1452         }
4df03d 1453
1869f3 1454         if(refundTotal.compareTo(BigDecimal.ZERO) > 0){
C 1455             throw new TipsException("退款金额分配错误[01]!");
1456         }
1457
e3fa0c 1458     }
da4ad2 1459
4df03d 1460     /**二级子单处理*/
1869f3 1461     public void insertRefundRecordItemTwo(RefundRecordItem recordItem,RefundRecord refundRecord,List<OrderItemSourceRefundDto> orderItemSourceRefundDtos){
4df03d 1462         if(orderItemSourceRefundDtos == null || orderItemSourceRefundDtos.size() == 0){
da4ad2 1463             return;
Z 1464         }
ae6ff7 1465
C 1466         //计算占比
1467         BigDecimal percentage;
1468         if(recordItem.getOccupyRefundTotal().compareTo(BigDecimal.ZERO) > 0){
1469             percentage = recordItem.getRefundMoney().divide(recordItem.getOccupyRefundTotal(),15,RoundingMode.HALF_UP);
1470         }else{
1471             percentage = BigDecimal.ZERO;
1472         }
1473
1474         //进行升序排序,避免后面不够
1475         orderItemSourceRefundDtos = orderItemSourceRefundDtos.stream().sorted(Comparator.comparing(OrderItemSourceRefundDto::getApproveRefundTotal)).collect(Collectors.toList());
431d07 1476
4df03d 1477         //退款总金额
C 1478         BigDecimal refundTotal = recordItem.getRefundMoney();
da4ad2 1479
4df03d 1480         OrderItemSon orderItemSon;
C 1481         OrderItemSourceRefundDto orderItemSourceRefundDto;
1482         RefundRecordItemSource refundRecordItemSource;
1869f3 1483
4df03d 1484         for(int i = 0;i<orderItemSourceRefundDtos.size();i++){
C 1485             orderItemSourceRefundDto = orderItemSourceRefundDtos.get(i);
da4ad2 1486
4df03d 1487             orderItemSon = orderItemSonMapper.selectOneByKey(orderItemSourceRefundDto.getOrderItemSonId());
C 1488             if(orderItemSon == null){
1489                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"子订单标识错误[024]!");
1490             }
da4ad2 1491
4df03d 1492             //////数据填充
C 1493             refundRecordItemSource = new RefundRecordItemSource();
1494             refundRecordItemSource.setType(orderItemSon.getType());
1495             refundRecordItemSource.setGoodsNo(orderItemSon.getGoodsNo());
2a45d4 1496             refundRecordItemSource.setGoodsName(orderItemSon.getGoodsName());
4df03d 1497             refundRecordItemSource.setSpecs(orderItemSon.getSpecs());
C 1498             refundRecordItemSource.setCommonId(orderItemSon.getGoodsId());
1499             refundRecordItemSource.setRefundNum(orderItemSourceRefundDto.getRefundNum());
2a45d4 1500             refundRecordItemSource.setRefundRecordId(refundRecord.getId());
4df03d 1501             refundRecordItemSource.setOrderItemSonId(orderItemSon.getId());
C 1502             refundRecordItemSource.setOccupyRefundTotal(orderItemSourceRefundDto.getApproveRefundTotal());
2a45d4 1503             refundRecordItemSource.setRefundRecordItemId(recordItem.getId());
4df03d 1504             ////退款备注
C 1505             if(StringUtils.isEmpty(orderItemSourceRefundDto.getRemarks())){
1506                 orderItemSourceRefundDto.setRemarks(refundRecord.getRemarks());
1507             }
1508             if(StringUtils.isEmpty(orderItemSourceRefundDto.getRefundReason())){
2a45d4 1509                 orderItemSourceRefundDto.setRefundReason(refundRecord.getRefundReason());
4df03d 1510             }
C 1511             refundRecordItemSource.setRemarks(orderItemSourceRefundDto.getRemarks());
1512             refundRecordItemSource.setRefundReason(orderItemSourceRefundDto.getRefundReason());
da4ad2 1513
4df03d 1514             //计算退款金额
C 1515             if(i == orderItemSourceRefundDtos.size()-1){
1516                 refundRecordItemSource.setRefundMoney(refundTotal);
1517             }else{
1518                 refundRecordItemSource.setRefundMoney(orderItemSourceRefundDto.getApproveRefundTotal().multiply(percentage).setScale(2,RoundingMode.UP));
1519             }
1520             if(refundRecordItemSource.getRefundMoney().compareTo(orderItemSourceRefundDto.getApproveRefundTotal()) > 0){
1521                 refundRecordItemSource.setRefundMoney(orderItemSourceRefundDto.getApproveRefundTotal());
1522             }
1523             if(refundRecordItemSource.getRefundMoney().compareTo(refundTotal) > 0){
1524                 refundRecordItemSource.setRefundMoney(refundTotal);
1525             }
2a45d4 1526
C 1527             refundRecordItemSource.setRealRefundNum(refundRecordItemSource.getRefundNum());
1528             refundRecordItemSource.setRealRefundTotal(refundRecordItemSource.getRefundMoney());
1529
4df03d 1530             refundRecordItemSourceMapper.insert(refundRecordItemSource);
ae6ff7 1531             //减去已经分配退款金额
C 1532             refundTotal = refundTotal.subtract(refundRecordItemSource.getRefundMoney()).setScale(2,RoundingMode.HALF_UP);
1869f3 1533         }
b2b4a4 1534
1869f3 1535         if(refundTotal.compareTo(BigDecimal.ZERO) > 0){
C 1536             throw new TipsException("退款金额分配错误[02]!");
431d07 1537         }
da4ad2 1538
431d07 1539     }
e3fa0c 1540
da4ad2 1541     /**
Z 1542      * 记录退款记录优惠卷
1543      */
e3fa0c 1544     public void handleOrderCouponRefunDto(List<OrderCouponRefunDto> couponList,StringBuilder orderNodeBuilder,OrdersTotal ordersTotal,RefundRecord refundRecord){
510678 1545         CouponOrderDiscountLog couponOrderDiscountLog;
C 1546         RefundRecordCoupon refundRecordCoupon;
e3fa0c 1547         orderNodeBuilder.append("-处理退款优惠卷");
Z 1548         for (OrderCouponRefunDto orderCouponRefunDto : couponList) {
1549             couponOrderDiscountLog=couponOrderDiscountLogMapper.selectOneByKey(orderCouponRefunDto.getOrderCouponId());
510678 1550             if( couponOrderDiscountLog == null){
4df03d 1551                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单优惠卷标识不正确");
e3fa0c 1552             }
Z 1553             refundRecordCoupon=new  RefundRecordCoupon(ordersTotal.getId(),refundRecord.getId(),ordersTotal.getUserId(),1,1,couponOrderDiscountLog.getId(),
1554                     couponOrderDiscountLog.getCouponId(),couponOrderDiscountLog.getTitle(),couponOrderDiscountLog.getCouponNumberId());
1555             refundRecordCouponMapper.insert(refundRecordCoupon);
1556         }
1557     }
1558
1559
1560
4df03d 1561     /**真正退款,是对钱和状态的回退到账开始操作
da4ad2 1562      * 进行退款操作,退款用户项目,商品,促销,卡项,卡包
Z 1563      */
3badb7 1564     @Override
a1c527 1565     public Map<String,Object> handleRefundOrder(Map<String, String> operator,RefundRecord refundRecord,OrdersTotal ordersTotal
C 1566             ,OrdersNodeLog ordersNodeLog,StringBuilder orderNodeBuilder,CancelOrder cancelOrder ){
c04e8a 1567
4dc6e5 1568         String operationId=operator.get("operatorId");
Z 1569         String operatorName=operator.get("operatorName");
c04e8a 1570
46bedb 1571         orderNodeBuilder.append("-处理退款支付方式,用户待执行项目");
ae6ff7 1572         //处理主业务
510678 1573         ordersTotal =  PartialRefundUtil.refundProcess(commonService, operationId, operatorName, refundRecord.getId());
c04e8a 1574
4dc6e5 1575         //返回数据
Z 1576         Map<String,Object> data=new HashMap<>();
1577         data.put("refundRecordId",refundRecord.getId());
1578         data.put("refundRecordCode",refundRecord.getCode());
16790d 1579
da4ad2 1580         //处理次业务,报错不影响主业务
ae6ff7 1581         refundRecord = refundRecordService.selectOneByKey(refundRecord.getId());
C 1582
478fa9 1583         //用户升降级(调用航爷) 金额=用户支付的实付现金金额(不包含储值金)
f13adb 1584         SqlSentence sqlSentence = new SqlSentence();
Z 1585         Map<String,Object> map=new HashMap<>();
1586         sqlSentence.setM(map);
1587         //退款成功
1588         map.put("refundRecordId", refundRecord.getId());
4df03d 1589         sqlSentence.sqlSentence("SELECT CAST(COALESCE(sum(rrm.realRefundTotal),0) as  DECIMAL(11,2))  as total FROM refund_record_method rrm LEFT JOIN payment_method pm ON pm.numberNo=rrm.refundNumberNo " +
C 1590                 "WHERE rrm.refundRecordId=#{m.refundRecordId} and pm.isMoneyPay=1",map);
f13adb 1591         Map<String,Object> totalMap =commonService.selectOneMap(RefundRecordMethodMapper.class,sqlSentence);
Z 1592         BigDecimal total=new BigDecimal(String.valueOf(totalMap.get("total"))) ;
1593         if(BigDecimal.ZERO.compareTo(total) < 0){
1594             try {
2a45d4 1595                 orderNodeBuilder.append("-开始处理用户升降级,金额:").append(total.negate());
26ebce 1596                 UserLevelUtil.refund(userLevelRuleService, ordersTotal.getUserId(),ordersTotal.getId(),total.negate(),ordersTotal.getAppIdCode());
16790d 1597                 orderNodeBuilder.append("-处理用户升降级成功");
f13adb 1598             }catch (Exception e){
Z 1599                 String snapshot="处理用户升降级失败";
2a45d4 1600                 orderNodeBuilder.append("-处理用户升降级失败,异常原因:").append(e.getMessage());
f13adb 1601                 logger.error("处理用户升降级失败:" + e.getMessage());
Z 1602                 //发送企业微信通知给工作人员
1603                 SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),snapshot,commonService,customParameter);
1604             }
1605         }
edf5ea 1606
46bedb 1607         //记录操作日志
Z 1608         orderNodeBuilder.append("-记录操作日志");
478fa9 1609         StringBuffer stringBuffer = new StringBuffer("操作人:"+operator.get("operatorName")+",进行退款");
46bedb 1610         OrderLog orderLog=new OrderLog(ordersTotal.getId(), OrderLogConstants.LOG_TYPE_REFUND,stringBuffer.toString()
Z 1611                 ,operator.get("operatorName"),operator.get("operatorId"),OrderTotalConstants.STATUS_CANCEL);
1612         commonService.insert(OrderLogMapper.class,orderLog);
1613
1614         orderNodeBuilder.append("-结束处理退款");
1615         ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_REFUND);
1616         ordersNodeLog.setContent(orderNodeBuilder.toString());
1617         ordersNodeLog.setOrderId(ordersTotal.getId());
1618         commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
1619
260188 1620         //第三方最后执行
C 1621         if(CancelOrderDto.HIS_ASSISTANT.equals(cancelOrder.getPlatformSource())){
1622             //如果是his自动处理退款单原路退回
1623             //CRM的操作也在这里
1624             hisAssistantNoteList(ordersTotal,refundRecord,operationId,orderNodeBuilder);
1625         }
1626
f23452 1627         //撤销【保妥适会员】标签
W 1628         ClubEquityTool.refundCancelLabel(commonService,sUserTagInfoService,ordersTotal,botoxClubConfig.getLabelTypeNo(),botoxClubConfig.getLabelNo());
1629
4dc6e5 1630         return data;
c38ec7 1631     }
277835 1632     /**
Z 1633      * his助手原路退回退款单
1634      */
7d7f9e 1635     public void hisAssistantNoteList(OrdersTotal ordersTotal,RefundRecord refundRecord,String operationId,StringBuilder orderNodeBuilder){
5c26f4 1636         OrderRefundNoteListDto orderRefundNoteListDto=new OrderRefundNoteListDto();
W 1637         orderRefundNoteListDto.setOperationId(operationId);
1638         orderRefundNoteListDto.setOrderId(ordersTotal.getId());
a0d15f 1639
f3ff4e 1640         //获取退款信息
277835 1641         SqlSentence sqlSentence = new SqlSentence();
Z 1642         Map<String,Object> map=new HashMap<>();
f3ff4e 1643
C 1644         //获取总退款方式
7d7f9e 1645         map.put("refundRecordId",refundRecord.getId());
f3ff4e 1646         sqlSentence.sqlSentence("SELECT * FROM refund_record_method WHERE isDel = 0 AND refundRecordId = #{m.refundRecordId}",map);
C 1647         List<RefundRecordMethod> refundRecordMethodList = commonService.selectList(RefundRecordMethodMapper.class,sqlSentence);
1648         if(refundRecordMethodList.size() == 0){
277835 1649             return;
Z 1650         }
1651
f3ff4e 1652         //组装数据,只有现金才生成
277835 1653         List<OrderRefundNoteDto> orderRefundNoteDtos=new ArrayList<>();
Z 1654         OrderRefundNoteDto orderRefundNoteDto;
f3ff4e 1655         for (RefundRecordMethod refundRecordMethod : refundRecordMethodList) {
C 1656             //是现金
f3a00b 1657             if(!refundRecordMethod.getIsMoneyPay().equals(BaseEntity.YES)){
f3ff4e 1658                 continue;
260188 1659             }
f3ff4e 1660             orderRefundNoteDto = new OrderRefundNoteDto();
C 1661             //退款,是否原路退回
1662             if(refundRecordMethod.getNumberNo().equals(refundRecordMethod.getRefundNumberNo())){
1663
260188 1664                 orderRefundNoteDto.setRefundroute(1);
C 1665             }else{
1666                 orderRefundNoteDto.setRefundroute(0);
1667             }
f3ff4e 1668             orderRefundNoteDto.setRefundRecordMethodId(refundRecordMethod.getId());
C 1669             orderRefundNoteDto.setPaymentTotal(refundRecordMethod.getActualTotal());
1670             orderRefundNoteDto.setPaymentNumberNo(refundRecordMethod.getNumberNo());
1671             orderRefundNoteDto.setPaymentName(refundRecordMethod.getName());
1672             orderRefundNoteDto.setRefundNumberNo(refundRecordMethod.getRefundNumberNo());
1673             orderRefundNoteDto.setRefundName(refundRecordMethod.getRefundName());
277835 1674             orderRefundNoteDtos.add(orderRefundNoteDto);
Z 1675         }
1676         orderRefundNoteListDto.setOrderRefundNoteDtos(orderRefundNoteDtos);
1677
7d7f9e 1678         noteConfirm(orderRefundNoteListDto, ordersTotal,refundRecord,orderNodeBuilder);
254bde 1679     }
4df03d 1680
f3ff4e 1681     public void noteConfirm(OrderRefundNoteListDto orderRefundNoteListDto,OrdersTotal ordersTotal,RefundRecord refundRecord
7d7f9e 1682             ,StringBuilder orderNodeBuilder) {
260188 1683         logger.info("退款单确认打印参数:{}",JSON.toJSONString(orderRefundNoteListDto));
254bde 1684         Map<String, String> operator = ApiOrderUtil.getOperator(commonService, orderRefundNoteListDto.getOperationId());//获取操作人信息
Z 1685         String operatorId= operator.get("operatorId");
1686         String operatorName=  operator.get("operatorName");
1687
1688
1689         SqlSentence sqlSentence = new SqlSentence();
1690         Map<String,Object> map=new HashMap<>();
1691         sqlSentence.setM(map);
1692
1693         List<OrderRefundNoteDto> orderRefundNoteDtos=orderRefundNoteListDto.getOrderRefundNoteDtos();
f3ff4e 1694         if(orderRefundNoteDtos == null || orderRefundNoteDtos.size() == 0){
C 1695             return;
1696         }
254bde 1697         if("crm".equals(ordersTotal.getAppIdCode())){
4df03d 1698             //CRM退款
7d7f9e 1699             handleCrmRefundOrder(orderRefundNoteDtos,ordersTotal,refundRecord,operatorId,operatorName,orderNodeBuilder);
254bde 1700         }else {
f3ff4e 1701             RefundCashVo refundCashVo = new RefundCashVo();
C 1702             refundCashVo.setOrderId(ordersTotal.getId());
1703             refundCashVo.setRemark(refundRecord.getRemarks());
1704             List<RefundCashItemVo> refundCashItemVoList = new ArrayList<>();
1705             RefundCashItemVo refundCashItemVo;
254bde 1706             for (OrderRefundNoteDto orderRefundNoteDto : orderRefundNoteDtos) {
f3ff4e 1707                 if(BaseEntity.YES.equals(orderRefundNoteDto.getRefundroute())){
C 1708                     refundCashItemVo = new RefundCashItemVo();
1709                     refundCashItemVo.setPaymentNo(orderRefundNoteDto.getRefundNumberNo());
1710                     refundCashItemVo.setRefundTotal(orderRefundNoteDto.getPaymentTotal());
1711                     refundCashItemVo.setRefundRecordId(refundRecord.getId());
1712                     refundCashItemVo.setRefundRecordMethodId(orderRefundNoteDto.getRefundRecordMethodId());
1713                     refundCashItemVoList.add(refundCashItemVo);
1714                 }
254bde 1715             }
f3ff4e 1716             refundCashVo.setRefundCashItemVoList(refundCashItemVoList);
88585a 1717             logger.info("支付退款-ordersTotal.getAppIdCode():{}",ordersTotal.getAppIdCode());
C 1718             logger.info("支付退款-refundCashVo:{}",JSON.toJSONString(refundCashVo));
50ba2e 1719             //开始退款 2023-09-06暂时屏蔽线上退款
C 1720             //refundCash(refundRecord.getId(),refundCashVo);
254bde 1721         }
Z 1722
1723         //记录操作日志
1724         StringBuffer stringBuffer=new StringBuffer("操作人:"+operator.get("operatorName")+",已支付订单现金支付退款:");
1725         OrderLog orderLog=new OrderLog(ordersTotal.getId(),OrderLogConstants.LOG_TYPE_CANCEL_ORDER,stringBuffer.toString()
1726                 ,operator.get("operatorName"),operator.get("operatorId"),OrderTotalConstants.STATUS_CANCEL);
1727         commonService.insert(OrderLogMapper.class,orderLog);
1728
1729     }
4df03d 1730     /**处理crm退款*/
7d7f9e 1731     public void handleCrmRefundOrder(List<OrderRefundNoteDto> orderRefundNoteDtos,OrdersTotal ordersTotal,RefundRecord refundRecord
C 1732             ,String operatorId, String operatorName,StringBuilder orderNodeBuilder){
254bde 1733         SqlSentence sqlSentence = new SqlSentence();
Z 1734         Map<String,Object> map=new HashMap<>();
1735         sqlSentence.setM(map);
1736
1737         //待确认
1738         BigDecimal crmAmount = orderRefundNoteDtos.stream().filter(item->RefundNote.ORIGINAL_ROAD.equals(item.getRefundroute())).map(o->o.getPaymentTotal())
1739                 .reduce(BigDecimal.ZERO,BigDecimal::add);
1740         List<RefundAmountModelDto> amountModelList=new ArrayList<>();
1741         RefundAmountModelDto refundAmountModelDto;
1742         for (OrderRefundNoteDto orderRefundNoteDto : orderRefundNoteDtos) {
1743             if(RefundNote.ORIGINAL_ROAD.equals(orderRefundNoteDto.getRefundroute())){
1744                 refundAmountModelDto=new RefundAmountModelDto();
260188 1745                 refundAmountModelDto.setRefundType(PayMethodTypeConstants.PAY_CRM_WX.equals(orderRefundNoteDto.getRefundNumberNo()) ?0:1);
254bde 1746                 refundAmountModelDto.setAmountTotal(orderRefundNoteDto.getPaymentTotal());
Z 1747                 amountModelList.add(refundAmountModelDto);
1748             }
1749         }
1750         logger.info("退款金额:{}",crmAmount);
832331 1751         if(0 < crmAmount.compareTo(BigDecimal.ZERO)){
254bde 1752             RefundDto refundDto=new RefundDto();
Z 1753             refundDto.setRefundOrderType(0);
1754             refundDto.setOrderId(ordersTotal.getId());
1755             refundDto.setRefundType(0);
1756             refundDto.setRefundAmountTotal(crmAmount);
1757             refundDto.setRefundRecharge(new BigDecimal(0));
1758             refundDto.setRefundIncrement(new BigDecimal(0));
1759             refundDto.setRefundIntegral(new BigDecimal(0));
1760             refundDto.setIsWholeOrder(0);
1761             refundDto.setRemarks("phis退款单退款,订单号:"+ordersTotal.getOrderNo());
1762             refundDto.setAmountModelList(amountModelList);
ed65d6 1763             refundDto.setOperatorId(operatorId);
W 1764             refundDto.setOperatorName(operatorName);
1765             if(OrderTotalConstants.STATUS_REFUND_FINSH==ordersTotal.getRefundStatus() &&
1766                     OrderTotalConstants.STATUS_CANCEL == ordersTotal.getStatus()){
af0ab2 1767                 //全部退款完成则取消订单
W 1768                 refundDto.setIsCancelOrder(BaseEntity.YES);
1769             }
1770
254bde 1771             logger.info("调用crm退款入参:{}",JSONObject.toJSONString(refundDto));
Z 1772             Result result= fOderService.refundOrder(refundDto);;
1773             logger.info("调用crm退款返回:{}",JSONObject.toJSONString(result));
1774             if (result != null) {
1775                 result.checkTips();
edf5ea 1776                 if("100".equals(result.getCode())){
254bde 1777                     RefundReturnDto refundReturnDto=JSON.parseObject(JSONObject.toJSONString(result.getData()),RefundReturnDto.class);
7d7f9e 1778                     if (RefundReturnDto.REFUND_STATUS_SUECCESS == refundReturnDto.getRefundStatus()){
edf5ea 1779                         orderNodeBuilder.append("-调用CRM退款金额:"+crmAmount+",返回成功返回流水号:"+refundReturnDto.getRefundNo()+",json:"+result);
254bde 1780                         logger.info("crm退款成功进行下面操作");
Z 1781                     }else {
5a8c60 1782                         //throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求crm退款接口报错,退款失败!退款状态不是成功状态");
W 1783                         throw new PlatTipsException(PlatformCode.ERROR_TIPS,"非常抱歉,当前公司财务账号金额不足无法进行退款,请稍后再试。如急需退款,请退[储值金] 在走oa申请线下退款。");
254bde 1784                     }
d095b1 1785                     //生成CRM回执记录
C 1786                     createCrmRefundReceipt(refundReturnDto,refundRecord,commonService);
254bde 1787                 }else{
55dbe8 1788                     throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求crm退款接口报错,接口返回错误!:code不是100");
254bde 1789                 }
Z 1790             } else {
1791                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求crm退款接口报错,返回为空!");
1792             }
1793
1794         }
edf5ea 1795
f3ff4e 1796         try{
C 1797             //退款成功发送企业微信给订单开单人
1798             JSONObject object = new JSONObject();
1799             object.put("abnormal","订单退款成功,现金支付资产已退回!");
1800             object.put("orderNo",ordersTotal.getOrderNo());
1801             User user=commonService.selectOneByKeyBlob(UserMapper.class,ordersTotal.getUserId());
1802             object.put("userName",user==null?"":user.getName());
1803             object.put("notificationSubject", NotificationLog.NOTIFICATION_SUBJECT_REFUND_NOTE_PHISKIN_SUC_NOTICE);
1804             SendNoticeUtil.successOrderSendNotice(commonService, customParameter, ordersTotal,object);
1805         }catch (Exception e){
1806             logger.error("退款成功发送企业微信给订单开单人错误:",e);
254bde 1807         }
277835 1808     }
9d4e6f 1809
e3fa0c 1810     /**
d095b1 1811      * 生成CRM退款回执
C 1812      * @param refundReturnDto crm退款返回总结构
1813      * @param refundRecord 退款总单
1814      * @param commonService 映射
1815      */
1816     public static void createCrmRefundReceipt(RefundReturnDto refundReturnDto,RefundRecord refundRecord,CommonService commonService){
1817         try{
1818             if (RefundReturnDto.REFUND_STATUS_SUECCESS==refundReturnDto.getRefundStatus()
1819                     ||RefundReturnDto.REFUND_STATUS_PART==refundReturnDto.getRefundStatus()){
1820                 StringBuilder crmReturnData = new StringBuilder();
1821                 crmReturnData.append("<p>【CRM退款】</p>");
1822                 crmReturnData.append("<p>CRM退款流水号:").append(refundReturnDto.getRefundNo()).append("</p>");
1823                 crmReturnData.append("<p>已退款总金额:");
1824                 crmReturnData.append(refundReturnDto.getRefundTotal());
1825                 crmReturnData.append(";");
ac3d6e 1826                 crmReturnData.append("已退款其他金额:");
C 1827                 crmReturnData.append(refundReturnDto.getRefundAmountTotal());
1828                 crmReturnData.append(";");
d095b1 1829                 crmReturnData.append("已退款储值金:");
C 1830                 crmReturnData.append(refundReturnDto.getRefundRecharge());
1831                 crmReturnData.append(";");
1832                 crmReturnData.append("已退款增值金:");
1833                 crmReturnData.append(refundReturnDto.getRefundIncrement());
1834                 crmReturnData.append(";");
1835                 crmReturnData.append("已退款积分:");
1836                 crmReturnData.append(refundReturnDto.getRefundIntegral());
1837                 crmReturnData.append("</p>");
1838                 crmReturnData.append("<p>退款方式:</p>");
1839                 if(refundReturnDto.getRefundAmountModelDtoList() != null && refundReturnDto.getRefundAmountModelDtoList().size() > 0){
1840                     for(RefundAmountModelDto refundAmountModelDto1:refundReturnDto.getRefundAmountModelDtoList()){
1841                         crmReturnData.append("<p>");
1842                         switch (refundAmountModelDto1.getRefundType()){
1843                             case RefundAmountModelDto.REFUND_TYPE_WX:
1844                                 crmReturnData.append("微信[CRM]:").append(refundAmountModelDto1.getAmountTotal());
1845                                 break;
1846                             case RefundAmountModelDto.REFUND_TYPE_ZFB:
1847                                 crmReturnData.append("支付宝[CRM]:").append(refundAmountModelDto1.getAmountTotal());
1848                                 break;
1849                             default:
1850                                 crmReturnData.append("[").append(refundAmountModelDto1.getRefundType()).append("]");
1851                                 crmReturnData.append("未知方式[CRM]:").append(refundAmountModelDto1.getAmountTotal());
1852                         }
1853                         crmReturnData.append("</p>");
1854                     }
1855                 }
1856                 RefundRecordReceipt refundRecordReceipt = new RefundRecordReceipt();
a2bbf7 1857                 refundRecordReceipt.setReceiptSource(RefundRecordReceipt.RECEIPT_SOURCE_CRM);
C 1858                 refundRecordReceipt.setReceiptSourceNo(refundReturnDto.getRefundNo());
1859                 refundRecordReceipt.setReceiptSourceData(JSON.toJSONString(refundReturnDto));
d095b1 1860                 refundRecordReceipt.setReceiptType(RefundRecordReceipt.RECEIPT_TYPE_REFUND);
C 1861                 refundRecordReceipt.setRemarks(crmReturnData.toString());
1862                 refundRecordReceipt.setOperatorId(refundRecord.getOperatorId());
1863                 refundRecordReceipt.setOperatorNo(refundRecord.getOperatorNo());
1864                 refundRecordReceipt.setOperatorName(refundRecord.getOperatorName());
1865                 refundRecordReceipt.setRefundRecordId(refundRecord.getId());
1866                 commonService.insert(RefundRecordReceiptMapper.class,refundRecordReceipt);
1867             }
1868         }catch (Exception e){
1869             logger.error("退款生成CRM回执报错:{}",e);
1870         }
1871     }
1872
1873     /**
e3fa0c 1874      * 营销中心回调审批处理接口
Z 1875      * @param aduitDto
1876      * @return
1877      */
b9b969 1878     @Override
Z 1879     public PlatformResult partRefundApproval(AduitDto aduitDto) {
25d452 1880         logger.info("营销中心审批退款入参:{}",JSON.toJSONString(aduitDto));
b9b969 1881         SqlSentence sqlSentence = new SqlSentence();
Z 1882         Map<String,Object> map=new HashMap<>();
1883         sqlSentence.setM(map);
1884         map.put("applyId",aduitDto.getApplyId());
4df03d 1885         sqlSentence.sqlSentence("SELECT * FROM cancel_order WHERE applyId=#{m.applyId} and isDel=0 ",map);
b9b969 1886         CancelOrder cancelOrder=commonService.selectOne(CancelOrderMapper.class,sqlSentence);
61a0db 1887         if( cancelOrder == null ){
b9b969 1888             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该审核标识");
Z 1889         }
c04e8a 1890         if(!CancelOrder.PENDING.equals(cancelOrder.getApprovalstatus())){
79f8fb 1891             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"该条审核标识已经处理过了,不要重复提交");
Z 1892         }
1893
edf5ea 1894         Map<String, String> operator=new HashMap<>();
Z 1895         operator.put("operatorId",cancelOrder.getOperatorId());
1896         operator.put("operatorName",cancelOrder.getOperatorName());
1897
b9b969 1898         //先判断项目的状态是否存在
c04e8a 1899         OrdersTotal ordersTotal= ordersTotalMapper.selectOneByKey(cancelOrder.getOrderId());
C 1900         if(ordersTotal==null){
1901             logger.info("取消订单流程:未找到总订单信息!订单id:{}",cancelOrder.getOrderId());
1902             return PlatformResult.failure(PlatformCode.ERROR_TIPS,"取消订单流程:未找到总订单信息!");
b9b969 1903         }
c04e8a 1904         
b9b969 1905         cancelOrder.setExamEmplId(aduitDto.getExamEmplId());
Z 1906         cancelOrder.setExamEmplName(aduitDto.getExamEmplName());
1907
c04e8a 1908         //获取退款记录
C 1909         RefundRecord refundRecord = commonService.selectOneByKey(RefundRecordMapper.class,cancelOrder.getRefundRecordId());
97a5fc 1910         if(refundRecord==null){
25d452 1911             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该审核的退款记录");
97a5fc 1912         }
Z 1913
160383 1914         //订单节点日志
C 1915         OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
1916         StringBuilder orderNodeBuilder = new StringBuilder();
1917
c04e8a 1918         if(BaseEntity.NO.equals(aduitDto.getType())){
160383 1919
C 1920             orderNodeBuilder.append("审核不通过");
1921             orderNodeBuilder.append("-最后审核人:").append(aduitDto.getExamEmplName());
1922
c04e8a 1923             //审核不通过
3badb7 1924             map.put("id",cancelOrder.getId());
C 1925             map.put("approvalstatus",CancelOrder.FAIL);
1926             map.put("approvalstatusOld",CancelOrder.PENDING);
1927             map.put("editTime",new Date());
1928             sqlSentence.sqlUpdate("approvalstatus = #{m.approvalstatus},editTime = #{m.editTime} WHERE id = #{m.id} AND approvalstatus = #{m.approvalstatusOld}",map);
1929             if(commonService.updateWhere(CancelOrderMapper.class,sqlSentence)!=1){
1930                 throw new TipsException("审核失败,审核状态已变更!");
1931             }
909b33 1932
df3f90 1933             //更改总订单退款状态
Z 1934             map.put("orderId",ordersTotal.getId());
4df03d 1935             sqlSentence.sqlSentence("select * from order_item WHERE  orderId=#{m.orderId} and isDel=0",map);
df3f90 1936             List<OrderItem> orderItemList=commonService.selectList(OrderItemMapper.class,sqlSentence);
Z 1937
832331 1938             List<Integer> collect = orderItemList.stream().map(OrderItem::getRefundStatus).collect(Collectors.toList());
df3f90 1939             if(collect.contains(OrderTotalConstants.STATUS_REFUND_PART)){
Z 1940                 ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
c04e8a 1941             }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE)
C 1942                     && collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
df3f90 1943                 ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
Z 1944             }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE)){
1945                 ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
c9f92c 1946             }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
df3f90 1947                 ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_FINSH);
c9f92c 1948             }else {
Z 1949                 ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
df3f90 1950             }
Z 1951
1952             map.put("refundStatus",ordersTotal.getRefundStatus());
909b33 1953             map.put("id",ordersTotal.getId());
4df03d 1954             sqlSentence.sqlSentence(" refundStatus=#{m.refundStatus}  WHERE id=#{m.id}  ",map);
909b33 1955             ordersTotalMapper.updateWhere(sqlSentence);
Z 1956
3badb7 1957             //退款单信息变更
C 1958             map.put("id",refundRecord.getId());
1959             map.put("refundStatus",RefundStatus.STATUS_INVALID_REFUND);
1960             map.put("refundStatusOld",RefundStatus.STATUS_APPLY_REFUND);
1961             map.put("editTime",new Date());
1962             sqlSentence.sqlUpdate("refundStatus = #{m.refundStatus},editTime = #{m.editTime} WHERE id = #{m.id} AND refundStatus = #{m.refundStatusOld}",map);
1963             if(commonService.updateWhere(RefundRecordMapper.class,sqlSentence) != 1){
1964                 throw new TipsException("审核失败,退款单状态已发生变更!");
1965             }
f5e288 1966
C 1967             //先赋值该作废操作人,后面会用到,注意,这里不存储
1968             refundRecord.setInvalidId(refundRecord.getOperatorId());
1969             refundRecord.setInvalidName(refundRecord.getInvalidName());
1970             refundRecord.setInvalidNo(refundRecord.getOperatorNo());
1971             refundRecord.setInvalidAppId(refundRecord.getOperatorAppId());
1972             refundRecord.setInvalidAppName(refundRecord.getOperatorAppName());
1973
160383 1974             //处理老带新的佣金,没有退款才退
C 1975             if(ordersTotal.getRefundStatus() == OrderTotalConstants.STATUS_REFUND_NONE){
1976                 oldBlingNewRefundFail(refundRecord,orderNodeBuilder,commonService);
1977             }
1978
edf5ea 1979             //拒绝审批需要还原回去储值金
Z 1980             //判断是否是充值订单,是的话需要把前面预扣的还原
bf63c3 1981             if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
edf5ea 1982                 //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
f5e288 1983                 //充值金额
b3fdea 1984                 OrderRefundCancelTool.rechargeHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_CANCEL,"拒绝审批",orderNodeBuilder,commonService);
edf5ea 1985             }
f5e288 1986             //活动规则退款处理
b3fdea 1987             OrderRefundCancelTool.activityRuleHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_CANCEL,"拒绝审批",orderNodeBuilder,commonService);
edf5ea 1988
160383 1989             ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_REFUND);
C 1990             ordersNodeLog.setContent(orderNodeBuilder.toString());
1991             ordersNodeLog.setOrderId(ordersTotal.getId());
1992             commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
1993
1994
b9b969 1995             return PlatformResult.success("拒绝取消审核通过");
Z 1996         }
c04e8a 1997
C 1998         cancelOrder.setEditTime(new Date());
1999         cancelOrder.setApprovalstatus(CancelOrder.SUCCESS);
2000         commonService.updateAll(CancelOrderMapper.class,cancelOrder);
97a5fc 2001
b9b969 2002         orderNodeBuilder.append("审核通过,开始处理退款");
Z 2003
edf5ea 2004
277835 2005         Map<String, Object>refund =handleRefundOrder(operator,refundRecord,ordersTotal,ordersNodeLog,orderNodeBuilder,cancelOrder);
b9b969 2006         return PlatformResult.success(refund);
Z 2007     }
df3f90 2008
Z 2009
97a5fc 2010     /**
Z 2011      * 全部退款处理退款逻辑
832331 2012      * @param orderRefundDto 退款信息
C 2013      * @return 结果
97a5fc 2014      */
Z 2015     @Override
4df03d 2016     public PlatformResult wholeRefund(OrderRefundDto orderRefundDto,ThirtApplication thirtApplication) {
97a5fc 2017
118d96 2018         OrdersTotal ordersTotal = ordersTotalMapper.selectOneByKey(orderRefundDto.getOrderId());
C 2019
d68a60 2020         OrderRefundDto parameter = getWholeRefundInfo(orderRefundDto, ordersTotal);
F 2021
2022         //调用退款处理退款逻辑
2023         return partRefund(ordersTotal,parameter,thirtApplication);
2024     }
2025
2026     /** 获取全部退款的详细信息 */
832331 2027     @Override
d68a60 2028     public OrderRefundDto getWholeRefundInfo(OrderRefundDto orderRefundDto, OrdersTotal ordersTotal){
F 2029         if(ordersTotal == null){
2030             ordersTotal = ordersTotalMapper.selectOneByKey(orderRefundDto.getOrderId());
2031         }
2032
97a5fc 2033         //获取该笔订单的项目详情
118d96 2034         List<Map<String, Object>> refundDetails=refundDetails(ordersTotal);
2e8393 2035
97a5fc 2036         // 退款信息集合
Z 2037         List<OrderItemRefundDto> refundList=new ArrayList<>();
2038         //退款二级子订单信息集合
2039         List<OrderItemSourceRefundDto> orderItemSourceRefundDtos;
2040         List<Map<String, Object>> refundSonDetails;
2041
2042         OrderItemRefundDto orderItemRefundDto;
2043         OrderItemSourceRefundDto orderItemSourceRefundDto;
2044         for (Map<String, Object> refundDetail : refundDetails) {
2e8393 2045             orderItemRefundDto = new OrderItemRefundDto();
97a5fc 2046             orderItemRefundDto.setOrderItemId(String.valueOf(refundDetail.get("id")));
Z 2047             orderItemRefundDto.setType(String.valueOf(refundDetail.get("type")));
2048
8eb9e6 2049             ////退款备注
C 2050             orderItemRefundDto.setRemarks(orderRefundDto.getRemarks());
2051             orderItemRefundDto.setRefundReason(orderRefundDto.getRefundReason());
2052
2e8393 2053             if(OrderItemConstants.TYPE_PROMOTION.equals(orderItemRefundDto.getType())
C 2054                     || OrderItemConstants.CARD_BAG.equals(orderItemRefundDto.getType())){
97a5fc 2055                 orderItemRefundDto.setRefundNum(0);
Z 2056                 refundSonDetails= (List<Map<String, Object>>) refundDetail.get("list");
2057                 orderItemSourceRefundDtos=new ArrayList<>();
2058                 for (Map<String, Object> refundSonDetail : refundSonDetails) {
2059                     orderItemSourceRefundDto=new OrderItemSourceRefundDto();
2060                     orderItemSourceRefundDto.setOrderItemSonId(String.valueOf(refundSonDetail.get("id")));
2061                     orderItemSourceRefundDto.setType(String.valueOf(refundSonDetail.get("type")));
2062                     orderItemSourceRefundDto.setRefundNum(Integer.parseInt(String.valueOf(refundSonDetail.get("notUsedNum"))));
8eb9e6 2063
C 2064                     //退款备注
2065                     orderItemSourceRefundDto.setRemarks(orderRefundDto.getRemarks());
2066                     orderItemSourceRefundDto.setRefundReason(orderRefundDto.getRefundReason());
2067
97a5fc 2068                     orderItemSourceRefundDtos.add(orderItemSourceRefundDto);
Z 2069                 }
2070                 orderItemRefundDto.setOrderItemSourceRefundDtos(orderItemSourceRefundDtos);
2071             }else {
2072                 orderItemRefundDto.setRefundNum(Integer.parseInt(refundDetail.get("notUsedNum").toString()) );
2073             }
2074             refundList.add(orderItemRefundDto);
2075         }
2076         orderRefundDto.setRefundList(refundList);
2077
2078         //获取退款资金信息
118d96 2079         OrderRefundDto  parameter= nextStep(ordersTotal,orderRefundDto);
97a5fc 2080
Z 2081         parameter.setOperatorId(orderRefundDto.getOperatorId());
2082         parameter.setIsRefund(orderRefundDto.getIsRefund());
2083         parameter.setIsApproval(orderRefundDto.getIsApproval());
2084         parameter.setRoleId(orderRefundDto.getRoleId());
2085         parameter.setPlatformSource(orderRefundDto.getPlatformSource());
04ce22 2086         parameter.setRefundOperationType(BaseEntity.NO);
f19292 2087         parameter.setRemarks(orderRefundDto.getRemarks());
F 2088         parameter.setRefundReason(orderRefundDto.getRefundReason());
7f9228 2089         parameter.setCouponList(parameter.getPayCouponList());
2e8393 2090
C 2091         //退款金额
2092         List<OrderPayMethodDto> refundPayMethodList = parameter.getPayMethodList();
2093         for(OrderPayMethodDto orderPayMethodDto:refundPayMethodList){
2094             orderPayMethodDto.setRefundNumberNo(orderPayMethodDto.getPayMethodNo());
2095             orderPayMethodDto.setRefundNumberName(orderPayMethodDto.getPayMethodName());
2096             orderPayMethodDto.setMoney(orderPayMethodDto.getPayTotal());
2097         }
2098
d993aa 2099         parameter.setRefundPayMethod(refundPayMethodList);
d68a60 2100         return parameter;
97a5fc 2101     }
b9b969 2102
250fca 2103     /**
25d452 2104      * 伪造退款处理退款逻辑
832331 2105      * @param orderRefundDto 退款信息
C 2106      * @return 结果
250fca 2107      */
Z 2108     @Override
2109     public PlatformResult forgePartRefund(OrderRefundDto orderRefundDto) {
25d452 2110         logger.info("退款打印参数:{}", JSON.toJSONString(orderRefundDto));
250fca 2111         //先判断项目的状态是否存在
Z 2112         OrdersTotal ordersTotal=null;
2113         try {
2114             ordersTotal=ordersTotalMapper.selectOneByKey(orderRefundDto.getOrderId());
2115             if(ordersTotal==null){
2116                 logger.info("取消订单流程:未找到总订单信息!订单id:{}",orderRefundDto.getOrderId());
2117                 return PlatformResult.failure(PlatformCode.ERROR_TIPS,"取消订单流程:未找到总订单信息!");
2118             }
2119         }catch (Exception e){
2120             logger.info("取消订单流程:根据订单id查询多条总订单信息!订单id:{}",orderRefundDto.getOrderId());
2121             return PlatformResult.failure(PlatformCode.ERROR_TIPS,"取消订单流程:根据订单id查询多条总订单信息!");
2122         }
2123
2124         if(!(OrderTotalConstants.STATUS_REFUND_NONE==ordersTotal.getRefundStatus()) &&
2125                 !(OrderTotalConstants.STATUS_REFUND_PART==ordersTotal.getRefundStatus())){
2126             throw new TipsException("订单标识错误,订单退款状态不正确!");
2127         }
2128
2129 //        orderRefundDto=parameterVerification(orderRefundDto);
2130
2131         return handleforgePartRefund(ordersTotal,orderRefundDto);
2132
2133     }
2134
892b96 2135
Z 2136
250fca 2137     /**
Z 2138      * 伪造处理退款详情
2139      */
2140     public PlatformResult  handleforgePartRefund(OrdersTotal ordersTotal,OrderRefundDto orderRefundDto){
2141
2142         //订单节点日志
2143         OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
2144         StringBuilder orderNodeBuilder = new StringBuilder();
2145
86bf93 2146         orderNodeBuilder.append("开始退款(WZ)");
250fca 2147
Z 2148         // 获取退款方式,退款项目,退款优惠卷
2149         List<OrderPayMethodDto> refundPayMethod=orderRefundDto.getRefundPayMethod();
2150         List<OrderItemRefundDto> refundList=orderRefundDto.getRefundList();
2151         List<OrderCouponRefunDto> couponList=orderRefundDto.getCouponList();
2152
2153         //客户选的退款方式总金额
2154         BigDecimal sumMoney=refundPayMethod.stream().map(OrderPayMethodDto::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
2155         //本次退款总金额
2156         BigDecimal refundSumMoney=refundList.stream().map(OrderItemRefundDto::getRefundMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
2157
2158         if(!OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
832331 2159             if(sumMoney.compareTo(refundSumMoney) > 0){
250fca 2160                 throw new TipsException("退款金额不能大于可退金额!");
Z 2161             }
832331 2162             orderNodeBuilder.append("-本次退款项目总金额:").append(refundSumMoney).append(",客户选的退款方式总金额:").append(sumMoney);
250fca 2163         }else {
832331 2164             orderNodeBuilder.append("-本次退款项目总金额:").append(ordersTotal.getActualTotal()).append(",客户选的退款方式总金额:").append(sumMoney);
250fca 2165         }
Z 2166
2167         Map<String, String> operator = ApiOrderUtil.getOperator(commonService, orderRefundDto.getOperatorId());//获取操作人信息
2168         SqlSentence sqlSentence = new SqlSentence();
2169         Map<String,Object> map=new HashMap<>();
2170         sqlSentence.setM(map);
2171
2172         //退款总记录
2173         orderNodeBuilder.append("-处理退款总记录");
2174         String totalCode = CreateNo.createTimeNo(systemParameterMapper, "R", 8, "yyyyMMddHHmmss");//总订单编号
25d452 2175         RefundRecord refundRecord=new RefundRecord(totalCode,ordersTotal.getShopId(),ordersTotal.getShopName(),sumMoney, RefundStatus.STATUS_APPLY_REFUND,0, RefundSoruceConstants.TYPE_SOURCE_ORDER,"phis退款",ordersTotal.getId(),ordersTotal.getUserId());
250fca 2176         refundRecord.setOperatorType(RefundRecord.OPERATOR_TYPE_EMPLOYEE);
Z 2177         Employee employee = commonService.selectOneByKey(EmployeeMapper.class,orderRefundDto.getOperatorId());
2178         refundRecord.setOperatorId(employee.getId());
2179         refundRecord.setRefundOperationType(orderRefundDto.getRefundOperationType());
2180         refundRecord.setOperatorName(employee.getCnName());
2181         refundRecordService.insert(refundRecord);
2182
832331 2183         if(refundPayMethod.size()>0){
250fca 2184             //处理退款方式记录表
4df03d 2185             handleRefundPayMethod(orderRefundDto,orderNodeBuilder,ordersTotal,refundRecord);
250fca 2186         }
Z 2187         if(couponList!=null && couponList.size()>0){
2188             //处理优惠卷
2189             handleOrderCouponRefunDto(couponList,orderNodeBuilder,ordersTotal,refundRecord);
2190         }
2191         try{
2192             orderNodeBuilder.append("-开始记录收入确认表");
2193             PerformanceInfoTool.handRefundPerformanceInfo(commonService,refundRecord);
2194             orderNodeBuilder.append("-记录收入确认表成功");
2195         }catch (Exception e){
2196             orderNodeBuilder.append("-记录收入确认表失败");
2197             logger.info("记录收入确认表,异常:{}",e.getMessage(),e);
071df8 2198             // 添加错误日志
A 2199             PerformanceInfoTool.addErrorLog(commonService, refundRecord.getId(), PerformanceInfo.ASSOCIATION_TYPE_GOODS_REFUND, e.getMessage());
250fca 2200         }
Z 2201         //记录操作日志
2202         orderNodeBuilder.append("-记录操作日志");
86bf93 2203         StringBuffer stringBuffer=new StringBuffer("操作人:"+operator.get("operatorName")+",进行退款(WZ)");
250fca 2204         OrderLog orderLog=new OrderLog(ordersTotal.getId(), OrderLogConstants.LOG_TYPE_REFUND,stringBuffer.toString()
Z 2205                 ,operator.get("operatorName"),operator.get("operatorId"),OrderTotalConstants.STATUS_CANCEL);
2206         commonService.insert(OrderLogMapper.class,orderLog);
2207
2208         orderNodeBuilder.append("-结束处理退款");
2209         ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_REFUND);
2210         ordersNodeLog.setContent(orderNodeBuilder.toString());
2211         ordersNodeLog.setOrderId(ordersTotal.getId());
2212         commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
2213
2214         return PlatformResult.success("成功");
2215     }
2216
892b96 2217     /**
Z 2218      * 根据订单 重新绑定订单退款状态
2219      *
2220      */
2221     @Override
2222     public void verifyOrderRefundStatus(OrdersTotal ordersTotalDto) {
2223         SqlSentence sqlSentence = new SqlSentence();
2224         Map<String, Object> sqlMap = new HashMap<>();
2225         sqlSentence.setM(sqlMap);
2226         sqlMap.put("isDel", BaseEntity.NO);
2227         sqlMap.put("orderId", ordersTotalDto.getId());
2228         sqlMap.put("type", OrderItemConstants.TYPE_PROJECT);
2229
4df03d 2230         sqlSentence.sqlSentence("SELECT * FROM  orders_total   WHERE  id = #{m.orderId}  and  isDel = #{m.isDel} ",sqlMap);
892b96 2231         OrdersTotal ordersTotal = ordersTotalMapper.selectOne(sqlSentence);
Z 2232         if(ordersTotal==null){
2233             throw new TipsException("订单标识错误,找不到订单!");
2234         }
2235         //查询二级订单
4df03d 2236         sqlSentence.sqlSentence("SELECT * FROM  order_item_source   WHERE  orderId = #{m.orderId}  and  type = #{m.type}  and  isDel = #{m.isDel} ",sqlMap);
892b96 2237         List<OrderItemSon> orderItemSonList=orderItemSonMapper.selectList(sqlSentence);
Z 2238
2239
2240         if(orderItemSonList!=null && orderItemSonList.size()>0){
2241             int oldRefundStatus;
2242             int newRefundStatus;
2243             UserProjectItem userProjectItem;
2244             for (OrderItemSon orderItemSon : orderItemSonList) {
2245                 if(OrderTotalConstants.STATUS_REFUND_FINSH==orderItemSon.getRefundStatus()){
2246                     oldRefundStatus=OrderTotalConstants.STATUS_REFUND_FINSH;
2247
ae6ff7 2248                     userProjectItem = PartialRefundUtil.getUserProject(orderItemSon.getId(),commonService);
892b96 2249
Z 2250                     if(userProjectItem.getNotUsedNum()>0){
2251                         newRefundStatus=OrderTotalConstants.STATUS_REFUND_PART;
2252                     }else {
2253                         newRefundStatus=oldRefundStatus;
2254                     }
2255
2256                     if(newRefundStatus!=oldRefundStatus){
2257                         sqlMap.put("refundStatus", newRefundStatus);
2258                         sqlMap.put("id", orderItemSon.getId());
4df03d 2259                         sqlSentence.sqlSentence(" refundStatus = #{m.refundStatus} WHERE id = #{m.id}  ",sqlMap);
892b96 2260                         orderItemSonMapper.updateWhere(sqlSentence);
Z 2261
2262                         sqlMap.put("refundStatus", newRefundStatus);
2263                         sqlMap.put("id", orderItemSon.getOrderItemId());
4df03d 2264                         sqlSentence.sqlSentence(" refundStatus = #{m.refundStatus} WHERE id = #{m.id}  ",sqlMap);
892b96 2265                         orderItemMapper.updateWhere(sqlSentence);
Z 2266                     }
2267
2268                 }
2269             }
2270             
2271         }
2272
2273         //查询二级订单
4df03d 2274         sqlSentence.sqlSentence("SELECT * FROM  order_item   WHERE  orderId = #{m.orderId}  and  type = #{m.type}  and  isDel = #{m.isDel} ",sqlMap);
892b96 2275         List<OrderItem> orderItemList=orderItemMapper.selectList(sqlSentence);
Z 2276         if(orderItemList!=null && orderItemList.size()>0){
2277             int oldRefundStatus;
2278             int newRefundStatus;
2279             UserProjectItem userProjectItem;
2280             for (OrderItem orderItem : orderItemList) {
2281                 oldRefundStatus=OrderTotalConstants.STATUS_REFUND_FINSH;
2282
ae6ff7 2283                 userProjectItem = PartialRefundUtil.getUserProject(orderItem.getId(),commonService);
892b96 2284
Z 2285                 if(userProjectItem.getNotUsedNum()>0){
2286                     newRefundStatus=OrderTotalConstants.STATUS_REFUND_PART;
2287                 }else {
2288                     newRefundStatus=oldRefundStatus;
2289                 }
2290
2291                 if(newRefundStatus!=oldRefundStatus){
2292                     sqlMap.put("refundStatus", newRefundStatus);
2293                     sqlMap.put("id", orderItem.getId());
4df03d 2294                     sqlSentence.sqlSentence(" refundStatus = #{m.refundStatus} WHERE id = #{m.id}  ",sqlMap);
892b96 2295                     orderItemMapper.updateWhere(sqlSentence);
Z 2296                 }
2297
2298             }
2299         }
2300
2301
2302         sqlMap.put("orderId",ordersTotal.getId());
4df03d 2303         sqlSentence.sqlSentence("select * from order_item WHERE  orderId=#{m.orderId} and isDel=0",sqlMap);
892b96 2304         List<OrderItem> orderItems=commonService.selectList(OrderItemMapper.class,sqlSentence);
Z 2305
832331 2306         List<Integer> collect = orderItems.stream().map(OrderItem::getRefundStatus).collect(Collectors.toList());
892b96 2307         if(collect.contains(OrderTotalConstants.STATUS_REFUND_PART)){
Z 2308             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
215be3 2309             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
892b96 2310         }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE) && collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
Z 2311             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
215be3 2312             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
892b96 2313         }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE)){
Z 2314             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
215be3 2315             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
892b96 2316         }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
Z 2317             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_FINSH);
2318             ordersTotal.setStatus(OrderTotalConstants.STATUS_CANCEL);
2319         }else {
2320             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
215be3 2321             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
892b96 2322         }
Z 2323         ordersTotal.setEditTime(new Date());
2324         commonService.updateAll(OrdersTotalMapper.class,ordersTotal);
2325     }
2326
fd7281 2327     /**作废退款*/
C 2328     @Override
2329     public void refundCancel(RefundCancelVo refundCancelVo, RefundRecord refundRecord,Employee employee,EmployeeRole employeeRole
2330             , ThirtApplication thirtApplication) {
2331
2332         //判断退款单状态
2333         if(refundRecord.getRefundStatus() != RefundStatus.STATUS_SUCC_REFUND){
2334             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作失败,退款单状态错误!");
2335         }
2336
2337         //获取订单信息
2338         OrdersTotal ordersTotal = ordersTotalMapper.selectOneByKey(refundRecord.getOrderId());
2339         if(ordersTotal == null){
2340             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作失败,获取订单信息失败!");
2341         }
2342
da6435 2343         //检查升单关联逻辑
befece 2344         cancelRefundCheckRiseOrder(ordersTotal);
fd7281 2345
C 2346         SqlSentence sqlSentence = new SqlSentence();
2347         Map<String,Object> values = new HashMap<>();
2348         StringBuilder sql = new StringBuilder();
2349
478fa9 2350         //如果是线上退款,那么就不给作废
C 2351         values.put("refundRecordId",refundRecord.getId());
2352         sqlSentence.sqlSentence(" isDel = 0 AND refundRecordId = #{m.refundRecordId}",values);
2353         if(commonService.selectCount(RefundCashMapper.class,sqlSentence) > 0){
2354             throw new TipsException("该退款记录含线上退款,不能作废!");
2355         }
2356
fd7281 2357         //填充数据,后面会用到
C 2358         refundRecord.setInvalidType(RefundRecord.OPERATOR_TYPE_EMPLOYEE);
2359         refundRecord.setInvalidRemarks(refundCancelVo.getRemarks());
2360
2361         //****更新退款单信息,更新完退款单再去做剩下的操作
2362         values.put("refundStatus",RefundStatus.STATUS_REFUND_CANCEL);
2363         values.put("refundStatusOld",RefundStatus.STATUS_SUCC_REFUND);
2364         values.put("id",refundRecord.getId());
2365         values.put("invalidTime",new Date());
2366         values.put("invalidType",RefundRecord.OPERATOR_TYPE_EMPLOYEE);
2367         values.put("invalidRemarks",refundCancelVo.getRemarks());
2368         sql.append("refundStatus = #{m.refundStatus},invalidTime = #{m.invalidTime},invalidRemarks = #{m.invalidRemarks},invalidType = #{m.invalidType}");
2369
2370         if(employee != null){
2371             refundRecord.setInvalidId(employee.getId());
2372             refundRecord.setInvalidNo(employee.getEmployeeNo());
2373             refundRecord.setInvalidName(employee.getCnName());
2374             values.put("invalidId",employee.getId());
2375             values.put("invalidNo",employee.getEmployeeNo());
2376             values.put("invalidName",employee.getCnName());
2377             sql.append(",invalidId = #{m.invalidId},invalidNo = #{m.invalidNo},invalidName = #{m.invalidName}");
2378         }
2379         if(employeeRole != null){
2380             refundRecord.setInvalidRoleNo(employeeRole.getRoleUniqueStr());
2381             refundRecord.setInvalidRoleName(employeeRole.getRoleName());
2382             values.put("invalidRoleNo",employeeRole.getRoleUniqueStr());
2383             values.put("invalidRoleName",employeeRole.getRoleName());
2384             sql.append(",invalidRoleNo = #{m.invalidRoleNo},invalidRoleName = #{m.invalidRoleName}");
2385         }
2386         if(thirtApplication != null){
2387             refundRecord.setInvalidAppId(thirtApplication.getAppId());
2388             refundRecord.setInvalidAppCode(thirtApplication.getAppIdCode());
2389             refundRecord.setInvalidAppName(thirtApplication.getName());
2390             values.put("invalidAppId",thirtApplication.getAppId());
2391             values.put("invalidAppCode",thirtApplication.getAppIdCode());
2392             values.put("invalidAppName",thirtApplication.getName());
2393             sql.append(",invalidAppId = #{m.invalidAppId},invalidAppCode = #{m.invalidAppCode},invalidAppName = #{m.invalidAppName}");
2394         }
2395         sql.append(" WHERE id = #{m.id} AND refundStatus = #{m.refundStatusOld}");
2396         sqlSentence.sqlUpdate(sql.toString(),values);
2397         if(refundRecordMapper.updateWhere(sqlSentence) != 1){
2398             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作失败,退款单状态已发生变化!");
2399         }
2400
b3fdea 2401         //订单系统日志
C 2402         StringBuilder orderNodeBuilder = new StringBuilder();
2403         orderNodeBuilder.append("开始作废退款");
2404
fd7281 2405         //判断订单类型
C 2406         if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
2407             //充值订单
b3fdea 2408             OrderRefundCancelTool.rechargeHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_CANCEL,"作废退款",orderNodeBuilder,commonService);
fd7281 2409         }else{
160c33 2410             //处理子单
C 2411             OrderRefundCancelTool.refundRecordItemHandle(ordersTotal,refundRecord,commonService);
fd7281 2412         }
C 2413
160c33 2414         //处理订单活动
b3fdea 2415         OrderRefundCancelTool.activityRuleHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_CANCEL,"作废退款",orderNodeBuilder,commonService);
160c33 2416         //处理订单优惠券
b3fdea 2417         OrderRefundCancelTool.handCoupon(ordersTotal,refundRecord,orderNodeBuilder,commonService);
4ebb90 2418         //处理总退款方式
b3fdea 2419         List<RefundRecordMethod> refundRecordMethodList= OrderRefundCancelTool.refundRecordMotnedHandle(refundRecord,ordersTotal,orderNodeBuilder,commonService);
C 2420
2421         //操作的现金金额
2422         BigDecimal cashTotal = BigDecimal.ZERO;
2423         for(RefundRecordMethod refundRecordMethod:refundRecordMethodList){
2424             if(refundRecordMethod.getIsMoneyPay().equals(RefundRecordMethod.YES)){
2425                 cashTotal = cashTotal.add(refundRecordMethod.getActualTotal());
2426             }
2427         }
2428
2429         //报错订单系统日志
fd7281 2430
160c33 2431         //****更改总订单退款状态
C 2432         values.clear();
2433         values.put("orderId",ordersTotal.getId());
2434         sqlSentence.sqlSentence("select * from order_item WHERE orderId=#{m.orderId} and isDel=0",values);
2435         List<OrderItem> orderItemList=commonService.selectList(OrderItemMapper.class,sqlSentence);
2436
7c2538 2437         int oldStatus = ordersTotal.getStatus();
160c33 2438         values.clear();
C 2439         values.put("oldStatus",ordersTotal.getStatus());
2440         values.put("oldRefundStatus",ordersTotal.getRefundStatus());
2441
2442         List<Integer> collect = orderItemList.stream().map(OrderItem::getRefundStatus).collect(Collectors.toList());
2443         if(collect.contains(OrderTotalConstants.STATUS_REFUND_PART)){
2444             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
2445             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
2446             ordersTotal.setReTotal(orderItemList.stream().map(OrderItem::getReTotal).reduce(BigDecimal.ZERO,BigDecimal::add));
2447         }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE) && collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
2448             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
2449             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
2450             ordersTotal.setReTotal(orderItemList.stream().map(OrderItem::getReTotal).reduce(BigDecimal.ZERO,BigDecimal::add));
2451         }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE)){
2452             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
2453             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
2454             ordersTotal.setReTotal(BigDecimal.ZERO);
2455         }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
2456             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_FINSH);
2457             ordersTotal.setStatus(OrderTotalConstants.STATUS_CANCEL);
2458             ordersTotal.setReTotal(orderItemList.stream().map(OrderItem::getReTotal).reduce(BigDecimal.ZERO,BigDecimal::add));
2459         }else {
2460             if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
2461                 if(ordersTotal.getReTotal().compareTo(refundRecord.getRefundTotal()) == 0){
2462                     ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
2463                     ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
2464                     ordersTotal.setReTotal(ordersTotal.getReTotal().subtract(refundRecord.getRefundTotal()));
2465                 }else if(ordersTotal.getReTotal().compareTo(refundRecord.getRefundTotal()) > 0){
2466                     ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
2467                     ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
2468                     ordersTotal.setReTotal(ordersTotal.getReTotal().subtract(refundRecord.getRefundTotal()));
2469                 }
2470             }else{
2471                 ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
2472                 ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
2473                 ordersTotal.setReTotal(ordersTotal.getReTotal().subtract(refundRecord.getRefundTotal()));
2474             }
2475         }
2476         ordersTotal.setIsSyncOrder(BaseEntity.NO);
2477
2478         values.put("isSyncOrder",BaseEntity.NO);
2479         values.put("status",ordersTotal.getStatus());
2480         values.put("refundStatus",ordersTotal.getRefundStatus());
2481         values.put("reTotal",ordersTotal.getReTotal());
2482         values.put("id",ordersTotal.getId());
2483         sqlSentence.sqlUpdate("isSyncOrder = #{m.isSyncOrder},status = #{m.status},refundStatus = #{m.refundStatus},reTotal = #{m.reTotal}" +
2484                 " WHERE id = #{m.id} AND status = #{m.oldStatus} AND refundStatus = #{m.oldRefundStatus}",values);
2485         if(commonService.updateWhere(OrdersTotalMapper.class,sqlSentence) != 1){
2486             throw new TipsException("作废失败,订单状态已发生改变!");
2487         }
fd7281 2488
7c2538 2489         //初始化初复诊信息
C 2490         if(OrderTotalConstants.STATUS_CANCEL == oldStatus
2491                 && oldStatus != ordersTotal.getStatus()){
6ed28c 2492             // OrderUtil.reCalcOrderBothTheOneData(commonService, VisitRecordMapper.class,null,ordersTotal.getUserId(), BaseEntity.NO);
A 2493             // 处理方法调整
9198b5 2494             TimerHandleTool.addTask(commonService, TimerHandleItem.TYPE_RECALC_ORDER_BOTH, ordersTotal.getUserId());
7c2538 2495         }
C 2496
b3fdea 2497         //额外的操作,升降级,收入确认表
26ebce 2498         additionalOperate(userLevelRuleService, ordersTotal,refundRecord,cashTotal,orderNodeBuilder,customParameter,commonService);
b3fdea 2499
C 2500         //记录日志(处理到具体节点(成功和失败))
2501         OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
2502         orderNodeBuilder.append("-作废退款单结束");
2503         ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_REFUND_CANCEL);
2504         ordersNodeLog.setContent(orderNodeBuilder.toString());
2505         ordersNodeLog.setOrderId(ordersTotal.getId());
2506         commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
2507
2508     }
2509
2510     /**额外操作,不影响主流程*/
26ebce 2511     public static void additionalOperate(UserLevelRuleService userLevelRuleService, OrdersTotal ordersTotal,RefundRecord refundRecord,BigDecimal total,StringBuilder orderNodeBuilder,CustomParameter customParameter,CommonService commonService){
b3fdea 2512         if(BigDecimal.ZERO.compareTo(total) < 0){
C 2513             try {
2910fd 2514                 orderNodeBuilder.append("-开始处理作废退款用户升降级,金额:").append(total);
A 2515                 // 把原退款撤销返回金额为正所以是升级
2516                 UserLevelUtil.order(userLevelRuleService, ordersTotal.getUserId(),ordersTotal.getId(),total,refundRecord.getInvalidAppCode()==null?"phiskin":refundRecord.getInvalidAppCode());
2517                 orderNodeBuilder.append("-处理作废退款用户升降级成功");
b3fdea 2518             }catch (Exception e){
2910fd 2519                 String snapshot="处理作废退款用户升降级失败";
A 2520                 orderNodeBuilder.append("-处理作废退款用户升降级失败,异常原因:").append(e.getMessage());
2521                 logger.error("处理作废退款用户升降级失败:" + e.getMessage());
b3fdea 2522                 //发送企业微信通知给工作人员
C 2523                 SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),snapshot,commonService,customParameter);
2524             }
2525         }
2526         try{
2527             orderNodeBuilder.append("-开始记录收入确认表");
2528             PerformanceInfoTool.refundCancelPerformanceInfo(commonService,refundRecord);
2529             orderNodeBuilder.append("-记录收入确认表成功");
2530         }catch (Exception e){
2531             orderNodeBuilder.append("-记录收入确认表失败");
2532             logger.info("记录收入确认表,异常:{}",e.getMessage(),e);
2533             // 添加错误日志
2534             PerformanceInfoTool.addErrorLog(commonService, refundRecord.getId(), PerformanceInfo.ASSOCIATION_TYPE_GOODS_REFUND, e.getMessage());
2535         }
fd7281 2536     }
C 2537
e3b9cc 2538
C 2539     /**退现金到用户
2540      * 不是原路退,不执行第三方支付退款,直接跳过
2541      * @param refundCashVo 退款信息
2542      */
2543     private synchronized void refundCash(String refundRecordId,RefundCashVo refundCashVo){
2544         if(refundCashVo.getRefundCashItemVoList() == null || refundCashVo.getRefundCashItemVoList().size() == 0){
2545             return;
2546         }
2547
999c98 2548         //--合并同一个的退款支付方式
C 2549         //装载退款金额,key值:支付编码,value值:退款金额
e3b9cc 2550         Map<String,BigDecimal> refundMap = new HashMap<>();
C 2551         BigDecimal refundTotal;
2552         for(RefundCashItemVo refundCashItemVo:refundCashVo.getRefundCashItemVoList()){
2553             refundTotal = refundMap.computeIfAbsent(refundCashItemVo.getPaymentNo(),k->BigDecimal.ZERO);
2554             refundTotal = refundTotal.add(refundCashItemVo.getRefundTotal());
2555             refundMap.put(refundCashItemVo.getPaymentNo(),refundTotal);
2556         }
2557
999c98 2558
C 2559         SqlSentence sqlSentence = new SqlSentence();
2560         Map<String,Object> values = new HashMap<>();
2561
2562         //--获取已经退款的记录
2563         values.put("refundRecordId",refundRecordId);
2564         sqlSentence.sqlSentence("SELECT * FROM refund_cash WHERE isDel = 0 AND refundRecordId = #{m.refundRecordId}",values);
2565         List<RefundCash> refundCashList = commonService.selectList(RefundCashMapper.class,sqlSentence);
2566         //装载已退款的金额,key值:支付编码,value值:退款金额
2567         Map<String,BigDecimal> realRefundMap = new HashMap<>();
2568         BigDecimal consumeRefundTotal;
2569         for(RefundCash refundCash:refundCashList){
2570             consumeRefundTotal = realRefundMap.computeIfAbsent(refundCash.getPaymentNo(),k->BigDecimal.ZERO);
2571             consumeRefundTotal = consumeRefundTotal.add(refundCash.getRefundTotal());
2572             realRefundMap.put(refundCash.getPaymentNo(),consumeRefundTotal);
2573         }
2574
e3b9cc 2575         List<ConsumeNotify> consumeNotifyList;
C 2576         String refundNo;
2577         BigDecimal consumeTotal;
2578         int refundStatus;
2579         for (Map.Entry<String, BigDecimal> entry : refundMap.entrySet()) {
2580             refundTotal = entry.getValue();
2581             if(refundTotal.compareTo(BigDecimal.ZERO) < 1){
2582                 continue;
2583             }
2584
999c98 2585             //--获取支付信息(回调),计算可退款的金额
e3b9cc 2586             //初始化可退金额
C 2587             consumeTotal = BigDecimal.ZERO;
2588             consumeNotifyList = ConsumeTool.selectList(refundCashVo.getOrderId(),entry.getKey(),null,commonService);
2589             for(ConsumeNotify consumeNotify:consumeNotifyList){
2590                 //计算总可退款金额
2591                 consumeTotal = consumeTotal.add(consumeNotify.getPayAmount()).subtract(consumeNotify.getRefundTotal());
f3ff4e 2592             }
C 2593
999c98 2594             //--避免多退,要减去已退款
C 2595             consumeRefundTotal = realRefundMap.computeIfAbsent(entry.getKey(),k->BigDecimal.ZERO);
f3ff4e 2596             refundTotal = refundTotal.subtract(consumeRefundTotal);
C 2597             if(refundTotal.compareTo(BigDecimal.ZERO) < 1){
2598                 continue;
e3b9cc 2599             }
C 2600
2601             if(refundTotal.compareTo(consumeTotal) > 0){
2602                 //总退款金额比可退金额大,那么就不执行
798ce2 2603                 logger.error("第三方退款失败,退款金额比可退金额大,退款金额:{};可退基恩:{}",refundTotal,consumeTotal);
e3b9cc 2604                 continue;
C 2605             }
2606             for(ConsumeNotify consumeNotify:consumeNotifyList){
2607                 if(refundTotal.compareTo(BigDecimal.ZERO) < 1){
2608                     //退完,那么就跳出循环
2609                     continue;
2610                 }
2611                 if(consumeNotify.getRefundStatus() == ConsumeNotify.REFUND_STATUS_ALL){
2612                     //没有可退金额,那么跳出循环
2613                     continue;
2614                 }
2615                 //计算可退金额
2616                 consumeTotal = consumeNotify.getPayAmount().subtract(consumeNotify.getRefundTotal());
2617                 if(consumeTotal.compareTo(BigDecimal.ZERO) < 1){
2618                     //没有可退金额,那么跳出循环
2619                     continue;
2620                 }
2621                 refundStatus = ConsumeNotify.REFUND_STATUS_ALL;
2622                 if(consumeTotal.compareTo(refundTotal) > 0){
2623                     //可退金额比剩下要退的金额大
2624                     refundStatus = ConsumeNotify.REFUND_STATUS_PART;
2625                     consumeTotal = refundTotal;
2626                 }
2627                 //生成退款单号
2628                 refundNo = createNoService.createNo("RF",String.valueOf(System.currentTimeMillis()),6);
2629                 try {
7c75e2 2630                     //服务商退款,生成退款记录
C 2631                     consumeNotifyRefundService.consumeNotifyRefund(consumeNotify,refundStatus,consumeTotal,refundNo,refundRecordId);
e3b9cc 2632                 }catch (Exception e){
f3ff4e 2633                     logger.error("第三方退款失败,错误信息:",e);
e3b9cc 2634                 }
7c75e2 2635                 //已经退的跳过
C 2636                 refundTotal = refundTotal.subtract(consumeTotal);
e3b9cc 2637             }
C 2638         }
2639     }
2640
befece 2641     /** 作废退款校验升单逻辑 */
F 2642     public void cancelRefundCheckRiseOrder(OrdersTotal ordersTotal) {
44a123 2643         if(OrderTotalConstants.ADD_WAY_RISE.equals(ordersTotal.getAddWay())){
F 2644             throw new PlatTipsException(PlatformCode.ERROR_TIPS, "作废退款失败,升单订单暂时不可作废退款!");
2645         }
2646
2647         SqlSentence sqlSentence = new SqlSentence();
2648         Map<String,Object> values = new HashMap<>();
2649         sqlSentence.setM(values);
2650         StringBuilder sql = new StringBuilder();
2651
2652         //查询有关联升单,且升单的订单已支付,未全部退款的
2653         values.put("orderId", ordersTotal.getId());
2654         values.put("payStatus", OrderTotalConstants.PAY_STATUS_SUC);
2655         values.put("refundStatus", OrderTotalConstants.STATUS_REFUND_FINSH);
2656         sql.append(" select count(1) from order_rise r  ")
2657                 .append(" join orders_total t on t.id = r.orderId ")
2658                 .append(" where r.isDel = 0 and r.assocOrderId = #{m.orderId} ")
2659                 .append(" and t.payStatus = #{m.payStatus}  ");
2660         sqlSentence.setSqlSentence(sql.toString());
2661         if(commonService.selectCountSql(sqlSentence) > 0){
2662             throw new TipsException("作废退款失败,当前订单已被升单关联,暂时不可作废退款!");
2663         }
2664
2665     }
2666
2667     /** 作废退款校验升单逻辑V2 */
2668     public void cancelRefundCheckRiseOrderV2(OrdersTotal ordersTotal) {
2669
befece 2670         SqlSentence sqlSentence = new SqlSentence();
F 2671         Map<String,Object> values = new HashMap<>();
2672         sqlSentence.setM(values);
2673         StringBuilder sql = new StringBuilder();
2674
2675         //查询有关联升单,且升单的订单已支付,未全部退款的
34c581 2676         values.put("orderId", ordersTotal.getId());
befece 2677         values.put("payStatus", OrderTotalConstants.PAY_STATUS_SUC);
F 2678         values.put("refundStatus", OrderTotalConstants.STATUS_REFUND_FINSH);
e118d7 2679         sql.append(" select t.id, t.orderNo from order_rise r  ")
befece 2680                 .append(" join orders_total t on t.id = r.orderId ")
34c581 2681                 .append(" where r.isDel = 0 and r.assocOrderId = #{m.orderId} ")
e118d7 2682                 .append(" and t.payStatus = #{m.payStatus} and t.refundStatus != #{m.refundStatus} limit 1 ");
befece 2683         sqlSentence.setSqlSentence(sql.toString());
e118d7 2684         OrdersTotal riseOrder = commonService.selectOne(OrdersTotalMapper.class, sqlSentence);
F 2685         if(riseOrder != null){
2686             throw new PlatTipsException(PlatformCode.ERROR_TIPS, "作废退款失败,当前订单已被升单关联,请先退款升单的订单[" + riseOrder.getOrderNo() + "]!");
befece 2687         }
34c581 2688
e118d7 2689         //查询是否有被关联的升单订单最新退款成功的退款记录下的退款方式记录
F 2690         sql.setLength(0);
2691         values.clear();
2692         values.put("orderId", ordersTotal.getId());
2693         values.put("refundStatus", RefundStatus.STATUS_SUCC_REFUND);
44a123 2694         sql.append(" select m.* from refund_record_method m  ")
F 2695                 .append(" where m.isDel = 0 and m.refundRecordId = ( ")
e118d7 2696                 .append(" select r.id from refund_record r ")
F 2697                 .append(" join orders_total ot on ot.id = r.orderId ")
2698                 .append(" join order_rise ri on ri.orderId = r.orderId ")
2699                 .append(" where r.isDel = 0 and r.refundStatus = #{m.refundStatus} and ri.assocOrderId = #{m.orderId} ")
2700                 .append(" order by r.createTime desc limit 1 ")
2701                 .append(" ) ");
44a123 2702         sqlSentence.setSqlSentence(sql.toString());
e118d7 2703         List<RefundRecordMethod> methodList = commonService.selectList(RefundRecordMethodMapper.class, sqlSentence);
F 2704         if(methodList != null && methodList.size() > 0){
2705             //遍历存储累加相同的退款方式
2706             Map<String, BigDecimal> refundMethodMap = new HashMap<>();
2707             for(RefundRecordMethod recordMethod : methodList){
2708                 if(refundMethodMap.containsKey(recordMethod.getRefundNumberNo())){
2709                     refundMethodMap.put(recordMethod.getRefundNumberNo(), refundMethodMap.get(recordMethod.getRefundNumberNo()).add(recordMethod.getRealRefundTotal()));
2710                 }else{
2711                     refundMethodMap.put(recordMethod.getRefundNumberNo(), recordMethod.getRealRefundTotal());
2712                 }
2713             }
44a123 2714             logger.info("退款方式Map:{}", refundMethodMap.entrySet());
e118d7 2715             //查询订单支付方式
F 2716             sqlSentence.setSqlSentence(" select * from consume_pay where isDel = 0 and orderId = #{m.orderId} ");
2717             List<ConsumePay> consumePayList = commonService.selectList(ConsumePayMapper.class, sqlSentence);
2718             if(consumePayList == null || consumePayList.size() < 1){
2719                 throw new PlatTipsException(PlatformCode.ERROR_TIPS, "作废退款失败,找不到订单支付方式记录!");
2720             }
2721
2722             //遍历判断最新的升单退款方式是否都和原订单支付方式对的上
2723             BigDecimal refundMoney;
44a123 2724             for(ConsumePay consumePay : consumePayList){
e118d7 2725                 refundMoney = refundMethodMap.get(consumePay.getNumberNo());
F 2726                 if(refundMoney == null){
2727                     throw new PlatTipsException(PlatformCode.ERROR_TIPS, "作废退款失败,当前订单支付时有["+consumePay.getName()+"],关联的升单退款方式没有!");
2728                 }
2729                 if(refundMoney.compareTo(consumePay.getActualTotal()) == -1){
2730                     throw new PlatTipsException(PlatformCode.ERROR_TIPS, "作废退款失败,,当前订单["+consumePay.getName()+"]支付金额和关联的升单退款金额不一致!");
2731                 }
2732             }
2733         }
2734
44a123 2735         //---------------------------------------------------------------------------------
F 2736
2737
2738
2739         //判断如果是升单的订单,作废退款时,判断原订单是否已退款(正常原订单是退款,且作废退款不可能成功的)
2740         if(OrderTotalConstants.ADD_WAY_RISE.equals(ordersTotal.getAddWay())){
2741             sql.setLength(0);
2742             values.put("orderId", ordersTotal.getId());
2743             values.put("payStatus", OrderTotalConstants.PAY_STATUS_SUC);
2744             values.put("refundStatus", OrderTotalConstants.STATUS_REFUND_FINSH);
2745             sql.append(" SELECT COUNT(1) FROM orders_total ")
2746                     .append(" WHERE isDel = 0 and payStatus = #{m.payStatus} and refundStatus != #{m.refundStatus}  ")
2747                     .append(" and id in (  ")
2748                     .append(" select assocOrderId from order_rise where isDel = 0 and orderId = #{m.orderId} ")
2749                     .append(" ) ");
2750             sqlSentence.setSqlSentence(sql.toString());
2751             if(commonService.selectCountSql(sqlSentence) > 0){
2752                 throw new PlatTipsException(PlatformCode.ERROR_TIPS, "作废退款失败,当前订单升单时关联的原订单未全部退款,请先退款关联的原订单!");
2753             }
2754
2755             //查询原订单退款方式和支付方式是否一致,不一致不给退款
2756             sql.setLength(0);
2757             sql.append(" elect count(1) from refund_record_method m  ")
2758                     .append(" where m.isDel = 0 and (m.numberNo != refundNumberNo or actualTotal != realRefundTotal)  ")
2759                     .append(" and m.refundRecordId in ( ")
2760                     .append(" select r.id from refund_record r ")
2761                     .append(" join order_rise ri on ri.orderId = r.orderId ")
2762                     .append(" where r.isDel = 0 and r.refundStatus = 2 and ri.isDel = 0 and ri.orderId = #{m.orderId} ");
2763             sqlSentence.setSqlSentence(sql.toString());
2764             if(commonService.selectCountSql(sqlSentence) > 0){
2765                 throw new PlatTipsException(PlatformCode.ERROR_TIPS, "作废退款失败,当前订单升单时关联的原订单退款方式或金额不一致!");
2766             }
2767         }
befece 2768     }
44a123 2769
F 2770
4dc6e5 2771 }