chenjiahe
2023-05-11 b3fdeac8c313971112a6245513f7215b39da537d
提交 | 用户 | 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())){
b3fdea 928             OrderRefundCancelTool.rechargeHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_EXECUTE,"申请退款",orderNodeBuilder,commonService);
4ebb90 929         }
C 930         //活动处理
b3fdea 931         OrderRefundCancelTool.activityRuleHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_EXECUTE,"申请退款",orderNodeBuilder,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
f5e288 1995
C 1996
1997             //先赋值该作废操作人,后面会用到,注意,这里不存储
1998             refundRecord.setInvalidId(refundRecord.getOperatorId());
1999             refundRecord.setInvalidName(refundRecord.getInvalidName());
2000             refundRecord.setInvalidNo(refundRecord.getOperatorNo());
2001             refundRecord.setInvalidAppId(refundRecord.getOperatorAppId());
2002             refundRecord.setInvalidAppName(refundRecord.getOperatorAppName());
2003
160383 2004             //处理老带新的佣金,没有退款才退
C 2005             if(ordersTotal.getRefundStatus() == OrderTotalConstants.STATUS_REFUND_NONE){
2006                 oldBlingNewRefundFail(refundRecord,orderNodeBuilder,commonService);
2007             }
2008
edf5ea 2009             //拒绝审批需要还原回去储值金
Z 2010             //判断是否是充值订单,是的话需要把前面预扣的还原
bf63c3 2011             if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
edf5ea 2012                 //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
f5e288 2013                 //充值金额
b3fdea 2014                 OrderRefundCancelTool.rechargeHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_CANCEL,"拒绝审批",orderNodeBuilder,commonService);
edf5ea 2015             }
f5e288 2016             //活动规则退款处理
b3fdea 2017             OrderRefundCancelTool.activityRuleHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_CANCEL,"拒绝审批",orderNodeBuilder,commonService);
edf5ea 2018
160383 2019             ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_REFUND);
C 2020             ordersNodeLog.setContent(orderNodeBuilder.toString());
2021             ordersNodeLog.setOrderId(ordersTotal.getId());
2022             commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
2023
2024
b9b969 2025             return PlatformResult.success("拒绝取消审核通过");
Z 2026         }
c04e8a 2027
C 2028         cancelOrder.setEditTime(new Date());
2029         cancelOrder.setApprovalstatus(CancelOrder.SUCCESS);
2030         commonService.updateAll(CancelOrderMapper.class,cancelOrder);
97a5fc 2031
b9b969 2032         orderNodeBuilder.append("审核通过,开始处理退款");
Z 2033
edf5ea 2034
277835 2035         Map<String, Object>refund =handleRefundOrder(operator,refundRecord,ordersTotal,ordersNodeLog,orderNodeBuilder,cancelOrder);
b9b969 2036         return PlatformResult.success(refund);
Z 2037     }
df3f90 2038
Z 2039
97a5fc 2040     /**
Z 2041      * 全部退款处理退款逻辑
2042      * @param orderRefundDto
2043      * @return
2044      */
2045     @Override
4df03d 2046     public PlatformResult wholeRefund(OrderRefundDto orderRefundDto,ThirtApplication thirtApplication) {
97a5fc 2047
118d96 2048         OrdersTotal ordersTotal = ordersTotalMapper.selectOneByKey(orderRefundDto.getOrderId());
C 2049
97a5fc 2050         //获取该笔订单的项目详情
118d96 2051         List<Map<String, Object>> refundDetails=refundDetails(ordersTotal);
2e8393 2052
97a5fc 2053         // 退款信息集合
Z 2054         List<OrderItemRefundDto> refundList=new ArrayList<>();
2055         //退款二级子订单信息集合
2056         List<OrderItemSourceRefundDto> orderItemSourceRefundDtos;
2057         List<Map<String, Object>> refundSonDetails;
2058
2059         OrderItemRefundDto orderItemRefundDto;
2060         OrderItemSourceRefundDto orderItemSourceRefundDto;
2061         for (Map<String, Object> refundDetail : refundDetails) {
2e8393 2062             orderItemRefundDto = new OrderItemRefundDto();
97a5fc 2063             orderItemRefundDto.setOrderItemId(String.valueOf(refundDetail.get("id")));
Z 2064             orderItemRefundDto.setType(String.valueOf(refundDetail.get("type")));
2065
8eb9e6 2066             ////退款备注
C 2067             orderItemRefundDto.setRemarks(orderRefundDto.getRemarks());
2068             orderItemRefundDto.setRefundReason(orderRefundDto.getRefundReason());
2069
2e8393 2070             if(OrderItemConstants.TYPE_PROMOTION.equals(orderItemRefundDto.getType())
C 2071                     || OrderItemConstants.CARD_BAG.equals(orderItemRefundDto.getType())){
97a5fc 2072                 orderItemRefundDto.setRefundNum(0);
Z 2073                 refundSonDetails= (List<Map<String, Object>>) refundDetail.get("list");
2074                 orderItemSourceRefundDtos=new ArrayList<>();
2075                 for (Map<String, Object> refundSonDetail : refundSonDetails) {
2076                     orderItemSourceRefundDto=new OrderItemSourceRefundDto();
2077                     orderItemSourceRefundDto.setOrderItemSonId(String.valueOf(refundSonDetail.get("id")));
2078                     orderItemSourceRefundDto.setType(String.valueOf(refundSonDetail.get("type")));
2079                     orderItemSourceRefundDto.setRefundNum(Integer.parseInt(String.valueOf(refundSonDetail.get("notUsedNum"))));
8eb9e6 2080
C 2081                     //退款备注
2082                     orderItemSourceRefundDto.setRemarks(orderRefundDto.getRemarks());
2083                     orderItemSourceRefundDto.setRefundReason(orderRefundDto.getRefundReason());
2084
97a5fc 2085                     orderItemSourceRefundDtos.add(orderItemSourceRefundDto);
Z 2086                 }
2087                 orderItemRefundDto.setOrderItemSourceRefundDtos(orderItemSourceRefundDtos);
2088             }else {
2089                 orderItemRefundDto.setRefundNum(Integer.parseInt(refundDetail.get("notUsedNum").toString()) );
2090             }
2091             refundList.add(orderItemRefundDto);
2092         }
2093         orderRefundDto.setRefundList(refundList);
2094
2095         //获取退款资金信息
118d96 2096         OrderRefundDto  parameter= nextStep(ordersTotal,orderRefundDto);
97a5fc 2097
Z 2098         parameter.setOperatorId(orderRefundDto.getOperatorId());
2099         parameter.setIsRefund(orderRefundDto.getIsRefund());
2100         parameter.setIsApproval(orderRefundDto.getIsApproval());
2101         parameter.setRoleId(orderRefundDto.getRoleId());
2102         parameter.setPlatformSource(orderRefundDto.getPlatformSource());
04ce22 2103         parameter.setRefundOperationType(BaseEntity.NO);
f19292 2104         parameter.setRemarks(orderRefundDto.getRemarks());
F 2105         parameter.setRefundReason(orderRefundDto.getRefundReason());
7f9228 2106         parameter.setCouponList(parameter.getPayCouponList());
2e8393 2107
C 2108         //退款金额
2109         List<OrderPayMethodDto> refundPayMethodList = parameter.getPayMethodList();
2110         for(OrderPayMethodDto orderPayMethodDto:refundPayMethodList){
2111             orderPayMethodDto.setRefundNumberNo(orderPayMethodDto.getPayMethodNo());
2112             orderPayMethodDto.setRefundNumberName(orderPayMethodDto.getPayMethodName());
2113             orderPayMethodDto.setMoney(orderPayMethodDto.getPayTotal());
2114         }
2115
d993aa 2116         parameter.setRefundPayMethod(refundPayMethodList);
C 2117
97a5fc 2118         //调用退款处理退款逻辑
4df03d 2119         return partRefund(ordersTotal,parameter,thirtApplication);
97a5fc 2120     }
b9b969 2121
250fca 2122     /**
25d452 2123      * 伪造退款处理退款逻辑
250fca 2124      * @param orderRefundDto
Z 2125      * @return
2126      */
2127     @Override
2128     public PlatformResult forgePartRefund(OrderRefundDto orderRefundDto) {
25d452 2129         logger.info("退款打印参数:{}", JSON.toJSONString(orderRefundDto));
250fca 2130         //先判断项目的状态是否存在
Z 2131         OrdersTotal ordersTotal=null;
2132         try {
2133             ordersTotal=ordersTotalMapper.selectOneByKey(orderRefundDto.getOrderId());
2134             if(ordersTotal==null){
2135                 logger.info("取消订单流程:未找到总订单信息!订单id:{}",orderRefundDto.getOrderId());
2136                 return PlatformResult.failure(PlatformCode.ERROR_TIPS,"取消订单流程:未找到总订单信息!");
2137             }
2138         }catch (Exception e){
2139             logger.info("取消订单流程:根据订单id查询多条总订单信息!订单id:{}",orderRefundDto.getOrderId());
2140             return PlatformResult.failure(PlatformCode.ERROR_TIPS,"取消订单流程:根据订单id查询多条总订单信息!");
2141         }
2142
2143         if(!(OrderTotalConstants.STATUS_REFUND_NONE==ordersTotal.getRefundStatus()) &&
2144                 !(OrderTotalConstants.STATUS_REFUND_PART==ordersTotal.getRefundStatus())){
2145             throw new TipsException("订单标识错误,订单退款状态不正确!");
2146         }
2147
2148 //        orderRefundDto=parameterVerification(orderRefundDto);
2149
2150         return handleforgePartRefund(ordersTotal,orderRefundDto);
2151
2152     }
2153
892b96 2154
Z 2155
250fca 2156     /**
Z 2157      * 伪造处理退款详情
2158      */
2159     public PlatformResult  handleforgePartRefund(OrdersTotal ordersTotal,OrderRefundDto orderRefundDto){
2160
2161         //订单节点日志
2162         OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
2163         StringBuilder orderNodeBuilder = new StringBuilder();
2164
86bf93 2165         orderNodeBuilder.append("开始退款(WZ)");
250fca 2166
Z 2167         // 获取退款方式,退款项目,退款优惠卷
2168         List<OrderPayMethodDto> refundPayMethod=orderRefundDto.getRefundPayMethod();
2169         List<OrderItemRefundDto> refundList=orderRefundDto.getRefundList();
2170         List<OrderCouponRefunDto> couponList=orderRefundDto.getCouponList();
2171
2172         //客户选的退款方式总金额
2173         BigDecimal sumMoney=refundPayMethod.stream().map(OrderPayMethodDto::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
2174         //本次退款总金额
2175         BigDecimal refundSumMoney=refundList.stream().map(OrderItemRefundDto::getRefundMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
2176
2177         if(!OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
2178             if(sumMoney.compareTo(refundSumMoney)==1){
2179                 throw new TipsException("退款金额不能大于可退金额!");
2180             }
2181             orderNodeBuilder.append("-本次退款项目总金额:"+refundSumMoney+",客户选的退款方式总金额:"+sumMoney);
2182         }else {
2183             orderNodeBuilder.append("-本次退款项目总金额:"+ordersTotal.getActualTotal()+",客户选的退款方式总金额:"+sumMoney);
2184         }
2185
2186         Map<String, String> operator = ApiOrderUtil.getOperator(commonService, orderRefundDto.getOperatorId());//获取操作人信息
2187         SqlSentence sqlSentence = new SqlSentence();
2188         Map<String,Object> map=new HashMap<>();
2189         sqlSentence.setM(map);
2190
2191         //退款总记录
2192         orderNodeBuilder.append("-处理退款总记录");
2193         String totalCode = CreateNo.createTimeNo(systemParameterMapper, "R", 8, "yyyyMMddHHmmss");//总订单编号
25d452 2194         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 2195         refundRecord.setOperatorType(RefundRecord.OPERATOR_TYPE_EMPLOYEE);
Z 2196         Employee employee = commonService.selectOneByKey(EmployeeMapper.class,orderRefundDto.getOperatorId());
2197         refundRecord.setOperatorId(employee.getId());
2198         refundRecord.setRefundOperationType(orderRefundDto.getRefundOperationType());
2199         refundRecord.setOperatorName(employee.getCnName());
2200         refundRecordService.insert(refundRecord);
2201
2202         if(refundPayMethod!=null && refundPayMethod.size()>0){
2203             //处理退款方式记录表
4df03d 2204             handleRefundPayMethod(orderRefundDto,orderNodeBuilder,ordersTotal,refundRecord);
250fca 2205         }
Z 2206         if(refundList!=null && refundList.size()>0){
2207             //记录本次退款的项目详情
2208             //分摊比例
2209             //因为优惠卷抵扣金额可能超过订单的金额,所以不会有支付记录
2210             BigDecimal percentage;
2211             if(sumMoney.compareTo(BigDecimal.ZERO)==0){
2212                 percentage=new BigDecimal(1);
2213             }else {
2214                 percentage=sumMoney.divide(refundSumMoney,10,BigDecimal.ROUND_HALF_UP);
2215             }
2216
4df03d 2217             //handleRefundRecordItem(orderRefundDto,orderNodeBuilder,ordersTotal,refundRecord,percentage);
250fca 2218         }
Z 2219         if(couponList!=null && couponList.size()>0){
2220             //处理优惠卷
2221             handleOrderCouponRefunDto(couponList,orderNodeBuilder,ordersTotal,refundRecord);
2222         }
2223         try{
2224             orderNodeBuilder.append("-开始记录收入确认表");
2225             PerformanceInfoTool.handRefundPerformanceInfo(commonService,refundRecord);
2226             orderNodeBuilder.append("-记录收入确认表成功");
2227         }catch (Exception e){
2228             orderNodeBuilder.append("-记录收入确认表失败");
2229             logger.info("记录收入确认表,异常:{}",e.getMessage(),e);
071df8 2230             // 添加错误日志
A 2231             PerformanceInfoTool.addErrorLog(commonService, refundRecord.getId(), PerformanceInfo.ASSOCIATION_TYPE_GOODS_REFUND, e.getMessage());
250fca 2232         }
Z 2233         //记录操作日志
2234         orderNodeBuilder.append("-记录操作日志");
86bf93 2235         StringBuffer stringBuffer=new StringBuffer("操作人:"+operator.get("operatorName")+",进行退款(WZ)");
250fca 2236         OrderLog orderLog=new OrderLog(ordersTotal.getId(), OrderLogConstants.LOG_TYPE_REFUND,stringBuffer.toString()
Z 2237                 ,operator.get("operatorName"),operator.get("operatorId"),OrderTotalConstants.STATUS_CANCEL);
2238         commonService.insert(OrderLogMapper.class,orderLog);
2239
2240         orderNodeBuilder.append("-结束处理退款");
2241         ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_REFUND);
2242         ordersNodeLog.setContent(orderNodeBuilder.toString());
2243         ordersNodeLog.setOrderId(ordersTotal.getId());
2244         commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
2245
2246         return PlatformResult.success("成功");
2247     }
2248
892b96 2249     /**
Z 2250      * 根据订单 重新绑定订单退款状态
2251      *
2252      */
2253     @Override
2254     public void verifyOrderRefundStatus(OrdersTotal ordersTotalDto) {
2255         SqlSentence sqlSentence = new SqlSentence();
2256         Map<String, Object> sqlMap = new HashMap<>();
2257         sqlSentence.setM(sqlMap);
2258         sqlMap.put("isDel", BaseEntity.NO);
2259         sqlMap.put("orderId", ordersTotalDto.getId());
2260         sqlMap.put("type", OrderItemConstants.TYPE_PROJECT);
2261
4df03d 2262         sqlSentence.sqlSentence("SELECT * FROM  orders_total   WHERE  id = #{m.orderId}  and  isDel = #{m.isDel} ",sqlMap);
892b96 2263         OrdersTotal ordersTotal = ordersTotalMapper.selectOne(sqlSentence);
Z 2264         if(ordersTotal==null){
2265             throw new TipsException("订单标识错误,找不到订单!");
2266         }
2267         //查询二级订单
4df03d 2268         sqlSentence.sqlSentence("SELECT * FROM  order_item_source   WHERE  orderId = #{m.orderId}  and  type = #{m.type}  and  isDel = #{m.isDel} ",sqlMap);
892b96 2269         List<OrderItemSon> orderItemSonList=orderItemSonMapper.selectList(sqlSentence);
Z 2270
2271
2272         if(orderItemSonList!=null && orderItemSonList.size()>0){
2273             int oldRefundStatus;
2274             int newRefundStatus;
2275             UserProjectItem userProjectItem;
2276             for (OrderItemSon orderItemSon : orderItemSonList) {
2277                 if(OrderTotalConstants.STATUS_REFUND_FINSH==orderItemSon.getRefundStatus()){
2278                     oldRefundStatus=OrderTotalConstants.STATUS_REFUND_FINSH;
2279
ae6ff7 2280                     userProjectItem = PartialRefundUtil.getUserProject(orderItemSon.getId(),commonService);
892b96 2281
Z 2282                     if(userProjectItem.getNotUsedNum()>0){
2283                         newRefundStatus=OrderTotalConstants.STATUS_REFUND_PART;
2284                     }else {
2285                         newRefundStatus=oldRefundStatus;
2286                     }
2287
2288                     if(newRefundStatus!=oldRefundStatus){
2289                         sqlMap.put("refundStatus", newRefundStatus);
2290                         sqlMap.put("id", orderItemSon.getId());
4df03d 2291                         sqlSentence.sqlSentence(" refundStatus = #{m.refundStatus} WHERE id = #{m.id}  ",sqlMap);
892b96 2292                         orderItemSonMapper.updateWhere(sqlSentence);
Z 2293
2294                         sqlMap.put("refundStatus", newRefundStatus);
2295                         sqlMap.put("id", orderItemSon.getOrderItemId());
4df03d 2296                         sqlSentence.sqlSentence(" refundStatus = #{m.refundStatus} WHERE id = #{m.id}  ",sqlMap);
892b96 2297                         orderItemMapper.updateWhere(sqlSentence);
Z 2298                     }
2299
2300                 }
2301             }
2302             
2303         }
2304
2305         //查询二级订单
4df03d 2306         sqlSentence.sqlSentence("SELECT * FROM  order_item   WHERE  orderId = #{m.orderId}  and  type = #{m.type}  and  isDel = #{m.isDel} ",sqlMap);
892b96 2307         List<OrderItem> orderItemList=orderItemMapper.selectList(sqlSentence);
Z 2308         if(orderItemList!=null && orderItemList.size()>0){
2309             int oldRefundStatus;
2310             int newRefundStatus;
2311             UserProjectItem userProjectItem;
2312             for (OrderItem orderItem : orderItemList) {
2313                 oldRefundStatus=OrderTotalConstants.STATUS_REFUND_FINSH;
2314
ae6ff7 2315                 userProjectItem = PartialRefundUtil.getUserProject(orderItem.getId(),commonService);
892b96 2316
Z 2317                 if(userProjectItem.getNotUsedNum()>0){
2318                     newRefundStatus=OrderTotalConstants.STATUS_REFUND_PART;
2319                 }else {
2320                     newRefundStatus=oldRefundStatus;
2321                 }
2322
2323                 if(newRefundStatus!=oldRefundStatus){
2324                     sqlMap.put("refundStatus", newRefundStatus);
2325                     sqlMap.put("id", orderItem.getId());
4df03d 2326                     sqlSentence.sqlSentence(" refundStatus = #{m.refundStatus} WHERE id = #{m.id}  ",sqlMap);
892b96 2327                     orderItemMapper.updateWhere(sqlSentence);
Z 2328                 }
2329
2330             }
2331         }
2332
2333
2334         sqlMap.put("orderId",ordersTotal.getId());
4df03d 2335         sqlSentence.sqlSentence("select * from order_item WHERE  orderId=#{m.orderId} and isDel=0",sqlMap);
892b96 2336         List<OrderItem> orderItems=commonService.selectList(OrderItemMapper.class,sqlSentence);
Z 2337
2338         List<Integer> collect = orderItems.stream().map(o -> o.getRefundStatus()).collect(Collectors.toList());
2339         if(collect.contains(OrderTotalConstants.STATUS_REFUND_PART)){
2340             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
215be3 2341             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
892b96 2342         }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE) && collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
Z 2343             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
215be3 2344             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
892b96 2345         }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE)){
Z 2346             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
215be3 2347             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
892b96 2348         }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
Z 2349             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_FINSH);
2350             ordersTotal.setStatus(OrderTotalConstants.STATUS_CANCEL);
2351         }else {
2352             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
215be3 2353             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
892b96 2354         }
Z 2355         ordersTotal.setEditTime(new Date());
2356         commonService.updateAll(OrdersTotalMapper.class,ordersTotal);
2357     }
2358
fd7281 2359     /**作废退款*/
C 2360     @Override
2361     public void refundCancel(RefundCancelVo refundCancelVo, RefundRecord refundRecord,Employee employee,EmployeeRole employeeRole
2362             , ThirtApplication thirtApplication) {
2363
2364         //判断退款单状态
2365         if(refundRecord.getRefundStatus() != RefundStatus.STATUS_SUCC_REFUND){
2366             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作失败,退款单状态错误!");
2367         }
2368
2369         //获取订单信息
2370         OrdersTotal ordersTotal = ordersTotalMapper.selectOneByKey(refundRecord.getOrderId());
2371         if(ordersTotal == null){
2372             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作失败,获取订单信息失败!");
2373         }
2374
2375         SqlSentence sqlSentence = new SqlSentence();
2376         Map<String,Object> values = new HashMap<>();
2377         StringBuilder sql = new StringBuilder();
2378
2379         //填充数据,后面会用到
2380         refundRecord.setInvalidType(RefundRecord.OPERATOR_TYPE_EMPLOYEE);
2381         refundRecord.setInvalidRemarks(refundCancelVo.getRemarks());
2382
2383         //****更新退款单信息,更新完退款单再去做剩下的操作
2384         values.put("refundStatus",RefundStatus.STATUS_REFUND_CANCEL);
2385         values.put("refundStatusOld",RefundStatus.STATUS_SUCC_REFUND);
2386         values.put("id",refundRecord.getId());
2387         values.put("invalidTime",new Date());
2388         values.put("invalidType",RefundRecord.OPERATOR_TYPE_EMPLOYEE);
2389         values.put("invalidRemarks",refundCancelVo.getRemarks());
2390         sql.append("refundStatus = #{m.refundStatus},invalidTime = #{m.invalidTime},invalidRemarks = #{m.invalidRemarks},invalidType = #{m.invalidType}");
2391
2392         if(employee != null){
2393             refundRecord.setInvalidId(employee.getId());
2394             refundRecord.setInvalidNo(employee.getEmployeeNo());
2395             refundRecord.setInvalidName(employee.getCnName());
2396             values.put("invalidId",employee.getId());
2397             values.put("invalidNo",employee.getEmployeeNo());
2398             values.put("invalidName",employee.getCnName());
2399             sql.append(",invalidId = #{m.invalidId},invalidNo = #{m.invalidNo},invalidName = #{m.invalidName}");
2400         }
2401         if(employeeRole != null){
2402             refundRecord.setInvalidRoleNo(employeeRole.getRoleUniqueStr());
2403             refundRecord.setInvalidRoleName(employeeRole.getRoleName());
2404             values.put("invalidRoleNo",employeeRole.getRoleUniqueStr());
2405             values.put("invalidRoleName",employeeRole.getRoleName());
2406             sql.append(",invalidRoleNo = #{m.invalidRoleNo},invalidRoleName = #{m.invalidRoleName}");
2407         }
2408         if(thirtApplication != null){
2409             refundRecord.setInvalidAppId(thirtApplication.getAppId());
2410             refundRecord.setInvalidAppCode(thirtApplication.getAppIdCode());
2411             refundRecord.setInvalidAppName(thirtApplication.getName());
2412             values.put("invalidAppId",thirtApplication.getAppId());
2413             values.put("invalidAppCode",thirtApplication.getAppIdCode());
2414             values.put("invalidAppName",thirtApplication.getName());
2415             sql.append(",invalidAppId = #{m.invalidAppId},invalidAppCode = #{m.invalidAppCode},invalidAppName = #{m.invalidAppName}");
2416         }
2417         sql.append(" WHERE id = #{m.id} AND refundStatus = #{m.refundStatusOld}");
2418         sqlSentence.sqlUpdate(sql.toString(),values);
2419         if(refundRecordMapper.updateWhere(sqlSentence) != 1){
2420             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"操作失败,退款单状态已发生变化!");
2421         }
2422
b3fdea 2423         //订单系统日志
C 2424         StringBuilder orderNodeBuilder = new StringBuilder();
2425         orderNodeBuilder.append("开始作废退款");
2426
fd7281 2427         //判断订单类型
C 2428         if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
2429             //充值订单
b3fdea 2430             OrderRefundCancelTool.rechargeHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_CANCEL,"作废退款",orderNodeBuilder,commonService);
fd7281 2431         }else{
160c33 2432             //处理子单
C 2433             OrderRefundCancelTool.refundRecordItemHandle(ordersTotal,refundRecord,commonService);
fd7281 2434         }
C 2435
160c33 2436         //处理订单活动
b3fdea 2437         OrderRefundCancelTool.activityRuleHandle(ordersTotal,refundRecord,OrderRefundCancelTool.OPT_TYPE_CANCEL,"作废退款",orderNodeBuilder,commonService);
160c33 2438         //处理订单优惠券
b3fdea 2439         OrderRefundCancelTool.handCoupon(ordersTotal,refundRecord,orderNodeBuilder,commonService);
4ebb90 2440         //处理总退款方式
b3fdea 2441         List<RefundRecordMethod> refundRecordMethodList= OrderRefundCancelTool.refundRecordMotnedHandle(refundRecord,ordersTotal,orderNodeBuilder,commonService);
C 2442
2443         //操作的现金金额
2444         BigDecimal cashTotal = BigDecimal.ZERO;
2445         for(RefundRecordMethod refundRecordMethod:refundRecordMethodList){
2446             if(refundRecordMethod.getIsMoneyPay().equals(RefundRecordMethod.YES)){
2447                 cashTotal = cashTotal.add(refundRecordMethod.getActualTotal());
2448             }
2449         }
2450
2451         //报错订单系统日志
fd7281 2452
160c33 2453         //****更改总订单退款状态
C 2454         values.clear();
2455         values.put("orderId",ordersTotal.getId());
2456         sqlSentence.sqlSentence("select * from order_item WHERE orderId=#{m.orderId} and isDel=0",values);
2457         List<OrderItem> orderItemList=commonService.selectList(OrderItemMapper.class,sqlSentence);
2458
2459         values.clear();
2460         values.put("oldStatus",ordersTotal.getStatus());
2461         values.put("oldRefundStatus",ordersTotal.getRefundStatus());
2462
2463         List<Integer> collect = orderItemList.stream().map(OrderItem::getRefundStatus).collect(Collectors.toList());
2464         if(collect.contains(OrderTotalConstants.STATUS_REFUND_PART)){
2465             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
2466             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
2467             ordersTotal.setReTotal(orderItemList.stream().map(OrderItem::getReTotal).reduce(BigDecimal.ZERO,BigDecimal::add));
2468         }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE) && collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
2469             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
2470             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
2471             ordersTotal.setReTotal(orderItemList.stream().map(OrderItem::getReTotal).reduce(BigDecimal.ZERO,BigDecimal::add));
2472         }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE)){
2473             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
2474             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
2475             ordersTotal.setReTotal(BigDecimal.ZERO);
2476         }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
2477             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_FINSH);
2478             ordersTotal.setStatus(OrderTotalConstants.STATUS_CANCEL);
2479             ordersTotal.setReTotal(orderItemList.stream().map(OrderItem::getReTotal).reduce(BigDecimal.ZERO,BigDecimal::add));
2480         }else {
2481             if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
2482                 if(ordersTotal.getReTotal().compareTo(refundRecord.getRefundTotal()) == 0){
2483                     ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
2484                     ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
2485                     ordersTotal.setReTotal(ordersTotal.getReTotal().subtract(refundRecord.getRefundTotal()));
2486                 }else if(ordersTotal.getReTotal().compareTo(refundRecord.getRefundTotal()) > 0){
2487                     ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
2488                     ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
2489                     ordersTotal.setReTotal(ordersTotal.getReTotal().subtract(refundRecord.getRefundTotal()));
2490                 }
2491             }else{
2492                 ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
2493                 ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
2494                 ordersTotal.setReTotal(ordersTotal.getReTotal().subtract(refundRecord.getRefundTotal()));
2495             }
2496         }
2497         ordersTotal.setIsSyncOrder(BaseEntity.NO);
2498
2499         values.put("isSyncOrder",BaseEntity.NO);
2500         values.put("status",ordersTotal.getStatus());
2501         values.put("refundStatus",ordersTotal.getRefundStatus());
2502         values.put("reTotal",ordersTotal.getReTotal());
2503         values.put("id",ordersTotal.getId());
2504         sqlSentence.sqlUpdate("isSyncOrder = #{m.isSyncOrder},status = #{m.status},refundStatus = #{m.refundStatus},reTotal = #{m.reTotal}" +
2505                 " WHERE id = #{m.id} AND status = #{m.oldStatus} AND refundStatus = #{m.oldRefundStatus}",values);
2506         if(commonService.updateWhere(OrdersTotalMapper.class,sqlSentence) != 1){
2507             throw new TipsException("作废失败,订单状态已发生改变!");
2508         }
fd7281 2509
b3fdea 2510         //额外的操作,升降级,收入确认表
C 2511         additionalOperate(ordersTotal,refundRecord,cashTotal,orderNodeBuilder,customParameter,commonService);
2512
2513         //记录日志(处理到具体节点(成功和失败))
2514         OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
2515         orderNodeBuilder.append("-作废退款单结束");
2516         ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_REFUND_CANCEL);
2517         ordersNodeLog.setContent(orderNodeBuilder.toString());
2518         ordersNodeLog.setOrderId(ordersTotal.getId());
2519         commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
2520
2521     }
2522
2523     /**额外操作,不影响主流程*/
2524     public static void additionalOperate(OrdersTotal ordersTotal,RefundRecord refundRecord,BigDecimal total,StringBuilder orderNodeBuilder,CustomParameter customParameter,CommonService commonService){
2525         if(BigDecimal.ZERO.compareTo(total) < 0){
2526             try {
2527                 orderNodeBuilder.append("-开始处理用户升降级,金额:").append(total);
2528                 UserLevelUtil.refund(ordersTotal.getUserId(),ordersTotal.getId(),total,ordersTotal.getAppIdCode());
2529                 orderNodeBuilder.append("-处理用户升降级成功");
2530             }catch (Exception e){
2531                 String snapshot="处理用户升降级失败";
2532                 orderNodeBuilder.append("-处理用户升降级失败,异常原因:").append(e.getMessage());
2533                 logger.error("处理用户升降级失败:" + e.getMessage());
2534                 //发送企业微信通知给工作人员
2535                 SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),snapshot,commonService,customParameter);
2536             }
2537         }
2538         try{
2539             orderNodeBuilder.append("-开始记录收入确认表");
2540             PerformanceInfoTool.refundCancelPerformanceInfo(commonService,refundRecord);
2541             orderNodeBuilder.append("-记录收入确认表成功");
2542         }catch (Exception e){
2543             orderNodeBuilder.append("-记录收入确认表失败");
2544             logger.info("记录收入确认表,异常:{}",e.getMessage(),e);
2545             // 添加错误日志
2546             PerformanceInfoTool.addErrorLog(commonService, refundRecord.getId(), PerformanceInfo.ASSOCIATION_TYPE_GOODS_REFUND, e.getMessage());
2547         }
fd7281 2548     }
C 2549
4dc6e5 2550 }