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