chenjiahe
2023-03-31 1869f358a6aaccf4e4f76df73f10ef5e1e5d8313
提交 | 用户 | 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;
1869f3 31 import com.hx.phip.util.api.PartialRefundUtil;
4df03d 32 import com.hx.phip.tool.order.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      */
876     public RefundRecord insertRefundInfo(OrderRefundDto orderRefundDto,OrdersTotal ordersTotal,StringBuilder orderNodeBuilder
877             , ThirtApplication thirtApplication){
878
879         ///////退款总表数据填充
880         //生成退款编号
881         String totalCode = createNoService.createNo("R",System.currentTimeMillis()+"",8);
882         RefundRecord refundRecord=new RefundRecord(totalCode,ordersTotal.getShopId(),ordersTotal.getShopName(),orderRefundDto.getRefundTotal()
883                 , RefundStatus.STATUS_APPLY_REFUND,0, RefundSoruceConstants.TYPE_SOURCE_ORDER,orderRefundDto.getRemarks(),ordersTotal.getId(),ordersTotal.getUserId());
884         refundRecord.setOperatorType(RefundRecord.OPERATOR_TYPE_EMPLOYEE);
885         Employee employee = commonService.selectOneByKey(EmployeeMapper.class,orderRefundDto.getOperatorId());
886         if(employee == null){
887             throw new TipsException("操作人标识错误!");
888         }
889         refundRecord.setOperatorId(employee.getId());
890         refundRecord.setRefundOperationType(orderRefundDto.getRefundOperationType());
891         refundRecord.setOperatorName(employee.getCnName());
892         /////退款的备注
893         refundRecord.setRemarks(orderRefundDto.getRemarks());
894         refundRecord.setRefundReason(orderRefundDto.getRefundReason());
895         refundRecord.setOperatorAppId(thirtApplication.getAppId());
896         refundRecord.setOperatorAppCode(thirtApplication.getAppIdCode());
897         refundRecord.setOperatorAppName(thirtApplication.getName());
898         refundRecordService.insert(refundRecord);
899
900         //退款方式处理
901         List<RefundRecordMethod> refundRecordMethodList = null;
ae6ff7 902         if(orderRefundDto.getRefundPayMethod() !=null && orderRefundDto.getRefundPayMethod().size() > 0){
4df03d 903             refundRecordMethodList = handleRefundPayMethod(orderRefundDto,orderNodeBuilder,ordersTotal,refundRecord);
C 904         }
905
906         //退款的子项处理
907         if(orderRefundDto.getRefundList()!=null && orderRefundDto.getRefundList().size()>0){
ae6ff7 908             insertRefundRecordItem(orderRefundDto,orderNodeBuilder,ordersTotal,refundRecord,refundRecordMethodList);
4df03d 909         }
C 910         //回退的优惠卷处理
911         if(orderRefundDto.getCouponList() != null && orderRefundDto.getCouponList().size()>0){
912             handleOrderCouponRefunDto(orderRefundDto.getCouponList(),orderNodeBuilder,ordersTotal,refundRecord);
913         }
914
915         return refundRecord;
edf5ea 916     }
Z 917
918     /**
919      * 退款-处理活动规则增值金和积分
4df03d 920      * @param commonService 映射对象
C 921      * @param operationId 操作人标识
922      * @param operationNme 操作人名称
923      * @param sqlSentence 映射对象
924      * @param map 映射对象
925      * @param refundRecord 退款记录
926      * @param ordersTotal 订单
927      * @param optType 操作:"0"减 1加
edf5ea 928      */
Z 929     private static void handActivityRule(CommonService commonService, String operationId, String operationNme, SqlSentence sqlSentence,
930                                          Map<String, Object> map, RefundRecord refundRecord, OrdersTotal ordersTotal, OrderInfo orderInfo,int optType) {
931         if(orderInfo!=null && StringUtils.noNull(orderInfo.getActivityId())){
932             ActivityRule activityRule=commonService.selectOneByKeyBlob(ActivityRuleMapper.class,orderInfo.getActivityId());
933             if(activityRule!=null){
934                 map.put("activityRuleId",activityRule.getId());
935                 map.put("type", ActivityAction.TYPE_INTEGRAL);
936                 map.put("type1",ActivityAction.TYPE_VALUEADDEDFUND);
937                 map.put("type2",ActivityAction.TYPE_COUPON);
4df03d 938                 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 939                 List<ActivityAction> activityActions = commonService.selectList(ActivityActionMapper.class, sqlSentence);
Z 940                 if(activityActions!=null && activityActions.size()>0){
941                     for (ActivityAction activityAction : activityActions) {
942                         if(ActivityAction.TYPE_INTEGRAL.equals(activityAction.getType())){
943                             //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
944                             if(new BigDecimal(activityAction.getWorth()).negate().compareTo(BigDecimal.ZERO)!=0){
945                                 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);
946                             }
947                         }else if(ActivityAction.TYPE_VALUEADDEDFUND.equals(activityAction.getType())){
948                             //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
949                             if(new BigDecimal(activityAction.getWorth()).negate().compareTo(BigDecimal.ZERO)!=0){
950                                 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);
951                             }
952                         }else if(ActivityAction.TYPE_COUPON.equals(activityAction.getType())){
953                             map.put("oldValidState",optType==0?BaseEntity.YES:BaseEntity.NO);
954                             map.put("newValidState",optType==0?BaseEntity.NO:BaseEntity.YES);
955                             map.put("couponId",activityAction.getCrmCouponId());
956                             map.put("commonId",ordersTotal.getId());
4df03d 957                             sqlSentence.sqlSentence(" validState=#{m.newValidState} where couponId=#{m.couponId} and commonId=#{m.commonId} and validState=#{m.oldValidState} ",map);
edf5ea 958                             commonService.updateWhere(CouponNumberMapper.class,sqlSentence);
Z 959                         }
960                     }
961                 }
962             }
963         }
964
9d4e6f 965     }
4df03d 966
da4ad2 967     /**
Z 968      * 对接审批
969      */
42a0e7 970     public PlatformResult handleApproval(OrdersNodeLog ordersNodeLog,StringBuilder orderNodeBuilder,OrdersTotal ordersTotal,CancelOrder cancelOrder,RefundRecord refundRecord){
25d452 971         orderNodeBuilder.append("-退款需要审批,开始对接营销中心");
42a0e7 972
Z 973
974         OrderPartRefundDto orderPartRefundDto=new OrderPartRefundDto();
975         OrdersTotalDto ordersTotalDto=new OrdersTotalDto();
976         BeanUtils.copyProperties(ordersTotal, ordersTotalDto);
977
978         orderPartRefundDto.setOrdersTotalDto(ordersTotalDto);//填充主订单信息
979
980
981         //填充操作人,用户的基本信息
982         orderPartRefundDto.setOrdersTotalDto(ordersTotalDto);
983         orderPartRefundDto.setOperatorId(cancelOrder.getOperatorId());
984         orderPartRefundDto.setOpName(cancelOrder.getOperatorName());
985         orderPartRefundDto.setShopId(cancelOrder.getShopId());
986         orderPartRefundDto.setShopName(cancelOrder.getShopName());
987         orderPartRefundDto.setRoleId(cancelOrder.getRoleId());
988         orderPartRefundDto.setRoleUniqueStr(cancelOrder.getRoleStr());
117ee9 989         if(StringUtils.noNull(refundRecord.getRemarks())){
C 990             orderPartRefundDto.setRemark(refundRecord.getRemarks());
991         }else{
992             orderPartRefundDto.setRemark(cancelOrder.getOperatorName()+"退款,订单号:"+ordersTotal.getOrderNo());
993         }
994
42a0e7 995         orderPartRefundDto.setUserId(ordersTotal.getUserId());
Z 996
997         //本次退款金额
998         orderPartRefundDto.setRefundTotal(refundRecord.getRefundTotal());
999
1000         /**本次退款支付方式*/
1001         SqlSentence sqlSentence = new SqlSentence();
1002         Map<String,Object> map=new HashMap<>();
4df03d 1003
42a0e7 1004         map.put("refundRecordId", refundRecord.getId());
4df03d 1005         sqlSentence.sqlSentence("SELECT refundNumberNo AS payMethodNo,refundName AS payMethodName,actualTotal as refundMoney,refundRecordId as payMethodId FROM refund_record_method " +
C 1006                 " WHERE refundRecordId=#{m.refundRecordId} ",map);
42a0e7 1007         List<Map<String, Object>> refundMethodList = commonService.selectListMap(RefundRecordMethodMapper.class,sqlSentence);
Z 1008         if(refundMethodList!=null && refundMethodList.size()!=0){
1009             JSONArray refundMethodArray=new JSONArray();
1010             refundMethodArray.addAll(refundMethodList);
1011             List<PartRefundPayDto> partRefundPayDtoList=refundMethodArray.toJavaList(PartRefundPayDto.class);
1012             orderPartRefundDto.setPartRefundPayDtoList(partRefundPayDtoList);
1013         }
1014         /**本次退款项目*/
1015         //退款一级项目
4df03d 1016         sqlSentence.sqlSentence("SELECT type AS projectType, commonId AS projectId, goodsNo AS projectNo, goodsName AS projectName, refundNum AS refundNum  " +
C 1017                 " FROM refund_record_item WHERE refundRecordId=#{m.refundRecordId} AND refundNum>0",map);
42a0e7 1018         List<Map<String, Object>> refundRecordItemList = commonService.selectListMap(RefundRecordItemMapper.class,sqlSentence);
Z 1019         JSONArray refundProjectDtoArray=new JSONArray();
1020         if(refundRecordItemList!=null && refundRecordItemList.size()!=0){
1021             refundProjectDtoArray.addAll(refundRecordItemList);
1022         }
1023         //退款二级项目
4df03d 1024         sqlSentence.sqlSentence("SELECT type AS projectType, commonId AS projectId, goodsNo AS projectNo, goodsName AS projectName, refundNum AS refundNum " +
C 1025                 " FROM refund_record_item_source   WHERE refundRecordId=#{m.refundRecordId} AND refundNum>0",map);
42a0e7 1026         List<Map<String, Object>> refundRecordItemSourceList = commonService.selectListMap(RefundRecordItemSourceMapper.class,sqlSentence);
Z 1027         if(refundRecordItemSourceList!=null && refundRecordItemSourceList.size()!=0){
1028             refundProjectDtoArray.addAll(refundRecordItemSourceList);
1029         }
1030         if(refundProjectDtoArray.size()>0){
1031             List<RefundProjectDto> refundProjectDtoList=refundProjectDtoArray.toJavaList(RefundProjectDto.class);
1032             orderPartRefundDto.setRefundProjectDtoList(refundProjectDtoList);
1033         }
1034
1035
25d452 1036         logger.info("调用营销中心审批退款入参:{}",JSONObject.toJSONString(orderPartRefundDto));
909b33 1037         Result result= mOrderService.applyPartRefund(orderPartRefundDto);
Z 1038 //        Result result= JSONObject.parseObject("{\"code\":\"100\",\"msg\":\"SUCCESS\",\"data\":{\"applyId\":\"6204eb10753511ed90ed525400b8510a\"}}",Result.class);
25d452 1039         logger.info("调用营销中心审批退款返回:{}",JSONObject.toJSONString(result));
42a0e7 1040         if (result != null) {
Z 1041             result.checkTips();
1042             JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(result.getData()));
1043             if(!object.isEmpty()){
1044                 String applyId = object.getString("applyId");
1045                 cancelOrder.setApplyId(applyId);
b9b969 1046                 cancelOrder.setRefundRecordId(refundRecord.getId());
42a0e7 1047                 commonService.updateAll(CancelOrderMapper.class,cancelOrder);
Z 1048
542dc1 1049                 ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_APPLY);
42a0e7 1050                 commonService.updateAll(OrdersTotalMapper.class,ordersTotal);
Z 1051
5425ba 1052 //                logger.info("调用营销中心成功,订单开始审核");
Z 1053                 orderNodeBuilder.append("-调用营销中心成功,订单开始审核");
42a0e7 1054                 ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_REFUND);
Z 1055                 ordersNodeLog.setContent(orderNodeBuilder.toString());
1056                 ordersNodeLog.setOrderId(ordersTotal.getId());
1057                 commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
1058
1059                 orderNodeBuilder.append("-调用营销中心成功,订单开始审核");
1060
1061                 return PlatformResult.success("订单正在审核中");
1062             }else{
1063                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求营销助手审批接口报错,data返回为空!");
1064             }
1065         } else {
1066             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求营销助手审批接口报错,返回为空!");
1067         }
1068     }
1069
da4ad2 1070     /**
Z 1071      * 记录退款订单记录日志
1072      */
9d4e6f 1073     public CancelOrder handleCancelOrder(OrdersTotal ordersTotal,OrderRefundDto orderRefundDto){
Z 1074         //记录取消日志
1075         CancelOrder cancelOrder=new CancelOrder();
1076         cancelOrder.setOrderId(ordersTotal.getId());
1077         Employee employee = commonService.selectOneByKey(EmployeeMapper.class,orderRefundDto.getOperatorId());
1078         if(employee==null){
1079             cancelOrder.setOperatorId(orderRefundDto.getOperatorId());
1080             cancelOrder.setOperatorName("找不到对应员工");
1081         }else {
1082             cancelOrder.setOperatorId(employee.getId());
1083             cancelOrder.setOperatorName(employee.getCnName());
1084         }
1085
1086         EmployeeRole employeeRole=commonService.selectOneByKey(EmployeeRoleMapper.class,orderRefundDto.getRoleId());
1087         if(employeeRole==null){
1088             cancelOrder.setRoleId(orderRefundDto.getRoleId());
1089             cancelOrder.setRoleStr("找不到对应角色");
1090             cancelOrder.setShopId(employeeRole.getShopId());
1091             cancelOrder.setShopName("找不到对应的门店");
1092         }else {
1093
1094             cancelOrder.setRoleId(employeeRole.getRoleTypeId());
1095             cancelOrder.setRoleStr(employeeRole.getRoleUniqueStr());
1096             Shop shop=commonService.selectOneByKey(ShopMapper.class,employeeRole.getShopId());
1097             if(shop==null){
1098                 cancelOrder.setShopId(employeeRole.getShopId());
1099                 cancelOrder.setShopName("找不到对应的门店");
1100             }else {
1101                 cancelOrder.setShopId(shop.getId());
1102                 cancelOrder.setShopName(shop.getName());
1103             }
1104
1105         }
1106         cancelOrder.setIsApproval(orderRefundDto.getIsApproval());
1107         cancelOrder.setIsRefund(orderRefundDto.getIsRefund());
1108         cancelOrder.setPlatformSource(orderRefundDto.getPlatformSource());
1109         commonService.insert(CancelOrderMapper.class,cancelOrder);
1110
1111         return cancelOrder;
1112     }
e3fa0c 1113
da4ad2 1114     /**
Z 1115      * 处理退款方式记录表
1116      */
4df03d 1117     public List<RefundRecordMethod> handleRefundPayMethod(OrderRefundDto orderRefundDto,StringBuilder orderNodeBuilder,OrdersTotal ordersTotal,RefundRecord refundRecord){
69ed11 1118         orderNodeBuilder.append("-记录退款方式:");
e3fa0c 1119
4df03d 1120         //获取订单可退款方式
C 1121         List<PayMethodVo> payMethodVoList = refundMapper.selectConsumePayList(ordersTotal.getId());
e3fa0c 1122
4df03d 1123         Map<String, PayMethodVo> payMethodVoMap = payMethodVoList.stream().collect(
C 1124                 Collectors.toMap(PayMethodVo::getNumberNo,(a) -> a));
e3fa0c 1125
4df03d 1126         List<RefundRecordMethod> refundRecordMethodList = new ArrayList<>();
e3fa0c 1127
4df03d 1128         PayMethodVo payMethodVo;
C 1129         RefundRecordMethod refundRecordMethod=null;
1130         RefundMethodTransformation refundMethodTransformation=null;
1131         for (OrderPayMethodDto orderPayMethodDto : orderRefundDto.getRefundPayMethod()) {
e3fa0c 1132
4df03d 1133             payMethodVo = payMethodVoMap.get(orderPayMethodDto.getPayMethodNo());
C 1134             //判断是不是在支付方式里面的
1135             if (payMethodVo == null){
1136                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"可退支付方式未找到对应的支付:"+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]");
da4ad2 1137             }
ae6ff7 1138             //判断支付方式
4df03d 1139             PaymentMethod payMethod = paymentMethodService.selectNumberNoUncheckUp(orderPayMethodDto.getPayMethodNo());
C 1140             if(payMethod == null){
1141                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到对应的支付:"+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]");
e3fa0c 1142             }
4df03d 1143             //判断退款方式
C 1144             PaymentMethod refundMethod = paymentMethodService.selectNumberNoUncheckUp(orderPayMethodDto.getRefundNumberNo());
e3fa0c 1145             if(refundMethod==null){
ae6ff7 1146                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到退款方式:"+orderPayMethodDto.getRefundNumberName()+"["+orderPayMethodDto.getRefundNumberNo()+"]");
4df03d 1147             }
C 1148             if(orderPayMethodDto.getMoney() == null){
ae6ff7 1149                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请填写退款方式["+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]"+"]金额");
C 1150             }
1151             //判断金额
1152             if(payMethodVo.getSurplusTotal().compareTo(orderPayMethodDto.getMoney()) < 0){
1153                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"退款金额错误:"+orderPayMethodDto.getPayMethodName()+"["+orderPayMethodDto.getPayMethodNo()+"]");
e3fa0c 1154             }
da4ad2 1155
e3fa0c 1156             //新增转换表记录
4df03d 1157             refundMethodTransformation = new RefundMethodTransformation();
e3fa0c 1158             BeanUtils.copyProperties(orderPayMethodDto, refundMethodTransformation);
4df03d 1159             refundMethodTransformation.setRefundTotal(orderPayMethodDto.getMoney());
431d07 1160             refundMethodTransformation.setRefundRecordId(refundRecord.getId());
95147d 1161             refundMethodTransformationMapper.insert(refundMethodTransformation);
da4ad2 1162
4df03d 1163             //退回客户的支付方式
C 1164             refundRecordMethod = new RefundRecordMethod();
ae6ff7 1165             refundRecordMethod.setType(refundRecord.getSourceType());
4df03d 1166             refundRecordMethod.setNumberNo(payMethod.getNumberNo());
C 1167             refundRecordMethod.setPaymentMethodId(payMethod.getId());
1168             refundRecordMethod.setName(payMethod.getName());
1169             refundRecordMethod.setIsMoneyPay(payMethodVo.getIsMoneyPay());
1170             refundRecordMethod.setIsExecute(payMethodVo.getIsExecute());
1171
1172             refundRecordMethod.setRefundNumberNo(refundMethod.getNumberNo());
1173             refundRecordMethod.setRefundName(refundMethod.getName());
1174             refundRecordMethod.setRefundMethodId(refundMethod.getId());
1175             refundRecordMethod.setActualTotal(orderPayMethodDto.getMoney());
1176             refundRecordMethod.setRefundMethodId(refundMethod.getId());
1177             refundRecordMethod.setIsMoneyPayRefund(refundMethod.getIsMoneyPay());
1178             refundRecordMethod.setIsExecuteRefund(refundMethod.getIsExecute());
1179
1180             refundRecordMethod.setRefundMethodTransId(refundMethodTransformation.getId());
1181             refundRecordMethod.setRemarks(orderPayMethodDto.getRemarks());
1182
1183             refundRecordMethodService.insert(refundRecordMethod);
1184             refundRecordMethodList.add(refundRecordMethod);
e3fa0c 1185         }
4df03d 1186         return refundRecordMethodList;
e3fa0c 1187     }
4df03d 1188
da4ad2 1189     /**
Z 1190      * 退款记录子项
1191      */
ae6ff7 1192     public void insertRefundRecordItem(OrderRefundDto orderRefundDto,StringBuilder orderNodeBuilder,OrdersTotal ordersTotal,RefundRecord refundRecord,List<RefundRecordMethod> refundRecordMethodList){
e3fa0c 1193
431d07 1194         orderNodeBuilder.append("-记录退款详情");
542dc1 1195
ae6ff7 1196         //计算金额占比,客户选择退款总金额和可退总金额占比
4df03d 1197         BigDecimal percentage;
C 1198         if(orderRefundDto.getTotalAmount().compareTo(BigDecimal.ZERO) < 1){
1199             percentage = BigDecimal.ZERO;
1200         }else {
1201             percentage = orderRefundDto.getRefundTotal().divide(orderRefundDto.getTotalAmount(),15,RoundingMode.HALF_UP);
1202         }
542dc1 1203
ae6ff7 1204         //总退款金额,用于后面计算分摊金额
4df03d 1205         BigDecimal refundTotal = refundRecord.getRefundTotal();
C 1206
ae6ff7 1207         //后面设计分配金额问题,要进行升序排序,避免到最后不够
C 1208         List<OrderItemRefundDto> refundList = orderRefundDto.getRefundList();
1209         refundList = refundList.stream().sorted(Comparator.comparing(OrderItemRefundDto::getApproveRefundTotal)).collect(Collectors.toList());
4df03d 1210
C 1211         /////引用参数
1212         RefundRecordItem refundRecordItem;
de3024 1213         OrderItemRefundDto orderItemRefundDto;
4df03d 1214         OrderItem orderItem;
ae6ff7 1215         for(int i = 0;i < refundList.size();i++){
C 1216             orderItemRefundDto = refundList.get(i);
de3024 1217
4df03d 1218             orderItem = orderItemMapper.selectOneByKey(orderItemRefundDto.getOrderItemId());
C 1219             if(orderItem == null){
1220                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"子订单标识错误!");
de3024 1221             }
Z 1222
4df03d 1223             //////数据填充
C 1224             refundRecordItem = new RefundRecordItem();
1225             refundRecordItem.setType(orderItem.getType());
1226             refundRecordItem.setGoodsNo(orderItem.getGoodsNo());
1227             refundRecordItem.setSpecs(orderItem.getSpecs());
1228             refundRecordItem.setCommonId(orderItem.getCommonId());
1229             refundRecordItem.setHeadPrice(orderItem.getCurPrice());
1230             refundRecordItem.setRefundNum(orderItemRefundDto.getRefundNum());
1231             refundRecordItem.setRefundRecordId(refundRecord.getId());
1232             refundRecordItem.setOrderItemId(orderItem.getId());
1233             refundRecordItem.setOccupyRefundTotal(orderItemRefundDto.getApproveRefundTotal());
77f162 1234             ////退款备注
C 1235             if(StringUtils.isEmpty(orderItemRefundDto.getRemarks())){
1236                 orderItemRefundDto.setRemarks(refundRecord.getRemarks());
1237             }
1238             if(StringUtils.isEmpty(orderItemRefundDto.getRefundReason())){
1239                 orderItemRefundDto.setRemarks(refundRecord.getRefundReason());
1240             }
8eb9e6 1241             refundRecordItem.setRemarks(orderItemRefundDto.getRemarks());
C 1242             refundRecordItem.setRefundReason(orderItemRefundDto.getRefundReason());
4df03d 1243
ae6ff7 1244             //////////分配退款金额
C 1245             if(i == refundList.size()-1){
4df03d 1246                 refundRecordItem.setRefundMoney(refundTotal);
C 1247             }else{
1248                 refundRecordItem.setRefundMoney(orderItemRefundDto.getApproveRefundTotal().multiply(percentage).setScale(2,RoundingMode.UP));
1249             }
1250             if(refundRecordItem.getRefundMoney().compareTo(orderItemRefundDto.getApproveRefundTotal()) > 0){
1251                 refundRecordItem.setRefundMoney(orderItemRefundDto.getApproveRefundTotal());
1252             }
ae6ff7 1253             //判断与未分配剩余金额
4df03d 1254             if(refundRecordItem.getRefundMoney().compareTo(refundTotal) > 0){
C 1255                 refundRecordItem.setRefundMoney(refundTotal);
1256             }
da4ad2 1257             refundRecordItemService.insert(refundRecordItem);
ae6ff7 1258             //计算剩余要分配的退款总金额
C 1259             refundTotal = refundTotal.subtract(refundRecordItem.getRefundMoney()).setScale(2,RoundingMode.HALF_UP);
da4ad2 1260
ae6ff7 1261             //子单子项处理
1869f3 1262             insertRefundRecordItemTwo(refundRecordItem,refundRecord,orderItemRefundDto.getOrderItemSourceRefundDtos());
e3fa0c 1263         }
4df03d 1264
1869f3 1265         if(refundTotal.compareTo(BigDecimal.ZERO) > 0){
C 1266             throw new TipsException("退款金额分配错误[01]!");
1267         }
1268
e3fa0c 1269     }
da4ad2 1270
4df03d 1271     /**二级子单处理*/
1869f3 1272     public void insertRefundRecordItemTwo(RefundRecordItem recordItem,RefundRecord refundRecord,List<OrderItemSourceRefundDto> orderItemSourceRefundDtos){
4df03d 1273         if(orderItemSourceRefundDtos == null || orderItemSourceRefundDtos.size() == 0){
da4ad2 1274             return;
Z 1275         }
ae6ff7 1276
C 1277         //计算占比
1278         BigDecimal percentage;
1279         if(recordItem.getOccupyRefundTotal().compareTo(BigDecimal.ZERO) > 0){
1280             percentage = recordItem.getRefundMoney().divide(recordItem.getOccupyRefundTotal(),15,RoundingMode.HALF_UP);
1281         }else{
1282             percentage = BigDecimal.ZERO;
1283         }
1284
1285         //进行升序排序,避免后面不够
1286         orderItemSourceRefundDtos = orderItemSourceRefundDtos.stream().sorted(Comparator.comparing(OrderItemSourceRefundDto::getApproveRefundTotal)).collect(Collectors.toList());
431d07 1287
4df03d 1288         //退款总金额
C 1289         BigDecimal refundTotal = recordItem.getRefundMoney();
da4ad2 1290
4df03d 1291         OrderItemSon orderItemSon;
C 1292         OrderItemSourceRefundDto orderItemSourceRefundDto;
1293         RefundRecordItemSource refundRecordItemSource;
1869f3 1294
4df03d 1295         for(int i = 0;i<orderItemSourceRefundDtos.size();i++){
C 1296             orderItemSourceRefundDto = orderItemSourceRefundDtos.get(i);
da4ad2 1297
4df03d 1298             orderItemSon = orderItemSonMapper.selectOneByKey(orderItemSourceRefundDto.getOrderItemSonId());
C 1299             if(orderItemSon == null){
1300                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"子订单标识错误[024]!");
1301             }
da4ad2 1302
4df03d 1303             //////数据填充
C 1304             refundRecordItemSource = new RefundRecordItemSource();
1305             refundRecordItemSource.setType(orderItemSon.getType());
1306             refundRecordItemSource.setGoodsNo(orderItemSon.getGoodsNo());
1307             refundRecordItemSource.setSpecs(orderItemSon.getSpecs());
1308             refundRecordItemSource.setCommonId(orderItemSon.getGoodsId());
1309             refundRecordItemSource.setHeadPrice(orderItemSon.getCurPrice());
1310             refundRecordItemSource.setRefundNum(orderItemSourceRefundDto.getRefundNum());
1311             refundRecordItemSource.setRefundRecordId(orderItemSon.getId());
1312             refundRecordItemSource.setOrderItemSonId(orderItemSon.getId());
1313             refundRecordItemSource.setOccupyRefundTotal(orderItemSourceRefundDto.getApproveRefundTotal());
1314             ////退款备注
1315             if(StringUtils.isEmpty(orderItemSourceRefundDto.getRemarks())){
1316                 orderItemSourceRefundDto.setRemarks(refundRecord.getRemarks());
1317             }
1318             if(StringUtils.isEmpty(orderItemSourceRefundDto.getRefundReason())){
1319                 orderItemSourceRefundDto.setRemarks(refundRecord.getRefundReason());
1320             }
1321             refundRecordItemSource.setRemarks(orderItemSourceRefundDto.getRemarks());
1322             refundRecordItemSource.setRefundReason(orderItemSourceRefundDto.getRefundReason());
da4ad2 1323
4df03d 1324             //计算退款金额
C 1325             if(i == orderItemSourceRefundDtos.size()-1){
1326                 refundRecordItemSource.setRefundMoney(refundTotal);
1327             }else{
1328                 refundRecordItemSource.setRefundMoney(orderItemSourceRefundDto.getApproveRefundTotal().multiply(percentage).setScale(2,RoundingMode.UP));
1329             }
1330             if(refundRecordItemSource.getRefundMoney().compareTo(orderItemSourceRefundDto.getApproveRefundTotal()) > 0){
1331                 refundRecordItemSource.setRefundMoney(orderItemSourceRefundDto.getApproveRefundTotal());
1332             }
1333             if(refundRecordItemSource.getRefundMoney().compareTo(refundTotal) > 0){
1334                 refundRecordItemSource.setRefundMoney(refundTotal);
1335             }
1336             refundRecordItemSourceMapper.insert(refundRecordItemSource);
ae6ff7 1337             //减去已经分配退款金额
C 1338             refundTotal = refundTotal.subtract(refundRecordItemSource.getRefundMoney()).setScale(2,RoundingMode.HALF_UP);
da4ad2 1339
1869f3 1340         }
ae6ff7 1341
1869f3 1342         if(refundTotal.compareTo(BigDecimal.ZERO) > 0){
C 1343             throw new TipsException("退款金额分配错误[02]!");
431d07 1344         }
da4ad2 1345
431d07 1346     }
e3fa0c 1347
da4ad2 1348     /**
Z 1349      * 记录退款记录优惠卷
1350      */
e3fa0c 1351     public void handleOrderCouponRefunDto(List<OrderCouponRefunDto> couponList,StringBuilder orderNodeBuilder,OrdersTotal ordersTotal,RefundRecord refundRecord){
Z 1352         CouponOrderDiscountLog couponOrderDiscountLog=null;
1353         RefundRecordCoupon refundRecordCoupon=null;
1354         orderNodeBuilder.append("-处理退款优惠卷");
1355         for (OrderCouponRefunDto orderCouponRefunDto : couponList) {
1356             couponOrderDiscountLog=couponOrderDiscountLogMapper.selectOneByKey(orderCouponRefunDto.getOrderCouponId());
1357             if(couponOrderDiscountLog==null){
4df03d 1358                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单优惠卷标识不正确");
e3fa0c 1359             }
Z 1360             refundRecordCoupon=new  RefundRecordCoupon(ordersTotal.getId(),refundRecord.getId(),ordersTotal.getUserId(),1,1,couponOrderDiscountLog.getId(),
1361                     couponOrderDiscountLog.getCouponId(),couponOrderDiscountLog.getTitle(),couponOrderDiscountLog.getCouponNumberId());
1362             refundRecordCouponMapper.insert(refundRecordCoupon);
1363         }
1364     }
1365
1366
1367
4df03d 1368     /**真正退款,是对钱和状态的回退到账开始操作
da4ad2 1369      * 进行退款操作,退款用户项目,商品,促销,卡项,卡包
Z 1370      */
277835 1371     public Map<String,Object> handleRefundOrder(Map<String, String> operator,RefundRecord refundRecord,OrdersTotal ordersTotal,OrdersNodeLog ordersNodeLog,StringBuilder orderNodeBuilder,CancelOrder cancelOrder ){
c04e8a 1372
4dc6e5 1373         String operationId=operator.get("operatorId");
Z 1374         String operatorName=operator.get("operatorName");
c04e8a 1375
46bedb 1376         orderNodeBuilder.append("-处理退款支付方式,用户待执行项目");
ae6ff7 1377         //处理主业务
4df03d 1378         ordersTotal=  PartialRefundUtil.refundProcess(commonService, operationId, operatorName, refundRecord.getId(), customParameter);
c04e8a 1379
4dc6e5 1380         //返回数据
Z 1381         Map<String,Object> data=new HashMap<>();
1382         data.put("refundRecordId",refundRecord.getId());
1383         data.put("refundRecordCode",refundRecord.getCode());
16790d 1384
909b33 1385
da4ad2 1386         //处理次业务,报错不影响主业务
ae6ff7 1387         refundRecord = refundRecordService.selectOneByKey(refundRecord.getId());
C 1388
f13adb 1389         /**
Z 1390          * 用户升降级(调用航爷) 金额=用户支付的实付现金金额(不包含储值金)
1391          */
1392         SqlSentence sqlSentence = new SqlSentence();
1393         Map<String,Object> map=new HashMap<>();
1394         sqlSentence.setM(map);
1395         //退款成功
1396         map.put("refundRecordId", refundRecord.getId());
4df03d 1397         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 1398                 "WHERE rrm.refundRecordId=#{m.refundRecordId} and pm.isMoneyPay=1",map);
f13adb 1399         Map<String,Object> totalMap =commonService.selectOneMap(RefundRecordMethodMapper.class,sqlSentence);
Z 1400         BigDecimal total=new BigDecimal(String.valueOf(totalMap.get("total"))) ;
1401         if(BigDecimal.ZERO.compareTo(total) < 0){
1402             try {
c9e2be 1403                 orderNodeBuilder.append("-开始处理用户升降级,金额:"+total.negate());
f13adb 1404                 UserLevelUtil.refund(ordersTotal.getUserId(),ordersTotal.getId(),total.negate(),ordersTotal.getAppIdCode());
16790d 1405                 orderNodeBuilder.append("-处理用户升降级成功");
f13adb 1406             }catch (Exception e){
Z 1407                 String snapshot="处理用户升降级失败";
1408                 orderNodeBuilder.append("-处理用户升降级失败,异常原因:"+e.getMessage());
1409                 logger.error("处理用户升降级失败:" + e.getMessage());
1410                 //发送企业微信通知给工作人员
1411                 SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),snapshot,commonService,customParameter);
1412             }
1413         }
16790d 1414         //判断本次是否需要退回储值金,有的话需要开单同步到领建
ad6cc3 1415        /* map.put("refundNumberNo", PayMethodTypeConstants.PAY_STORED);
16790d 1416         sqlSentence.setSqlSentence(" SELECT CAST(COALESCE(sum(realRefundTotal),0) as  DECIMAL(11,2)) as total FROM refund_record_method   " +
Z 1417                 "WHERE refundRecordId=#{m.refundRecordId} and refundNumberNo=#{m.refundNumberNo}");
1418         Map<String,Object> moneyMap =commonService.selectOneMap(RefundRecordMethodMapper.class,sqlSentence);
1419         BigDecimal money=new BigDecimal(String.valueOf(moneyMap.get("total"))) ;
254bde 1420         if(BigDecimal.ZERO.compareTo(money) < 0  && !StringUtils.isEmpty(ordersTotal.getHisOrderId())){
16790d 1421             try {
c9e2be 1422                 orderNodeBuilder.append("-开始处理增加储值金开充值单到领建,金额:"+money);
16790d 1423                 orderRefundNewService.handStroedValue(ordersTotal,operationId,money);
c9e2be 1424                 orderNodeBuilder.append("-处理增加储值金成功");
16790d 1425             }catch (Exception e){
c9e2be 1426                 orderNodeBuilder.append("-处理增加储值金失败:"+e.getMessage());
Z 1427             }
ad6cc3 1428         }*/
c9e2be 1429         //判断订单是否是充值订单,如果是的话,需要同步储值金到领建去
ad6cc3 1430        /* if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())  && !StringUtils.isEmpty(ordersTotal.getHisOrderId())){
c9e2be 1431             try {
Z 1432                 orderNodeBuilder.append("-开始处理扣减储值金开充值单到领建,金额:"+ordersTotal.getTotal());
1433                 orderRefundNewService.deductionsStroedValue(ordersTotal,operationId,ordersTotal.getTotal());
1434                 orderNodeBuilder.append("-处理扣减储值金成功");
1435             }catch (Exception e){
1436                 orderNodeBuilder.append("-处理扣减储值金失败:"+e.getMessage());
16790d 1437             }
ad6cc3 1438         }*/
16790d 1439
da4ad2 1440         //同步领建,处理订单状态,未执行项目,卡包
ad6cc3 1441        /* if(!StringUtils.isEmpty(ordersTotal.getHisOrderId())){
da4ad2 1442             try {
Z 1443                 orderNodeBuilder.append("-开始处理his数据同步");
bb28ef 1444                 OrderCancelUtil.hisPartOrder(commonService,syncOrderService,syncExecutionRecordService,ordersTotal,syncUserCardService,customParameter,orderNodeBuilder, refundRecord);
da4ad2 1445                 orderNodeBuilder.append("-结束处理his数据同步");
Z 1446             }catch (Exception e){
1447                 orderNodeBuilder.append("-处理his数据同步失败,异常原因:"+e.getMessage());
79f8fb 1448                 logger.error("处理his数据同步失败:" + e.getMessage());
4dc6e5 1449
da4ad2 1450             }
ad6cc3 1451         }*/
575cd4 1452         try{
Z 1453             orderNodeBuilder.append("-开始记录收入确认表");
de3024 1454             PerformanceInfoTool.handRefundPerformanceInfo(commonService,refundRecord);
575cd4 1455             orderNodeBuilder.append("-记录收入确认表成功");
Z 1456         }catch (Exception e){
1457             orderNodeBuilder.append("-记录收入确认表失败");
1458             logger.info("记录收入确认表,异常:{}",e.getMessage(),e);
071df8 1459             // 添加错误日志
A 1460             PerformanceInfoTool.addErrorLog(commonService, refundRecord.getId(), PerformanceInfo.ASSOCIATION_TYPE_GOODS_REFUND, e.getMessage());
575cd4 1461         }
edf5ea 1462
4df03d 1463         if(CancelOrderDto.HIS_ASSISTANT.equals(cancelOrder.getPlatformSource())){
edf5ea 1464             //如果是his自动处理退款单原路退回
Z 1465             hisAssistantNoteList(ordersTotal,refundRecord.getId(),operationId,orderNodeBuilder);
1466         }
1467
46bedb 1468         //记录操作日志
Z 1469         orderNodeBuilder.append("-记录操作日志");
25d452 1470         StringBuffer stringBuffer=new StringBuffer("操作人:"+operator.get("operatorName")+",进行退款");
46bedb 1471         OrderLog orderLog=new OrderLog(ordersTotal.getId(), OrderLogConstants.LOG_TYPE_REFUND,stringBuffer.toString()
Z 1472                 ,operator.get("operatorName"),operator.get("operatorId"),OrderTotalConstants.STATUS_CANCEL);
1473         commonService.insert(OrderLogMapper.class,orderLog);
1474
1475         orderNodeBuilder.append("-结束处理退款");
1476         ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_REFUND);
1477         ordersNodeLog.setContent(orderNodeBuilder.toString());
1478         ordersNodeLog.setOrderId(ordersTotal.getId());
1479         commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
1480
4dc6e5 1481         return data;
c38ec7 1482     }
277835 1483     /**
Z 1484      * his助手原路退回退款单
1485      */
edf5ea 1486     public void hisAssistantNoteList(OrdersTotal ordersTotal,String refundRecordId,String operationId,StringBuilder orderNodeBuilder){
5c26f4 1487         OrderRefundNoteListDto orderRefundNoteListDto=new OrderRefundNoteListDto();
W 1488         orderRefundNoteListDto.setOperationId(operationId);
1489         orderRefundNoteListDto.setOrderId(ordersTotal.getId());
a0d15f 1490
W 1491         // 没有现金支付, 如果是crm的订单则调用crm取消订单的方法
1492         if("crm".equals(ordersTotal.getAppIdCode()) && OrderTotalConstants.STATUS_CANCEL == ordersTotal.getStatus()){
1493             //通知crm
1494             if(OrderTotalConstants.STATUS_REFUND_FINSH==ordersTotal.getRefundStatus()){
1495                 //全部退款完成
1496                 //通知crm订单取消成功了
1497                 Map<String, String> operator = ApiOrderUtil.getOperator(commonService, orderRefundNoteListDto.getOperationId());//获取操作人信息
1498                 String operatorId= operator.get("operatorId");
1499                 String operatorName=  operator.get("operatorName");
1500                 OrderStatusDto orderStatusDto=new OrderStatusDto();
1501                 orderStatusDto.setId(ordersTotal.getId());
1502                 orderStatusDto.setOpName(operatorName);
1503                 orderStatusDto.setOpId(operatorId);
1504                 orderStatusDto.setCancelInfo("phis取消退款");
1505                 orderStatusDto.setOpDetail("phis取消退款");
1506                 try {
1507                     logger.info("通知CRM订单号:{}退款成功请求参数:{}",ordersTotal.getOrderNo(),JSONObject.toJSONString(orderStatusDto));
1508                     Result result=  fOderService.cancelOrder(orderStatusDto);
1509                     logger.info("通知CRM订单号:{}退款成功返回参数:{}",ordersTotal.getOrderNo(),JSONObject.toJSONString(result));
1510                     orderNodeBuilder.append("通知crm退款状态返回成功");
1511                 }catch (Exception e){
1512                     logger.info("通知crm订单号:{}退款成功错误:{}",ordersTotal.getOrderNo(),e.getMessage());
1513                     orderNodeBuilder.append("通知crm退款状态返回失败");
1514                 }
1515
1516             }
1517         }
1518
277835 1519         SqlSentence sqlSentence = new SqlSentence();
Z 1520         Map<String,Object> map=new HashMap<>();
1521         sqlSentence.setM(map);
254bde 1522         map.put("orderId",ordersTotal.getId());
277835 1523         map.put("refundRecordId",refundRecordId);
4df03d 1524         sqlSentence.sqlSentence("SELECT * FROM refund_note WHERE orderId=#{m.orderId} and  refundRecordId=#{m.refundRecordId} and isDel=0 ",map);
277835 1525         List<RefundNote> refundNotes=refundNoteMapper.selectList(sqlSentence);
Z 1526         if(refundNotes==null || refundNotes.size()==0){
1527             return;
1528         }
1529
1530         List<OrderRefundNoteDto> orderRefundNoteDtos=new ArrayList<>();
1531         OrderRefundNoteDto orderRefundNoteDto;
1532         for (RefundNote refundNote : refundNotes) {
1533             orderRefundNoteDto=new OrderRefundNoteDto();
1534             BeanUtils.copyProperties(refundNote,orderRefundNoteDto);
1535             orderRefundNoteDto.setRefundroute(1);
1536             orderRefundNoteDto.setRefundNumberNo(refundNote.getPaymentNumberNo());
1537             orderRefundNoteDto.setRefundName(refundNote.getPaymentName());
1538             orderRefundNoteDtos.add(orderRefundNoteDto);
1539         }
1540         orderRefundNoteListDto.setOrderRefundNoteDtos(orderRefundNoteDtos);
1541
edf5ea 1542         noteConfirm(orderRefundNoteListDto, ordersTotal,orderNodeBuilder);
254bde 1543     }
4df03d 1544
edf5ea 1545     public PlatformResult noteConfirm(OrderRefundNoteListDto orderRefundNoteListDto,OrdersTotal ordersTotal,StringBuilder orderNodeBuilder) {
254bde 1546         logger.info("退款单确认打印参数:{}",JSON.toJSONString(orderRefundNoteListDto));
Z 1547         Map<String, String> operator = ApiOrderUtil.getOperator(commonService, orderRefundNoteListDto.getOperationId());//获取操作人信息
1548         String operatorId= operator.get("operatorId");
1549         String operatorName=  operator.get("operatorName");
1550
1551
1552         SqlSentence sqlSentence = new SqlSentence();
1553         Map<String,Object> map=new HashMap<>();
1554         sqlSentence.setM(map);
1555
1556
1557         List<OrderRefundNoteDto> orderRefundNoteDtos=orderRefundNoteListDto.getOrderRefundNoteDtos();
1558         if("crm".equals(ordersTotal.getAppIdCode())){
4df03d 1559             //CRM退款
edf5ea 1560             handleCrmRefundOrder(orderRefundNoteDtos,ordersTotal,operatorId,operatorName,orderNodeBuilder);
254bde 1561         }else {
4df03d 1562             sqlSentence.sqlSentence(" refundroute=#{m.refundroute},refundNumberNo=#{m.refundNumberNo},refundName=#{m.refundName}, " +
254bde 1563                     " refundStoredTotal=#{m.refundStoredTotal},refundStatus=#{m.refundStatus},remarks=#{m.remarks},shopId=#{m.shopId}, " +
4df03d 1564                     " shopName=#{m.shopName},operationName=#{m.operationName},operationId=#{m.operationId} where id=#{m.id} ",map);
254bde 1565
Z 1566             map.put("shopId",ordersTotal.getShopId());
1567             map.put("shopName",ordersTotal.getShopName());
1568             map.put("operationName",operatorName);
1569             map.put("operationId",operatorId);
1570             map.put("refundStatus",RefundNote.STATUS_SUCCESS);
1571             for (OrderRefundNoteDto orderRefundNoteDto : orderRefundNoteDtos) {
1572                 map.put("refundroute",orderRefundNoteDto.getRefundroute());
1573                 map.put("refundNumberNo",orderRefundNoteDto.getRefundNumberNo());
1574                 map.put("refundName",orderRefundNoteDto.getRefundName());
1575                 map.put("refundStoredTotal",orderRefundNoteDto.getRefundStoredTotal());
1576                 map.put("remarks",orderRefundNoteDto.getRemarks());
1577                 map.put("id",orderRefundNoteDto.getId());
1578                 refundNoteMapper.updateWhere(sqlSentence);
1579
1580                 if (!StringUtils.isEmpty(orderRefundNoteDto.getImageList())){
1581                     String [] imageList= orderRefundNoteDto.getImageList().split(",");
1582                     for (String s : imageList) {
1583                         RefundNoteItems refundNoteItems=new RefundNoteItems();
1584                         refundNoteItems.setRefundNoteId(orderRefundNoteDto.getId());
1585                         refundNoteItems.setImgUrl(s);
1586                         refundNoteItemsMapper.insert(refundNoteItems);
1587                     }
1588                 }
1589             }
1590         }
1591
1592
1593         //记录操作日志
1594         StringBuffer stringBuffer=new StringBuffer("操作人:"+operator.get("operatorName")+",已支付订单现金支付退款:");
1595         OrderLog orderLog=new OrderLog(ordersTotal.getId(),OrderLogConstants.LOG_TYPE_CANCEL_ORDER,stringBuffer.toString()
1596                 ,operator.get("operatorName"),operator.get("operatorId"),OrderTotalConstants.STATUS_CANCEL);
1597         commonService.insert(OrderLogMapper.class,orderLog);
1598
1599         return PlatformResult.success();
1600     }
4df03d 1601     /**处理crm退款*/
edf5ea 1602     public void handleCrmRefundOrder(List<OrderRefundNoteDto> orderRefundNoteDtos,OrdersTotal ordersTotal,String operatorId, String operatorName,StringBuilder orderNodeBuilder){
254bde 1603         SqlSentence sqlSentence = new SqlSentence();
Z 1604         Map<String,Object> map=new HashMap<>();
1605         sqlSentence.setM(map);
1606
1607         //待确认
1608         BigDecimal crmAmount = orderRefundNoteDtos.stream().filter(item->RefundNote.ORIGINAL_ROAD.equals(item.getRefundroute())).map(o->o.getPaymentTotal())
1609                 .reduce(BigDecimal.ZERO,BigDecimal::add);
1610         List<RefundAmountModelDto> amountModelList=new ArrayList<>();
1611         RefundAmountModelDto refundAmountModelDto;
1612         for (OrderRefundNoteDto orderRefundNoteDto : orderRefundNoteDtos) {
1613             if(RefundNote.ORIGINAL_ROAD.equals(orderRefundNoteDto.getRefundroute())){
1614                 refundAmountModelDto=new RefundAmountModelDto();
1615                 refundAmountModelDto.setRefundType(PayMethodTypeConstants.PAY_CRM_WX.equals(orderRefundNoteDto.getPaymentNumberNo()) ?0:1);
1616                 refundAmountModelDto.setAmountTotal(orderRefundNoteDto.getPaymentTotal());
1617                 amountModelList.add(refundAmountModelDto);
1618             }
1619
1620         }
1621         logger.info("退款金额:{}",crmAmount);
1622         if(1==crmAmount.compareTo(BigDecimal.ZERO)){
1623             RefundDto refundDto=new RefundDto();
1624             refundDto.setRefundOrderType(0);
1625             refundDto.setOrderId(ordersTotal.getId());
1626             refundDto.setRefundType(0);
1627             refundDto.setRefundAmountTotal(crmAmount);
1628             refundDto.setRefundRecharge(new BigDecimal(0));
1629             refundDto.setRefundIncrement(new BigDecimal(0));
1630             refundDto.setRefundIntegral(new BigDecimal(0));
1631             refundDto.setIsWholeOrder(0);
1632             refundDto.setRemarks("phis退款单退款,订单号:"+ordersTotal.getOrderNo());
1633             refundDto.setAmountModelList(amountModelList);
1634             logger.info("调用crm退款入参:{}",JSONObject.toJSONString(refundDto));
1635             Result result= fOderService.refundOrder(refundDto);;
1636             logger.info("调用crm退款返回:{}",JSONObject.toJSONString(result));
1637             if (result != null) {
1638                 result.checkTips();
edf5ea 1639                 if("100".equals(result.getCode())){
254bde 1640                     RefundReturnDto refundReturnDto=JSON.parseObject(JSONObject.toJSONString(result.getData()),RefundReturnDto.class);
Z 1641                     if (RefundReturnDto.REFUND_STATUS_SUECCESS==refundReturnDto.getRefundStatus()){
edf5ea 1642                         orderNodeBuilder.append("-调用CRM退款金额:"+crmAmount+",返回成功返回流水号:"+refundReturnDto.getRefundNo()+",json:"+result);
254bde 1643                         logger.info("crm退款成功进行下面操作");
Z 1644                     }else {
55dbe8 1645                         throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求crm退款接口报错,退款失败!退款状态不是成功状态");
254bde 1646                     }
Z 1647
1648                 }else{
55dbe8 1649                     throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求crm退款接口报错,接口返回错误!:code不是100");
254bde 1650                 }
Z 1651             } else {
1652                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"请求crm退款接口报错,返回为空!");
1653             }
1654
1655         }
1656         logger.info("订单状态为:{}",ordersTotal.getRefundStatus());
edf5ea 1657         //通知crm
a0d15f 1658 /*        if(OrderTotalConstants.STATUS_REFUND_FINSH==ordersTotal.getRefundStatus()){
254bde 1659             //全部退款完成
Z 1660             //通知crm订单取消成功了
1661             OrderStatusDto orderStatusDto=new OrderStatusDto();
1662             orderStatusDto.setId(ordersTotal.getId());
1663             orderStatusDto.setOpName(operatorName);
1664             orderStatusDto.setOpId(operatorId);
1665             orderStatusDto.setCancelInfo("phis取消退款");
1666             orderStatusDto.setOpDetail("phis取消退款");
1667             try {
edf5ea 1668                 logger.info("通知CRM订单号:{}退款成功请求参数:{}",ordersTotal.getOrderNo(),JSONObject.toJSONString(orderStatusDto));
254bde 1669                 Result result=  fOderService.cancelOrder(orderStatusDto);
edf5ea 1670                 logger.info("通知CRM订单号:{}退款成功返回参数:{}",ordersTotal.getOrderNo(),JSONObject.toJSONString(result));
Z 1671                 orderNodeBuilder.append("通知crm退款状态返回成功");
254bde 1672             }catch (Exception e){
Z 1673                 logger.info("通知crm订单号:{}退款成功错误:{}",ordersTotal.getOrderNo(),e.getMessage());
edf5ea 1674                 orderNodeBuilder.append("通知crm退款状态返回失败");
254bde 1675             }
Z 1676
a0d15f 1677         }*/
254bde 1678
edf5ea 1679
4df03d 1680         sqlSentence.sqlSentence(" refundroute=#{m.refundroute},refundNumberNo=#{m.refundNumberNo},refundName=#{m.refundName}, " +
254bde 1681                 " refundStoredTotal=#{m.refundStoredTotal},refundStatus=#{m.refundStatus},remarks=#{m.remarks},shopId=#{m.shopId}, " +
4df03d 1682                 " shopName=#{m.shopName},operationName=#{m.operationName},operationId=#{m.operationId} where id=#{m.id} ",map);
254bde 1683
Z 1684         map.put("shopId",ordersTotal.getShopId());
1685         map.put("shopName",ordersTotal.getShopName());
1686         map.put("operationName",operatorName);
1687         map.put("operationId",operatorId);
1688         map.put("refundStatus",RefundNote.STATUS_SUCCESS);
1689         for (OrderRefundNoteDto orderRefundNoteDto : orderRefundNoteDtos) {
1690             map.put("refundroute",orderRefundNoteDto.getRefundroute());
1691             map.put("refundNumberNo",orderRefundNoteDto.getRefundNumberNo());
1692             map.put("refundName",orderRefundNoteDto.getRefundName());
1693             map.put("refundStoredTotal",orderRefundNoteDto.getRefundStoredTotal());
1694             map.put("remarks",orderRefundNoteDto.getRemarks());
1695             map.put("id",orderRefundNoteDto.getId());
1696             refundNoteMapper.updateWhere(sqlSentence);
1697
1698             if (!StringUtils.isEmpty(orderRefundNoteDto.getImageList())){
1699                 String [] imageList= orderRefundNoteDto.getImageList().split(",");
1700                 for (String s : imageList) {
1701                     RefundNoteItems refundNoteItems=new RefundNoteItems();
1702                     refundNoteItems.setRefundNoteId(orderRefundNoteDto.getId());
1703                     refundNoteItems.setImgUrl(s);
1704                     refundNoteItemsMapper.insert(refundNoteItems);
1705                 }
1706             }
1707         }
1708
1709         //退款成功发送企业微信给订单开单人
1710         JSONObject object = new JSONObject();
1711         object.put("abnormal","订单退款成功,现金支付资产已退回!");
1712         object.put("orderNo",ordersTotal.getOrderNo());
1713         User user=commonService.selectOneByKeyBlob(UserMapper.class,ordersTotal.getUserId());
1714         object.put("userName",user==null?"":user.getName());
1715         object.put("notificationSubject", NotificationLog.NOTIFICATION_SUBJECT_REFUND_NOTE_PHISKIN_SUC_NOTICE);
1716         SendNoticeUtil.successOrderSendNotice(commonService, customParameter, ordersTotal,object);
1717
277835 1718     }
9d4e6f 1719
e3fa0c 1720     /**
Z 1721      * 营销中心回调审批处理接口
1722      * @param aduitDto
1723      * @return
1724      */
b9b969 1725     @Override
Z 1726     public PlatformResult partRefundApproval(AduitDto aduitDto) {
25d452 1727         logger.info("营销中心审批退款入参:{}",JSON.toJSONString(aduitDto));
b9b969 1728         SqlSentence sqlSentence = new SqlSentence();
Z 1729         Map<String,Object> map=new HashMap<>();
1730         sqlSentence.setM(map);
1731         map.put("applyId",aduitDto.getApplyId());
4df03d 1732         sqlSentence.sqlSentence("SELECT * FROM cancel_order WHERE applyId=#{m.applyId} and isDel=0 ",map);
b9b969 1733         CancelOrder cancelOrder=commonService.selectOne(CancelOrderMapper.class,sqlSentence);
Z 1734         if(cancelOrder==null){
1735             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该审核标识");
1736         }
c04e8a 1737         if(!CancelOrder.PENDING.equals(cancelOrder.getApprovalstatus())){
79f8fb 1738             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"该条审核标识已经处理过了,不要重复提交");
Z 1739         }
1740
edf5ea 1741         Map<String, String> operator=new HashMap<>();
Z 1742         operator.put("operatorId",cancelOrder.getOperatorId());
1743         operator.put("operatorName",cancelOrder.getOperatorName());
1744
b9b969 1745         //先判断项目的状态是否存在
c04e8a 1746         OrdersTotal ordersTotal= ordersTotalMapper.selectOneByKey(cancelOrder.getOrderId());
C 1747         if(ordersTotal==null){
1748             logger.info("取消订单流程:未找到总订单信息!订单id:{}",cancelOrder.getOrderId());
1749             return PlatformResult.failure(PlatformCode.ERROR_TIPS,"取消订单流程:未找到总订单信息!");
b9b969 1750         }
c04e8a 1751         
b9b969 1752         cancelOrder.setExamEmplId(aduitDto.getExamEmplId());
Z 1753         cancelOrder.setExamEmplName(aduitDto.getExamEmplName());
1754
c04e8a 1755         //获取退款记录
C 1756         RefundRecord refundRecord = commonService.selectOneByKey(RefundRecordMapper.class,cancelOrder.getRefundRecordId());
97a5fc 1757         if(refundRecord==null){
25d452 1758             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到该审核的退款记录");
97a5fc 1759         }
Z 1760
c04e8a 1761         if(BaseEntity.NO.equals(aduitDto.getType())){
C 1762             //审核不通过
b9b969 1763             cancelOrder.setApprovalstatus(CancelOrder.FAIL);
25d452 1764             cancelOrder.setEditTime(new Date());
b9b969 1765             commonService.updateAll(CancelOrderMapper.class,cancelOrder);
909b33 1766
df3f90 1767             //更改总订单退款状态
Z 1768             map.put("orderId",ordersTotal.getId());
4df03d 1769             sqlSentence.sqlSentence("select * from order_item WHERE  orderId=#{m.orderId} and isDel=0",map);
df3f90 1770             List<OrderItem> orderItemList=commonService.selectList(OrderItemMapper.class,sqlSentence);
Z 1771
1772             List<Integer> collect = orderItemList.stream().map(o -> o.getRefundStatus()).collect(Collectors.toList());
1773             if(collect.contains(OrderTotalConstants.STATUS_REFUND_PART)){
1774                 ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
c04e8a 1775             }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE)
C 1776                     && collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
df3f90 1777                 ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
Z 1778             }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE)){
1779                 ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
c9f92c 1780             }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
df3f90 1781                 ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_FINSH);
c9f92c 1782             }else {
Z 1783                 ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
df3f90 1784             }
Z 1785
1786             map.put("refundStatus",ordersTotal.getRefundStatus());
909b33 1787             map.put("id",ordersTotal.getId());
4df03d 1788             sqlSentence.sqlSentence(" refundStatus=#{m.refundStatus}  WHERE id=#{m.id}  ",map);
909b33 1789             ordersTotalMapper.updateWhere(sqlSentence);
Z 1790
97a5fc 1791             refundRecord.setRefundStatus(RefundStatus.STATUS_INVALID_REFUND);
25d452 1792             refundRecord.setEditTime(new Date());
97a5fc 1793             commonService.updateAll(RefundRecordMapper.class,refundRecord);
Z 1794
edf5ea 1795             //拒绝审批需要还原回去储值金
Z 1796             //判断是否是充值订单,是的话需要把前面预扣的还原
bf63c3 1797             if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
edf5ea 1798                 //判断金额不等于0,才执行操作,不然操作余额的时候会爆操作数量或金额不能为0
c04e8a 1799                 if(ordersTotal.getActualTotal().compareTo(BigDecimal.ZERO)!=0){
edf5ea 1800
363fc8 1801                     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 1802                     OrderLog orderLog = RefundToolUtil.setOrderLog(refundRecord, operator.get("operatorId"), operator.get("operatorName"), "充值单:"+ordersTotal.getOrderNo()+"申请退款,预扣除金额:"+ordersTotal.getTotal(), 0, OrderLogConstants.LOG_TYPE_REFUND);
Z 1803                     commonService.insert(OrderLogMapper.class,orderLog);
1804                     //活动规则退款处理
1805                     map.put("orderId", ordersTotal.getId());
4df03d 1806                     sqlSentence.sqlSentence("select * from orders_info where isDel=0 and orderId=#{m.orderId}",map);
edf5ea 1807                     OrderInfo orderInfo=commonService.selectOne(OrderInfoMapper.class,sqlSentence);
Z 1808                     handActivityRule(commonService, operator.get("operatorId"), operator.get("operatorName"), sqlSentence, map, refundRecord,ordersTotal,orderInfo,1);
1809                 }
1810             }
1811
b9b969 1812             return PlatformResult.success("拒绝取消审核通过");
Z 1813         }
c04e8a 1814
C 1815         cancelOrder.setEditTime(new Date());
1816         cancelOrder.setApprovalstatus(CancelOrder.SUCCESS);
1817         commonService.updateAll(CancelOrderMapper.class,cancelOrder);
97a5fc 1818
b9b969 1819         //订单节点日志
Z 1820         OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
1821         StringBuilder orderNodeBuilder = new StringBuilder();
1822         orderNodeBuilder.append("审核通过,开始处理退款");
1823
edf5ea 1824
277835 1825         Map<String, Object>refund =handleRefundOrder(operator,refundRecord,ordersTotal,ordersNodeLog,orderNodeBuilder,cancelOrder);
b9b969 1826         return PlatformResult.success(refund);
Z 1827     }
df3f90 1828
Z 1829
97a5fc 1830     /**
Z 1831      * 全部退款处理退款逻辑
1832      * @param orderRefundDto
1833      * @return
1834      */
1835     @Override
4df03d 1836     public PlatformResult wholeRefund(OrderRefundDto orderRefundDto,ThirtApplication thirtApplication) {
97a5fc 1837
118d96 1838         OrdersTotal ordersTotal = ordersTotalMapper.selectOneByKey(orderRefundDto.getOrderId());
C 1839
97a5fc 1840         //获取该笔订单的项目详情
118d96 1841         List<Map<String, Object>> refundDetails=refundDetails(ordersTotal);
97a5fc 1842         // 退款信息集合
Z 1843         List<OrderItemRefundDto> refundList=new ArrayList<>();
1844         //退款二级子订单信息集合
1845         List<OrderItemSourceRefundDto> orderItemSourceRefundDtos;
1846         List<Map<String, Object>> refundSonDetails;
1847
1848         OrderItemRefundDto orderItemRefundDto;
1849         OrderItemSourceRefundDto orderItemSourceRefundDto;
1850         for (Map<String, Object> refundDetail : refundDetails) {
1851             orderItemRefundDto=new OrderItemRefundDto();
1852             orderItemRefundDto.setOrderItemId(String.valueOf(refundDetail.get("id")));
1853             orderItemRefundDto.setType(String.valueOf(refundDetail.get("type")));
1854
8eb9e6 1855             ////退款备注
C 1856             orderItemRefundDto.setRemarks(orderRefundDto.getRemarks());
1857             orderItemRefundDto.setRefundReason(orderRefundDto.getRefundReason());
1858
98b886 1859             if(OrderItemConstants.TYPE_PROMOTION.equals(orderItemRefundDto.getType()) || OrderItemConstants.CARD_BAG.equals(orderItemRefundDto.getType())){
97a5fc 1860                 orderItemRefundDto.setRefundNum(0);
Z 1861                 refundSonDetails= (List<Map<String, Object>>) refundDetail.get("list");
1862                 orderItemSourceRefundDtos=new ArrayList<>();
1863                 for (Map<String, Object> refundSonDetail : refundSonDetails) {
1864                     orderItemSourceRefundDto=new OrderItemSourceRefundDto();
1865                     orderItemSourceRefundDto.setOrderItemSonId(String.valueOf(refundSonDetail.get("id")));
1866                     orderItemSourceRefundDto.setType(String.valueOf(refundSonDetail.get("type")));
1867                     orderItemSourceRefundDto.setRefundNum(Integer.parseInt(String.valueOf(refundSonDetail.get("notUsedNum"))));
8eb9e6 1868
C 1869                     //退款备注
1870                     orderItemSourceRefundDto.setRemarks(orderRefundDto.getRemarks());
1871                     orderItemSourceRefundDto.setRefundReason(orderRefundDto.getRefundReason());
1872
97a5fc 1873                     orderItemSourceRefundDtos.add(orderItemSourceRefundDto);
Z 1874                 }
1875                 orderItemRefundDto.setOrderItemSourceRefundDtos(orderItemSourceRefundDtos);
1876             }else {
1877                 orderItemRefundDto.setRefundNum(Integer.parseInt(refundDetail.get("notUsedNum").toString()) );
1878             }
1879             refundList.add(orderItemRefundDto);
1880         }
1881         orderRefundDto.setRefundList(refundList);
1882
1883         //获取退款资金信息
118d96 1884         OrderRefundDto  parameter= nextStep(ordersTotal,orderRefundDto);
97a5fc 1885
Z 1886         parameter.setOperatorId(orderRefundDto.getOperatorId());
1887         parameter.setIsRefund(orderRefundDto.getIsRefund());
1888         parameter.setIsApproval(orderRefundDto.getIsApproval());
1889         parameter.setRoleId(orderRefundDto.getRoleId());
1890         parameter.setPlatformSource(orderRefundDto.getPlatformSource());
04ce22 1891         parameter.setRefundOperationType(BaseEntity.NO);
97a5fc 1892         //调用退款处理退款逻辑
4df03d 1893         return partRefund(ordersTotal,parameter,thirtApplication);
97a5fc 1894     }
b9b969 1895
250fca 1896     /**
25d452 1897      * 伪造退款处理退款逻辑
250fca 1898      * @param orderRefundDto
Z 1899      * @return
1900      */
1901     @Override
1902     public PlatformResult forgePartRefund(OrderRefundDto orderRefundDto) {
25d452 1903         logger.info("退款打印参数:{}", JSON.toJSONString(orderRefundDto));
250fca 1904         //先判断项目的状态是否存在
Z 1905         OrdersTotal ordersTotal=null;
1906         try {
1907             ordersTotal=ordersTotalMapper.selectOneByKey(orderRefundDto.getOrderId());
1908             if(ordersTotal==null){
1909                 logger.info("取消订单流程:未找到总订单信息!订单id:{}",orderRefundDto.getOrderId());
1910                 return PlatformResult.failure(PlatformCode.ERROR_TIPS,"取消订单流程:未找到总订单信息!");
1911             }
1912         }catch (Exception e){
1913             logger.info("取消订单流程:根据订单id查询多条总订单信息!订单id:{}",orderRefundDto.getOrderId());
1914             return PlatformResult.failure(PlatformCode.ERROR_TIPS,"取消订单流程:根据订单id查询多条总订单信息!");
1915         }
1916
1917         if(!(OrderTotalConstants.STATUS_REFUND_NONE==ordersTotal.getRefundStatus()) &&
1918                 !(OrderTotalConstants.STATUS_REFUND_PART==ordersTotal.getRefundStatus())){
1919             throw new TipsException("订单标识错误,订单退款状态不正确!");
1920         }
1921
1922 //        orderRefundDto=parameterVerification(orderRefundDto);
1923
1924         return handleforgePartRefund(ordersTotal,orderRefundDto);
1925
1926     }
1927
892b96 1928
Z 1929
250fca 1930     /**
Z 1931      * 伪造处理退款详情
1932      */
1933     public PlatformResult  handleforgePartRefund(OrdersTotal ordersTotal,OrderRefundDto orderRefundDto){
1934
1935         //订单节点日志
1936         OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
1937         StringBuilder orderNodeBuilder = new StringBuilder();
1938
86bf93 1939         orderNodeBuilder.append("开始退款(WZ)");
250fca 1940
Z 1941         // 获取退款方式,退款项目,退款优惠卷
1942         List<OrderPayMethodDto> refundPayMethod=orderRefundDto.getRefundPayMethod();
1943         List<OrderItemRefundDto> refundList=orderRefundDto.getRefundList();
1944         List<OrderCouponRefunDto> couponList=orderRefundDto.getCouponList();
1945
1946         //客户选的退款方式总金额
1947         BigDecimal sumMoney=refundPayMethod.stream().map(OrderPayMethodDto::getMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
1948         //本次退款总金额
1949         BigDecimal refundSumMoney=refundList.stream().map(OrderItemRefundDto::getRefundMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
1950
1951         if(!OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType())){
1952             if(sumMoney.compareTo(refundSumMoney)==1){
1953                 throw new TipsException("退款金额不能大于可退金额!");
1954             }
1955             orderNodeBuilder.append("-本次退款项目总金额:"+refundSumMoney+",客户选的退款方式总金额:"+sumMoney);
1956         }else {
1957             orderNodeBuilder.append("-本次退款项目总金额:"+ordersTotal.getActualTotal()+",客户选的退款方式总金额:"+sumMoney);
1958         }
1959
1960         Map<String, String> operator = ApiOrderUtil.getOperator(commonService, orderRefundDto.getOperatorId());//获取操作人信息
1961         SqlSentence sqlSentence = new SqlSentence();
1962         Map<String,Object> map=new HashMap<>();
1963         sqlSentence.setM(map);
1964
1965         //退款总记录
1966         orderNodeBuilder.append("-处理退款总记录");
1967         String totalCode = CreateNo.createTimeNo(systemParameterMapper, "R", 8, "yyyyMMddHHmmss");//总订单编号
25d452 1968         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 1969         refundRecord.setOperatorType(RefundRecord.OPERATOR_TYPE_EMPLOYEE);
Z 1970         Employee employee = commonService.selectOneByKey(EmployeeMapper.class,orderRefundDto.getOperatorId());
1971         refundRecord.setOperatorId(employee.getId());
1972         refundRecord.setRefundOperationType(orderRefundDto.getRefundOperationType());
1973         refundRecord.setOperatorName(employee.getCnName());
1974         refundRecordService.insert(refundRecord);
1975
1976         if(refundPayMethod!=null && refundPayMethod.size()>0){
1977             //处理退款方式记录表
4df03d 1978             handleRefundPayMethod(orderRefundDto,orderNodeBuilder,ordersTotal,refundRecord);
250fca 1979         }
Z 1980         if(refundList!=null && refundList.size()>0){
1981             //记录本次退款的项目详情
1982             //分摊比例
1983             //因为优惠卷抵扣金额可能超过订单的金额,所以不会有支付记录
1984             BigDecimal percentage;
1985             if(sumMoney.compareTo(BigDecimal.ZERO)==0){
1986                 percentage=new BigDecimal(1);
1987             }else {
1988                 percentage=sumMoney.divide(refundSumMoney,10,BigDecimal.ROUND_HALF_UP);
1989             }
1990
4df03d 1991             //handleRefundRecordItem(orderRefundDto,orderNodeBuilder,ordersTotal,refundRecord,percentage);
250fca 1992         }
Z 1993         if(couponList!=null && couponList.size()>0){
1994             //处理优惠卷
1995             handleOrderCouponRefunDto(couponList,orderNodeBuilder,ordersTotal,refundRecord);
1996         }
1997         try{
1998             orderNodeBuilder.append("-开始记录收入确认表");
1999             PerformanceInfoTool.handRefundPerformanceInfo(commonService,refundRecord);
2000             orderNodeBuilder.append("-记录收入确认表成功");
2001         }catch (Exception e){
2002             orderNodeBuilder.append("-记录收入确认表失败");
2003             logger.info("记录收入确认表,异常:{}",e.getMessage(),e);
071df8 2004             // 添加错误日志
A 2005             PerformanceInfoTool.addErrorLog(commonService, refundRecord.getId(), PerformanceInfo.ASSOCIATION_TYPE_GOODS_REFUND, e.getMessage());
250fca 2006         }
Z 2007         //记录操作日志
2008         orderNodeBuilder.append("-记录操作日志");
86bf93 2009         StringBuffer stringBuffer=new StringBuffer("操作人:"+operator.get("operatorName")+",进行退款(WZ)");
250fca 2010         OrderLog orderLog=new OrderLog(ordersTotal.getId(), OrderLogConstants.LOG_TYPE_REFUND,stringBuffer.toString()
Z 2011                 ,operator.get("operatorName"),operator.get("operatorId"),OrderTotalConstants.STATUS_CANCEL);
2012         commonService.insert(OrderLogMapper.class,orderLog);
2013
2014         orderNodeBuilder.append("-结束处理退款");
2015         ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_REFUND);
2016         ordersNodeLog.setContent(orderNodeBuilder.toString());
2017         ordersNodeLog.setOrderId(ordersTotal.getId());
2018         commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
2019
2020         return PlatformResult.success("成功");
2021     }
2022
892b96 2023     /**
Z 2024      * 根据订单 重新绑定订单退款状态
2025      *
2026      */
2027     @Override
2028     public void verifyOrderRefundStatus(OrdersTotal ordersTotalDto) {
2029         SqlSentence sqlSentence = new SqlSentence();
2030         Map<String, Object> sqlMap = new HashMap<>();
2031         sqlSentence.setM(sqlMap);
2032         sqlMap.put("isDel", BaseEntity.NO);
2033         sqlMap.put("orderId", ordersTotalDto.getId());
2034         sqlMap.put("type", OrderItemConstants.TYPE_PROJECT);
2035
4df03d 2036         sqlSentence.sqlSentence("SELECT * FROM  orders_total   WHERE  id = #{m.orderId}  and  isDel = #{m.isDel} ",sqlMap);
892b96 2037         OrdersTotal ordersTotal = ordersTotalMapper.selectOne(sqlSentence);
Z 2038         if(ordersTotal==null){
2039             throw new TipsException("订单标识错误,找不到订单!");
2040         }
2041         //查询二级订单
4df03d 2042         sqlSentence.sqlSentence("SELECT * FROM  order_item_source   WHERE  orderId = #{m.orderId}  and  type = #{m.type}  and  isDel = #{m.isDel} ",sqlMap);
892b96 2043         List<OrderItemSon> orderItemSonList=orderItemSonMapper.selectList(sqlSentence);
Z 2044
2045
2046         if(orderItemSonList!=null && orderItemSonList.size()>0){
2047             int oldRefundStatus;
2048             int newRefundStatus;
2049             UserProjectItem userProjectItem;
2050             for (OrderItemSon orderItemSon : orderItemSonList) {
2051                 if(OrderTotalConstants.STATUS_REFUND_FINSH==orderItemSon.getRefundStatus()){
2052                     oldRefundStatus=OrderTotalConstants.STATUS_REFUND_FINSH;
2053
ae6ff7 2054                     userProjectItem = PartialRefundUtil.getUserProject(orderItemSon.getId(),commonService);
892b96 2055
Z 2056                     if(userProjectItem.getNotUsedNum()>0){
2057                         newRefundStatus=OrderTotalConstants.STATUS_REFUND_PART;
2058                     }else {
2059                         newRefundStatus=oldRefundStatus;
2060                     }
2061
2062                     if(newRefundStatus!=oldRefundStatus){
2063                         sqlMap.put("refundStatus", newRefundStatus);
2064                         sqlMap.put("id", orderItemSon.getId());
4df03d 2065                         sqlSentence.sqlSentence(" refundStatus = #{m.refundStatus} WHERE id = #{m.id}  ",sqlMap);
892b96 2066                         orderItemSonMapper.updateWhere(sqlSentence);
Z 2067
2068                         sqlMap.put("refundStatus", newRefundStatus);
2069                         sqlMap.put("id", orderItemSon.getOrderItemId());
4df03d 2070                         sqlSentence.sqlSentence(" refundStatus = #{m.refundStatus} WHERE id = #{m.id}  ",sqlMap);
892b96 2071                         orderItemMapper.updateWhere(sqlSentence);
Z 2072                     }
2073
2074                 }
2075             }
2076             
2077         }
2078
2079         //查询二级订单
4df03d 2080         sqlSentence.sqlSentence("SELECT * FROM  order_item   WHERE  orderId = #{m.orderId}  and  type = #{m.type}  and  isDel = #{m.isDel} ",sqlMap);
892b96 2081         List<OrderItem> orderItemList=orderItemMapper.selectList(sqlSentence);
Z 2082         if(orderItemList!=null && orderItemList.size()>0){
2083             int oldRefundStatus;
2084             int newRefundStatus;
2085             UserProjectItem userProjectItem;
2086             for (OrderItem orderItem : orderItemList) {
2087                 oldRefundStatus=OrderTotalConstants.STATUS_REFUND_FINSH;
2088
ae6ff7 2089                 userProjectItem = PartialRefundUtil.getUserProject(orderItem.getId(),commonService);
892b96 2090
Z 2091                 if(userProjectItem.getNotUsedNum()>0){
2092                     newRefundStatus=OrderTotalConstants.STATUS_REFUND_PART;
2093                 }else {
2094                     newRefundStatus=oldRefundStatus;
2095                 }
2096
2097                 if(newRefundStatus!=oldRefundStatus){
2098                     sqlMap.put("refundStatus", newRefundStatus);
2099                     sqlMap.put("id", orderItem.getId());
4df03d 2100                     sqlSentence.sqlSentence(" refundStatus = #{m.refundStatus} WHERE id = #{m.id}  ",sqlMap);
892b96 2101                     orderItemMapper.updateWhere(sqlSentence);
Z 2102                 }
2103
2104             }
2105         }
2106
2107
2108         sqlMap.put("orderId",ordersTotal.getId());
4df03d 2109         sqlSentence.sqlSentence("select * from order_item WHERE  orderId=#{m.orderId} and isDel=0",sqlMap);
892b96 2110         List<OrderItem> orderItems=commonService.selectList(OrderItemMapper.class,sqlSentence);
Z 2111
2112         List<Integer> collect = orderItems.stream().map(o -> o.getRefundStatus()).collect(Collectors.toList());
2113         if(collect.contains(OrderTotalConstants.STATUS_REFUND_PART)){
2114             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
215be3 2115             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
892b96 2116         }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE) && collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
Z 2117             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_PART);
215be3 2118             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
892b96 2119         }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_NONE)){
Z 2120             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
215be3 2121             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
892b96 2122         }else if (collect.contains(OrderTotalConstants.STATUS_REFUND_FINSH)){
Z 2123             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_FINSH);
2124             ordersTotal.setStatus(OrderTotalConstants.STATUS_CANCEL);
2125         }else {
2126             ordersTotal.setRefundStatus(OrderTotalConstants.STATUS_REFUND_NONE);
215be3 2127             ordersTotal.setStatus(OrderTotalConstants.STATUS_PAY);
892b96 2128         }
Z 2129         ordersTotal.setEditTime(new Date());
2130         commonService.updateAll(OrdersTotalMapper.class,ordersTotal);
2131     }
2132
4dc6e5 2133 }