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