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