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