ANDRU-PC\Andru
2023-10-08 572fd8325c78965f462cc19847033dac86fc5be6
提交 | 用户 | age
a24ca9 1 package com.hx.phip.service.order.impl;
Z 2
9897b5 3 import com.alibaba.fastjson.JSON;
a24ca9 4 import com.alibaba.fastjson.JSONArray;
823513 5 import com.alibaba.fastjson.JSONObject;
a24ca9 6 import com.hx.common.service.CommonService;
6942c5 7 import com.hx.exception.TipsException;
a24ca9 8 import com.hx.mybatisTool.SqlSentence;
fd269d 9 import com.hx.phiappt.common.*;
d993a2 10 import com.hx.phiappt.constants.tool.*;
fd269d 11 import com.hx.phiappt.constants.tool.model.MessageTemplate;
ebc87a 12 import com.hx.phiappt.constants.tool.order.OrderUtil;
386c9d 13 import com.hx.phiappt.constants.tool.user.UserLabelTool;
a24ca9 14 import com.hx.phiappt.model.*;
fd269d 15 import com.hx.phiappt.model.consume.ConsumePay;
6a4f14 16 import com.hx.phiappt.model.coupon.Coupon;
Z 17 import com.hx.phiappt.model.coupon.CouponNumber;
c1d896 18 import com.hx.phiappt.model.coupon.CouponOrderDiscountLog;
56f07c 19 import com.hx.phiappt.model.memberLevel.MemberLevel;
6942c5 20 import com.hx.phiappt.model.order.*;
Z 21 import com.hx.phiappt.model.user.UserProjectItem;
26ac4c 22 import com.hx.phiappt.tool.CouponCheckTool;
314764 23 import com.hx.phip.config.ApproveConfig;
a24ca9 24 import com.hx.phip.config.CustomParameter;
6942c5 25 import com.hx.phip.dao.mapper.*;
572fd8 26 import com.hx.phip.model.ApplyParameter;
A 27 import com.hx.phip.model.SysParameter;
a24ca9 28 import com.hx.phip.service.OrdersTotalService;
f9fd77 29 import com.hx.phip.service.ProjectService;
572fd8 30 import com.hx.phip.service.SystemParameterService;
e63a65 31 import com.hx.phip.service.deduction.DeductionSingleService;
42d29a 32 import com.hx.phip.service.init.OrderInitService;
e03fd8 33 import com.hx.phip.service.order.OrderRiseService;
a24ca9 34 import com.hx.phip.service.order.OrderServiceV2;
26ebce 35 import com.hx.phip.service.userLevel.UserLevelRuleService;
572fd8 36 import com.hx.phip.tool.ApplyParameterTool;
A 37 import com.hx.phip.tool.SendSMSTool;
e63a65 38 import com.hx.phip.tool.deduction.UserDeductionSingleTool;
823513 39 import com.hx.phip.util.OrdersSnapshotUtil;
d993a2 40 import com.hx.phip.util.api.ApiPlatformUtil;
4b9a7c 41 import com.hx.phip.util.api.*;
6942c5 42 import com.hx.resultTool.Result;
Z 43 import com.hx.util.DateUtil;
a24ca9 44 import com.hx.util.StringUtils;
659adc 45 import com.hx.warehouse.feign.WOrderService;
9897b5 46 import com.hz.crm.dto.GoodsTypeDto;
2f3b3a 47 import com.hz.crm.feign.FGoodsSkuService;
9897b5 48 import com.hz.his.dto.coupon.CouponCheckDto;
F 49 import com.hz.his.dto.coupon.CouponCheckItemDto;
6942c5 50 import com.hz.his.dto.gzh.GzhTemplateVO;
e63a65 51 import com.hz.his.dto.order.PayDto;
c3d8f9 52 import com.hz.his.feign.service.dcp.SUserTagInfoService;
d63b45 53 import com.hz.his.feign.service.marketing.MOrderService;
9897b5 54 import com.hz.his.feign.service.phis.SCouponService;
6942c5 55 import com.hz.his.feign.service.phisAdmin.SGzhTemplateService;
a24ca9 56 import com.hz.his.feign.service.sync.SyncOrderService;
9897b5 57 import com.hz.phis.dt.ListDt;
F 58 import com.hz.phis.dt.coupon.CouponCheckDt;
6942c5 59 import com.platform.constants.PlatformPattern;
e63a65 60 import com.platform.entity.ThirtApplication;
823513 61 import com.platform.exception.PlatTipsException;
Z 62 import com.platform.resultTool.PlatformCode;
572fd8 63 import com.platform.resultTool.SystemCode;
a24ca9 64 import org.slf4j.Logger;
Z 65 import org.slf4j.LoggerFactory;
6942c5 66 import org.springframework.scheduling.annotation.Async;
a24ca9 67 import org.springframework.stereotype.Service;
Z 68 import org.springframework.transaction.annotation.Transactional;
69
70 import javax.annotation.Resource;
71 import java.math.BigDecimal;
9897b5 72 import java.math.RoundingMode;
36ca20 73 import java.text.DecimalFormat;
a24ca9 74 import java.util.*;
823513 75 import java.util.stream.Collectors;
a24ca9 76
Z 77 /**
f9fd77 78  * 开单实现类
a24ca9 79  *
Z 80  * @Author: zhouxiang
81  * @Date: 2022/09/19/15:32
82  * @Description:
83  */
84 @Transactional
85 @Service
86 public class OrderServiceV2Impl implements OrderServiceV2 {
87     //log4j日志
88     private static Logger logger = LoggerFactory.getLogger(OrderServiceV2Impl.class.getName());
d64999 89
a24ca9 90     private static List<String> orderTypeList= Arrays.asList(OrderTotalConstants.TYPE_RECHARGE,OrderTotalConstants.TYPE_TURN_RECHARGE);
Z 91
92     @Resource
93     private SystemParameterMapper systemParameterMapper;
94     @Resource
95     private OrdersTotalService ordersTotalService;
96     @Resource
97     private CustomParameter customParameter;
f9fd77 98     @Resource
Z 99     private ProjectService projectService;
823513 100     @Resource
Z 101     private CommonService commonService;
6942c5 102     @Resource
Z 103     private SGzhTemplateService sGzhTemplateService;
2f3b3a 104     @Resource
Z 105     private FGoodsSkuService fGoodsSkuService;
d63b45 106     @Resource
Z 107     private MOrderService mOrderService;
659adc 108     @Resource
Z 109     private WOrderService wOrderService;
ae7de4 110     @Resource
314764 111     private ApproveConfig approveConfig;
42d29a 112     @Resource
C 113     private OrderInitService orderInitService;
c3d8f9 114     @Resource
A 115     private SUserTagInfoService sUserTagInfoService;
9897b5 116     @Resource
F 117     private SCouponService sCouponService;
26ebce 118     @Resource
A 119     private UserLevelRuleService userLevelRuleService;
e63a65 120     @Resource
C 121     private DeductionSingleService deductionSingleService;
e03fd8 122     @Resource
F 123     private OrderRiseService orderRiseService;
572fd8 124     @Resource
A 125     private SystemParameterService systemParameterService;
d63b45 126
e2c918 127     /**
F 128      * @param opShopId 操作人门店
129      * */
d63b45 130     @Override
eb25b2 131     public Map<String, Object> orderCreate(OrdersTotal ordersTotal, List<OrderItem> items, Integer type, List<OrderDeveloper> orderDeveloperList
e2c918 132             , Map<String, String> operator, Shop shop,String opShopId, UserMoney userMoney, User user, PlatformApplication platformApplication
eb25b2 133             , List<OrderRise> orderRiseList, CommonService commonService) {
d63b45 134         //定义总订单金额初始字段
e8809b 135         //总订单订单售价总金额
d63b45 136         BigDecimal totalPrice=BigDecimal.ZERO;
e8809b 137         //总订单订单原价总金额
Z 138         BigDecimal oriTotal=BigDecimal.ZERO;
d63b45 139         //总订单应付支付总金额
Z 140         BigDecimal shouldOrderTotal=BigDecimal.ZERO;
6f4129 141         //总订单的总积分
F 142         BigDecimal totalPoints = BigDecimal.ZERO;
143         //总订单的应付总积分
144         BigDecimal shouldTotalPoints = BigDecimal.ZERO;
91de2f 145         //总订单的折扣金额
d63b45 146         BigDecimal discountTotal=BigDecimal.ZERO;
3043fe 147         //非主线任务节点报错标记
d31c0f 148         Integer nodeType=0;
d63b45 149
Z 150         //是否老带新
151         Integer isOldBringNew =BaseEntity.NO;
e1d05e 152         //是否初诊单
Z 153         Integer isBothTheOne =BaseEntity.NO;
d63b45 154
Z 155         //返回参数
156         Map<String,Object> data=new HashMap<>();
157         //开单节点日志
158         OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
159         StringBuilder orderCreate = new StringBuilder();
160
161         SqlSentence sqlSentence=new SqlSentence();
162         Map<String, Object> appIdMap = new HashMap<>();
163         sqlSentence.setM(appIdMap);
164
fd7281 165         //主线业务
3043fe 166         //业务逻辑判断(商品限制、订单重复等)
Z 167         OrderCreateUtil.businessJudge(ordersTotal,items,user,shop,ordersTotalService,commonService);
168
169         /**
170          * 计算订单金额信息(计算请求参数的一级子订单)
171          *      1、充值订单不需要系统计算金额,充多少是多少
172          *      2、商品、项目、促销、卡项、卡向内等均系统计算订单金额
173          *      3、处理活动规则(主要处理是满减、满折扣情况),对总订单金额进行扣减
174          */
175         if(orderTypeList.contains(ordersTotal.getType())){
176             //订单充值总金额
177             totalPrice=ordersTotal.getTotal();
178             //订单应付付总金额
179             shouldOrderTotal=ordersTotal.getTotal();
180         }else {
e2c918 181             Map<String, Object> handOrderItemMap = OrderCreateUtil.handOrderItem(ordersTotal, shop,opShopId, items, totalPrice, shouldOrderTotal,discountTotal,oriTotal, commonService, systemParameterMapper);
6f4129 182             totalPrice = (BigDecimal) handOrderItemMap.get("totalPrice");
F 183             shouldOrderTotal = (BigDecimal) handOrderItemMap.get("shouldOrderTotal");
184             discountTotal = (BigDecimal) handOrderItemMap.get("discountTotal");
185             oriTotal = (BigDecimal) handOrderItemMap.get("oriTotal");
186             totalPoints = (BigDecimal) handOrderItemMap.get("totalPoints");
187             shouldTotalPoints = (BigDecimal) handOrderItemMap.get("shouldTotalPoints");
188             items = (List<OrderItem>) handOrderItemMap.get("items");
3043fe 189         }
Z 190
191         //处理活动规则,活动规则如果是满减、折扣,则订单应付金额需要扣减活动规则金额,(目前只有充值订单才能用到活动规则)
192         if(OrderTotalConstants.TYPE_RECHARGE.equals(ordersTotal.getType()) &&  ordersTotal.getActivityIds() !=null && ordersTotal.getActivityIds().size()>0){
cfef0d 193             ordersTotal.setShouldTotal(totalPrice);
3043fe 194             BigDecimal price=OrderAddUtil.activityRule(ordersTotal,commonService,operator,userMoney,customParameter,user,0);
bf543d 195             if(!price.equals(BigDecimal.ZERO)){
3043fe 196                 ordersTotal.setActivityTotal(shouldOrderTotal.subtract(price));
Z 197                 shouldOrderTotal=price;
198             }
199         }
200
201
202         //处理订单基本信息(总订单和子订单)
203         //处理总订单开发人,默认客户的所属顾问,注意如果是crm开单的传什么就是什么
204         OrderCreateUtil.handUserDeveloper(ordersTotal,user,orderTypeList,commonService);
205
206         //构架总订单基本信息,金额信息,并保存(orderTotal、orderInfo)
207         OrderCreateUtil.setOrderTotal(ordersTotal, shop, totalPrice, shouldOrderTotal, discountTotal,
6f4129 208                 operator.get("operatorId"),operator.get("operatorName"),Integer.valueOf(operator.get("operatorType"))
F 209                 ,oriTotal, totalPoints, shouldTotalPoints
210                 ,type,user,systemParameterMapper, platformApplication,commonService);
232e08 211
3043fe 212         ordersTotal = OrderCreateUtil.createOrder(ordersTotal, operator, user, userMoney, commonService);
Z 213
f15332 214         //开单优先校验处理升单关联信息,出错后不再往下走其他逻辑
F 215         OrderCreateUtil.createOrderRiseInfo(commonService, ordersTotal, orderRiseList);
216
217
5dca89 218         //保存活动规则信息(目前只有充值订单才能用到活动规则)
Z 219         OrderCreateUtil.insertActivity(ordersTotal.getActivityIds(),ordersTotal,commonService);
220
91de2f 221         //非主线业务
d63b45 222         try {
e1d05e 223             //判断是否是初诊单
Z 224             nodeType=3;
225             orderCreate.append("-开始判断是否是初诊单");
e7427f 226             // 改集中工具类 复制于翔爷代码 统一方便修改代码
A 227             isBothTheOne = OrderUtil.checkIsBothTheOne(ordersTotal, commonService, VisitRecordMapper.class);
e1d05e 228             orderCreate.append("-结束判断是否是初诊单");
e9e4f9 229             nodeType=4;
6d1e4e 230             //订单如果为复诊单那么就是老带新订单,对应禅道需求编号694
9a9cd0 231 //            if(isBothTheOne !=null && isBothTheOne==OrderInfo.CONSULTATION){
Z 232 //                isOldBringNew=BaseEntity.YES;
233 //            }
c96a16 234             //判断是否老带新
Z 235             nodeType=1;
236             orderCreate.append("-开始判断是否老带新");
237             // 改集中工具类 复制于翔爷代码 统一方便修改代码
238             ordersTotal.getOrderInfo().setIsBothTheOne(isBothTheOne);
5286d6 239             ordersTotal.getOrderInfo().setIsBothTheOneInitial(isBothTheOne);
c96a16 240             isOldBringNew = OrderUtil.checkOldBringNew(ordersTotal, commonService, VisitRecordMapper.class);
Z 241             orderCreate.append("-结束判断是否老带新");
242             nodeType=2;
e9e4f9 243
d63b45 244         }catch (Exception e){
3043fe 245             String nodeText="";
d31c0f 246             if(nodeType>=1 && nodeType<2){
3043fe 247                 nodeText="判断是否老带新失败";
Z 248                 orderCreate.append("-判断是否老带新失败,异常信息:"+e.getMessage());
e1d05e 249             }else if(nodeType>=3 && nodeType<4){
Z 250                 nodeText="判断是否是初诊单失败";
251                 orderCreate.append("-判断是否是初诊单失败,异常信息:"+e.getMessage());
d31c0f 252             }
3043fe 253             //记录非主线日志(处理到具体节点(成功和失败))
Z 254             ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_CREATE);
255             ordersNodeLog.setContent(orderCreate.toString());
256             ordersNodeLog.setOrderId(ordersTotal.getId());
257             commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
258
d31c0f 259             //异常发送企业微信通知给工作人员
3043fe 260             SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),nodeText,commonService,customParameter);
Z 261             logger.info("开单"+nodeText+",异常原因:{}",e.getMessage(),e);
d63b45 262             e.printStackTrace();
Z 263         }
264
eb25b2 265         //主线业务
3043fe 266         //保存订单其他信息(对象:orderInfo)
7ac388 267         String activityName = OrderCreateUtil.saveOrderInfo(ordersTotal, user,customParameter,isOldBringNew,isBothTheOne, commonService);
3043fe 268
Z 269         //保存一级子订单和处理二级子订单信息(orderItem、orderItemSon)
270         if(!orderTypeList.contains(ordersTotal.getType())){
271             //创建子订单
272             OrderCreateUtil.createOrderItem(ordersTotal, items,projectService,commonService,sqlSentence,appIdMap);
273         }
274         //生成订单日志
275         commonService.insert(OrderLogMapper.class, ApiOrderUtil.setOrderLog(ordersTotal, null, operator.get("operatorId"), operator.get("operatorName"), activityName, 0, OrderLogConstants.LOG_TYPE_CREATE));
276
277         //保存绑定的其他开发人集合信息
278         OrderAddUtil.creatDeveloperList(ordersTotal, orderDeveloperList,commonService);
279
314764 280
F 281         //如果是开单开了设置的卡项
282         if (haveCard(items)){
283             //营销助手审批,如果订单有支付
284             if(StringUtils.isEmpty(ordersTotal.getKoapOrderId())&& ordersTotal.getOrderInfo()!=null) {
285                 OrderCreateUtil.approvalPayMarketing(ordersTotal,items,mOrderService,commonService);
286             }
287         }else {
288             //营销助手审批,如果订单有折扣
289             if(StringUtils.isEmpty(ordersTotal.getKoapOrderId())&& ordersTotal.getOrderInfo()!=null) {
290                 OrderCreateUtil.approvalMarketing(ordersTotal,mOrderService,commonService);
291             }
3043fe 292         }
314764 293
3043fe 294
Z 295         //返回phis订单号、phis订单id
296         data.put("orderNo",ordersTotal.getOrderNo());
297         data.put("orderId",ordersTotal.getId());
298
d63b45 299         return data;
314764 300     }
F 301
302     /**判断子订单是否包含对应的要审核的卡项*/
303     private boolean haveCard(List<OrderItem> items) {
304         boolean isHaveCard = false;
305         String cardNoString = approveConfig.getCardNoList();
306         if (!StringUtils.isEmpty(cardNoString)){
307             List<String> collect = Arrays.stream(cardNoString.split(ApproveConfig.SIGN)).collect(Collectors.toList());
308             if (collect.size() > 0){
309                 for (String s : collect) {
310                     for (OrderItem item : items) {
311                         if (!StringUtils.isEmpty(item.getGoodsNo()) && s.equals(item.getGoodsNo())){
312                             isHaveCard = true;
313                             break;
314                         }
315                     }
316                 }
317             }
318         }
319         return isHaveCard;
d63b45 320     }
Z 321
0c698a 322     /**
A 323      * 处理优惠券发送人和订单推荐人
324      * @param couponNumber 优惠券
325      * @param coupon 优惠券配置
326      * @param ordersTotal 订单
327      * @param orderInfo 订单详情
328      */
329     private void couponSentInfo(CouponNumber couponNumber, Coupon coupon, OrdersTotal ordersTotal, OrderInfo orderInfo) {
330         // 都不等于空同时订单信息没用发放人
028e90 331         if (coupon != null && couponNumber != null && ordersTotal != null && orderInfo != null && StringUtils.isEmpty(ordersTotal.getInviteeId())) {
0c698a 332             // 排除生日券处理同时发送人不为空
A 333             if (BaseEntity.NO.equals(coupon.getIsBirthday()) && !StringUtils.isEmpty(couponNumber.getSendId())) {
334                 // 员工信息
335                 Employee employee = commonService.selectOneByKey(EmployeeMapper.class, couponNumber.getSendId());
336                 if (employee != null) {
337                     // 判断是否是crm平台下单
338                     if (PlatformConstants.TYPE_PLATFORM_CRM.equals(ordersTotal.getAppIdCode())) {
339                         // 没有推荐人
340                         if (StringUtils.isEmpty(ordersTotal.getInviteeId())) {
028e90 341                             ordersTotal.setInviteeType(UserChannelType.CATEGORY_EMPLOYEE);
0c698a 342                             ordersTotal.setInviteeId(employee.getId());
A 343                             ordersTotal.setInviteeName(employee.getCnName());
344                         }
345                     }
346                 } else {
347                     // 用户信息
348                     User user = commonService.selectOneByKey(UserMapper.class, couponNumber.getUserId());
349                     if (user != null) {
350                         // 判断是否是crm平台下单
351                         if (PlatformConstants.TYPE_PLATFORM_CRM.equals(ordersTotal.getAppIdCode())) {
352                             // 没有推荐人
353                             if (StringUtils.isEmpty(ordersTotal.getInviteeId())) {
354                                 ordersTotal.setInviteeType(UserChannelType.CATEGORY_MEMBERS);
355                                 ordersTotal.setInviteeId(user.getId());
356                                 ordersTotal.setInviteeName(user.getName());
357                                 ordersTotal.setUserBelongingType(user.getUserBelongingType());
358                             }
359                         }
360                     }
361                 }
362             }
363         }
364     }
365
d63b45 366     @Override
e63a65 367     public Map<String, Object> orderPayMoney(Integer couponCheckVersion, Integer type, OrdersTotal ordersTotal, User user, User payUser, Shop shop, OrderInfo info, List<OrderItem> orderItemList,
fbde78 368                                              Map<String, String> operator, UserMoney userMoney, String total, JSONArray amountList, JSONArray userCouponIds,
e63a65 369                                              PayDto payDto, ThirtApplication thirtApplication) {
374c64 370         String message="";
d63b45 371         //订单优惠券金额
Z 372         BigDecimal couponAfterAmount =BigDecimal.ZERO;
373
374         //用户支付方式集合,用于同步到his系统
375         JSONArray hisPayList=new JSONArray();
376
377         //接口返回参数map
378         Map<String,Object> data=new HashMap<>();
379
380         //订单节点日志
381         OrdersNodeLog ordersNodeLog = new OrdersNodeLog();
94bf3f 382         StringBuilder orderNodeBuilder = new StringBuilder();
d63b45 383
fbde78 384 //        if(userCouponIds!=null && userCouponIds.size()>0){
Z 385 //            //获取优惠券金额
386 //            couponAfterAmount = CouponTool.handCouponAmout(ordersTotal.getShouldTotal(), coupon);
387 //        }
388
d68a60 389         //升单的订单在开始结账时就要处理对应逻辑
0458cf 390         if(OrderTotalConstants.ADD_WAY_RISE.equals(ordersTotal.getAddWay())){
e03fd8 391             orderRiseService.beforeCheckoutHandle(ordersTotal, operator.get("operatorId"), operator.get("opRoleId"), amountList, thirtApplication);
F 392         }
6a4f14 393
e2ef5a 394         orderNodeBuilder.append("开始结账");
Z 395         /**
396          * 处理优惠券金额,先计算优惠金额因为优惠券金额也需要参加到业务判断金额是否符合
397          */
fbde78 398         if(userCouponIds!=null && userCouponIds.size()>0){
e2ef5a 399             orderNodeBuilder.append("-开始处理优惠券信息");
fbde78 400             CouponNumber couponNumber=null;
Z 401             Coupon coupon=null;
9897b5 402             //旧版逻辑
F 403             if (couponCheckVersion == null || couponCheckVersion == 0){
404                 //判断优惠券是否可以使用,以及保存订单使用优惠券记录,以及线下券核销操作
405                 for(int i=0;i<userCouponIds.size();i++){
406                     String couponId = userCouponIds.getString(i);
407                     //查看用户是否有优惠券
408                     couponNumber = commonService.selectOneByKey(CouponNumberMapper.class, couponId);
409                     //查看用户是否有优惠券
410                     coupon = commonService.selectOneByKey(CouponMapper.class, couponNumber.getCouponId());
411                     BigDecimal couponTotal = OrderPayMoneyUtil.handCoupon(couponNumber, coupon, orderItemList, ordersTotal.getId(), ordersTotal.getShouldTotal(), user, commonService, fGoodsSkuService);
412                     couponAfterAmount=couponAfterAmount.add(couponTotal);
0c698a 413                     // 优惠券发送人处理
A 414                     this.couponSentInfo(couponNumber, coupon, ordersTotal, ordersTotal.getOrderInfo());
9897b5 415                 }
F 416             }else {
417                 List<CouponNumber> couponNumberList = new ArrayList<>();
418                 //新版逻辑
419                 CouponCheckDto couponCheckDto = new CouponCheckDto();
b43a7c 420
F 421                 //1.封装优惠券码
9897b5 422                 List<String> couponNumberIdList = new ArrayList<>();
F 423                 for(int i=0;i<userCouponIds.size();i++) {
424                     couponNumberIdList.add(userCouponIds.getString(i));
d55321 425                     CouponNumber userCouponNumber = commonService.selectOneByKey(CouponNumberMapper.class, userCouponIds.getString(i));
F 426                     if (userCouponNumber != null){
427                         Coupon userCoupon = commonService.selectOneByKey(CouponMapper.class, userCouponNumber.getCouponId());
428                         if (userCoupon != null){
429                             userCouponNumber.setType(userCoupon.getType());
0c698a 430                             // 优惠券发送人处理
A 431                             this.couponSentInfo(userCouponNumber, userCoupon, ordersTotal, ordersTotal.getOrderInfo());
d55321 432                         }
F 433                     }
434                     couponNumberList.add(userCouponNumber);
9897b5 435                 }
F 436                 couponCheckDto.setCouponNumberIdList(couponNumberIdList);
fbde78 437
b43a7c 438                 //2.封装商品信息
9897b5 439                 List<CouponCheckItemDto> goodsList = new ArrayList<>();
F 440                 for (OrderItem orderItem : orderItemList) {
441                     CouponCheckItemDto couponCheckItemDto = new CouponCheckItemDto();
b43a7c 442                     couponCheckItemDto.setSkuId(orderItem.getPlatformTypeId());
F 443                     couponCheckItemDto.setHisId(orderItem.getCommonId());
444                     couponCheckItemDto.setHisType(orderItem.getType());
445                     couponCheckItemDto.setPrice(orderItem.getProPrice());
446                     couponCheckItemDto.setBuyNum(orderItem.getBuyNum());
9897b5 447
b43a7c 448                     //获取商品所属分类
9897b5 449                     GoodsTypeDto goodsTypeDto = new GoodsTypeDto();
b43a7c 450                     if (!StringUtils.isEmpty(orderItem.getPlatformTypeId())){
F 451                         goodsTypeDto.setSkuId(orderItem.getPlatformTypeId());
452                     }else if (!StringUtils.isEmpty(orderItem.getCommonId())){
453                         goodsTypeDto.setHisId(orderItem.getCommonId());
9897b5 454                     }
F 455                     Result result = fGoodsSkuService.goodsSkuTypeList(goodsTypeDto);
456                     if (result == null || !result.checkCode()){
457                         logger.error("优惠券校验-获取所属分类信息失败"+JSON.toJSONString(result));
458                         throw new TipsException("优惠券校验失败,错误代码01");
459                     }
460                     ListDt listDt = result.getObject(result.getData(), ListDt.class);
461                     if (listDt == null){
462                         logger.error("优惠券校验-获取所属分类信息失败,转换信息为空"+JSON.toJSONString(result));
463                         throw new TipsException("优惠券校验失败,错误代码02");
464                     }
465                     couponCheckItemDto.setTypeIdList(listDt.getList().stream().map(a -> (String)a.get("id")).collect(Collectors.toList()));
b43a7c 466
9897b5 467                     goodsList.add(couponCheckItemDto);
F 468                 }
469                 couponCheckDto.setGoodsList(goodsList);
b43a7c 470                 //3.封装支付方式
9897b5 471                 List<String> payMethodList = new ArrayList<>();
F 472                 for(int i=0;i<amountList.size();i++) {
473                     JSONObject object = amountList.getJSONObject(i);
474                     payMethodList.add(object.getString("method"));
475                 }
476                 couponCheckDto.setPayMethodList(payMethodList);
b43a7c 477
9897b5 478                 logger.info("校验优惠券,参数"+JSON.toJSONString(couponCheckDto));
f3819f 479 //                Result result = sCouponService.unifyCheck(couponCheckDto);
F 480 //                logger.info("校验优惠券,返回"+JSON.toJSONString(result));
481 //                if (result == null){
482 //                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠券校验不通过-错误代码01");
483 //                }
484 //                if (!result.checkCode()){
485 //                    throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠券校验不通过-错误代码02");
486 //                }
487 //                CouponCheckDt couponCheckDt = result.getObject(result.getData(), CouponCheckDt.class);
488                 CouponCheckDt couponCheckDt = CouponCheckTool.unifyCheck(couponCheckDto, commonService);
489                 logger.info("校验优惠券,返回"+JSON.toJSONString(couponCheckDt));
9897b5 490                 if (couponCheckDt == null){
F 491                     throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠券校验不通过-错误代码03");
492                 }
493                 if (couponCheckDt.getIsErr()){
b43a7c 494                     throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠券校验不通过,"+couponCheckDt.getErrMsg());
9897b5 495                 }
F 496                 if (!couponCheckDt.getIsCanUse()){
b43a7c 497                     throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠券校验不通过,"+couponCheckDt.getUnavailableMsg());
9897b5 498                 }
F 499                 //叠加金额,先算满减的叠加
d55321 500                 List<CouponNumber> moneyList = couponNumberList.stream().filter(a -> a.getType() != null && a.getType().equals(Coupon.TYPE_AMOUNT)).collect(Collectors.toList());
9897b5 501                 for (CouponNumber number : moneyList) {
F 502                     BigDecimal couponTotal = OrderPayMoneyUtil.handCouponNew(number, ordersTotal.getId(),
503                             user.getId(), ordersTotal.getShouldTotal(),commonService);
504                     couponAfterAmount = couponAfterAmount.add(couponTotal);
505                 }
506                 //再算剩余的折扣
d55321 507                 List<CouponNumber> disList = couponNumberList.stream().filter(a -> a.getType() != null && a.getType().equals(Coupon.TYPE_DIS)).collect(Collectors.toList());
9897b5 508                 for (CouponNumber number : disList) {
F 509                     BigDecimal couponTotal = OrderPayMoneyUtil.handCouponNew(number,ordersTotal.getId(), user.getId(),
510                             ordersTotal.getShouldTotal().subtract(couponAfterAmount).setScale(2, RoundingMode.HALF_UP), commonService);
511                     couponAfterAmount = couponAfterAmount.add(couponTotal);
512                 }
fbde78 513             }
e2ef5a 514             orderNodeBuilder.append("-结束处理优惠券信息");
Z 515         }
516
7e14a4 517         //判断升单金额逻辑
F 518         if(OrderTotalConstants.ADD_WAY_RISE.equals(ordersTotal.getAddWay())){
519             OrderPayMoneyUtil.riseCheckOutAmount(couponAfterAmount, ordersTotal, amountList);
520         }
9897b5 521
fbde78 522         /**
Z 523          * 业务判断(判断金额是否符合(需要把优惠券金额加进用户支付金额进行判断),状态是否能结账,项目、商品、促销、卡项等模板限制等)
524          */
525         OrderPayMoneyUtil.checkOrderAmount(type, ordersTotal, couponAfterAmount, total, amountList,orderItemList,user,commonService);
94bf3f 526
56f07c 527         ///////支付人信息填充
C 528         if(!payUser.getId().equals(ordersTotal.getUserId())){
529             //是否代付
530             ordersTotal.setIsGenerationPay(BaseEntity.YES);
531         }
dc0e3f 532         ordersTotal.setPayUserId(payUser.getId());
56f07c 533         ordersTotal.setPayUserNo(payUser.getMemberNO());
C 534         ordersTotal.setPayUserName(payUser.getName());
535         ordersTotal.setPayUserCIQ(payUser.getCIQ());
536         ordersTotal.setPayUserMemberId(payUser.getMemberLevelId());
537         if(StringUtils.noNull(payUser.getMemberLevelId())){
538             MemberLevel memberLevel = commonService.selectOneByKey(MemberLevelMapper.class,payUser.getMemberLevelId());
539             if(memberLevel != null){
540                 ordersTotal.setPayUserMemberNo(memberLevel.getHisNo());
541             }
542         }
543         ordersTotal.setPayUserLevel(payUser.getUserLevel());
544         ordersTotal.setPayUserAdviserId(payUser.getHisCorpUserId());
b0e13c 545         ordersTotal.setPayUserAdviserName(payUser.getHisCorpUserName());
56f07c 546         if(StringUtils.noNull(payUser.getHisCorpUserId())){
C 547             Employee employee = commonService.selectOneByKey(EmployeeMapper.class,payUser.getHisCorpUserId());
548             if(employee != null){
549                 ordersTotal.setPayUserAdviserNo(employee.getEmployeeNo());
b0e13c 550                 ordersTotal.setPayUserAdviserName(employee.getCnName());
56f07c 551             }
C 552         }
553         ordersTotal.setPayUserShopId(payUser.getShopId());
554         if(StringUtils.noNull(payUser.getShopId())){
555             Shop shop1 = commonService.selectOneByKey(ShopMapper.class,payUser.getShopId());
556             if(shop1 != null){
557                 ordersTotal.setPayUserShopNo(shop1.getCode());
558                 ordersTotal.setPayUserShopName(shop1.getName());
559             }
560         }
561
b1fcb2 562         //主业务
d63b45 563         try {
e2ef5a 564
b1fcb2 565
Z 566             /**
567              * 处理支付记录
568              */
569             orderNodeBuilder.append("-开始处理订单支付记录");
570             //计算金额信息-根据用户支付集合计算用户实际支付金额
e63a65 571             Map<String, Object> objectMap = OrderPayMoneyUtil.handPayMethod(payDto,amountList, ordersTotal, commonService, customParameter);
b1fcb2 572             //总订单
Z 573             ordersTotal= (OrdersTotal) objectMap.get("ordersTotal");
574             //一级子订单用户实际支付金额,该Map用于统计用户按照项目部分付款
575             Map<String,String>itemMap= (Map<String, String>) objectMap.get("itemMap");
576             //订单的已支付现金金额(微信/支付宝支付/其他)
577             BigDecimal payTotal= (BigDecimal) objectMap.get("payTotal");
578             //订单的已支付储值金金额
579             BigDecimal payRecharge= (BigDecimal) objectMap.get("payRecharge");
580             //订单的已支付增值金金额
581             BigDecimal payIncrement= (BigDecimal) objectMap.get("payIncrement");
582             //订单现金支付总金额
583             BigDecimal snapPayTotal= (BigDecimal) objectMap.get("snapPayTotal");
584             //订单现金支付总金额
585             BigDecimal snapExecuteTotal= (BigDecimal) objectMap.get("snapExecuteTotal");
766aa8 586             //订单已支付积分
F 587             BigDecimal actualTotalPoints = (BigDecimal) objectMap.get("totalPoints");
b1fcb2 588             //用户支付方式集合,用于同步到his系统
Z 589             hisPayList= (JSONArray) objectMap.get("hisPayList");
590             //存储卡项id,用户判断用户是否使用的是卡包进行结算
591             List<String> cardIds= (List<String>) objectMap.get("cardIds");
592             orderNodeBuilder.append("-结束处理订单支付记录");
593
594             /**
595              * 处理充值订单-增加储值金
596              */
597             if(orderTypeList.contains(ordersTotal.getType())){
598                 orderNodeBuilder.append("-开始处理充值订单增加储值金");
599                 OrderPayMoneyUtil.handRecharge(ordersTotal, amountList, objectMap, commonService);
600                 orderNodeBuilder.append("-结束处理充值订单增加储值金");
601             }
602
603             /**
604              * 处理订单基本信息(总订单和子订单)
605              */
606             orderNodeBuilder.append("-开始处理订单基本信息");
607             //更改订单基本信息(商品、项目、促销、卡项、卡集基本信息)
608             //更新一级子订单或者二级子订单(需要处理未执行划扣金额、项目生成未执行划扣、商品生成提货单(目前没有库存不处理)、促销、卡项(目前不处理)、卡包)
9c136d 609             ordersTotal.getOrderInfo().setSnapPayTotal(snapPayTotal);
Z 610             ordersTotal.getOrderInfo().setSnapExecuteTotal(snapExecuteTotal);
b1fcb2 611             if(!orderTypeList.contains(ordersTotal.getType())){
9ae4b2 612                 OrderPayMoneyUtil.payHandOrderItem(orderItemList,ordersTotal, itemMap,operator ,userMoney,cardIds,user,
129962 613                         couponAfterAmount,wOrderService,payTotal, payRecharge,payIncrement, actualTotalPoints,commonService,customParameter);
b1fcb2 614
Z 615             }
616             //更新总订单状态、金额信息、记录日志
766aa8 617             OrderPayUtil.payHandleOrderTotal(operator, ordersTotal, payTotal, payRecharge, couponAfterAmount,payIncrement,actualTotalPoints,commonService);
b1fcb2 618             orderNodeBuilder.append("-结束处理订单基本信息");
Z 619
6875f3 620             //--非常重要:结账成功之后,重新算订单部分金额信息。注意:该程序只能运行一次
ff4006 621             orderInitService.initOrder(ordersTotal.getId(),true,true);
42d29a 622
e63a65 623             //--直接划扣订单里面的所有项目
C 624             if(payDto.getDirectDeduction() != null && payDto.getDirectDeduction().equals(BaseEntity.YES)){
625                 UserDeductionSingleTool.orderDeduction(ordersTotal,thirtApplication,deductionSingleService,commonService);
626             }
b1fcb2 627
d63b45 628             /**
Z 629              * 处理活动规则
fe13fe 630              */
Z 631             orderNodeBuilder.append("-开始处理活动规则");
143537 632             OrderPayMoneyUtil.handActivity(ordersTotal, user, operator, userMoney,commonService,customParameter);
fe13fe 633             orderNodeBuilder.append("-结束处理活动规则");
9c136d 634
ec073d 635             //非主线业务
Z 636
9c136d 637             /**
ec073d 638              * 用户升降级(调用航爷) 金额=用户支付的实付现金金额(不包含储值金)
Z 639              */
640             if(snapPayTotal !=null && snapPayTotal.compareTo(BigDecimal.ZERO) == 1){
641                 try {
642                     orderNodeBuilder.append("-开始处理用户升降级");
26ebce 643                     UserLevelUtil.order(userLevelRuleService, ordersTotal.getUserId(),ordersTotal.getId(),snapPayTotal,ordersTotal.getAppIdCode());
ec073d 644                     orderNodeBuilder.append("-结束处理用户升降级");
Z 645                 }catch (Exception e){
646                     String snapshot="处理用户升降级失败";
647                     orderNodeBuilder.append("-处理用户升降级失败,异常原因:"+e.getMessage());
648                     logger.error("处理用户升降级失败:" + e.getMessage());
649                     //发送企业微信通知给工作人员
650                     SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),snapshot,commonService,customParameter);
651                 }
143537 652             }
fe13fe 653
d63b45 654             //用户活跃状态处理(先暂时不处理)
Z 655
656             /**
657              * 快照
658              */
659             //订单快照
660             if(OrderTotalConstants.STATUS_PAY == ordersTotal.getStatus() || OrderTotalConstants.STATUS_DONE == ordersTotal.getStatus()){
661                 // 状态 已支付与已完成
662                 try {
94bf3f 663                     orderNodeBuilder.append("-开始处理订单快照");
d63b45 664                     OrdersSnapshotUtil.createOrdersSnapshot(customParameter, ordersTotal.getId(), commonService);
94bf3f 665                     orderNodeBuilder.append("-结束处理订单快照");
d63b45 666                 } catch (Exception e) {
Z 667                     String snapshot="处理订单快照失败";
b294bc 668                     orderNodeBuilder.append("-处理订单快照失败,异常原因:"+e.getMessage());
d63b45 669                     logger.error("生成快照失败:" + e.getMessage());
Z 670                     //发送企业微信通知给工作人员
671                     SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),snapshot,commonService,customParameter);
374c64 672                     message=e.getMessage();
d63b45 673                 }
Z 674             }
675
676             Integer synHisOrderType=0;
677
678             /**
679              * 同步
680              */
350069 681 //            try {
Z 682 //                //同步开单-同步订单到领建
683 //                if(ordersTotal.getHisSynStatus()==1){
684 //                    orderNodeBuilder.append("-开始处理创建订单同步订单到领建");
685 //                    synHisOrderType=1;
686 //                    String hisOrderId = OrderCreateUtil.syncOrder(ordersTotal, operator,ordersTotal.getOrderNo(),customParameter,commonService);
687 //                    if(StringUtils.isEmpty(hisOrderId)){
688 //                        throw new PlatTipsException(PlatformCode.ERROR_TIPS,"同步领建失败!领建标识为空");
689 //                    }
690 //                    data.put("hisOrderId",hisOrderId);
691 //                    ordersTotal.setHisOrderId(hisOrderId);
692 //                    orderNodeBuilder.append("-结束处理创建订单同步订单到领建");
693 //
694 //                    //同步结账-同步订单到领建
695 //                    orderNodeBuilder.append("-开始处理结账同步订单到领建");
696 //                    synHisOrderType=2;
697 //                    //封装支付方式,如果结账采用了优惠券,封装支付方式为优惠券到领建,如果是积分封装支付方式为积分
698 //                    OrderPayMoneyUtil.synOrderPayWay(ordersTotal, couponAfterAmount, hisPayList);
699 //                    //将p-his结账的订单同步到领建系统
700 //                    SynOrderUtil.synPayOrder(operator, ordersTotal, shop.getApiId(), hisPayList,customParameter,commonService);
701 //                    orderNodeBuilder.append("-结束处理结账同步订单到领建");
702 //                }
703 //
704 //
705 //                //同步结账-如果是卡包支付则需要扣减领建卡包次数操作(调用同步中心接口)
706 //                if(OrderTotalConstants.TYPE_CARD_BAG.equals(ordersTotal.getType())){
707 //                    orderNodeBuilder.append("-开始处理结账扣减领建卡包次数");
708 //                    synHisOrderType=3;
709 //                    //因为p-his开的已有卡项订单是用普通项目开过去的,所以这里需要调用同步中心接口扣减已有卡项次数,切掉领建该方法也需要去掉
710 //                    RefundUtil.handHisCardBag(commonService, customParameter, ordersTotal,0);
711 //                    orderNodeBuilder.append("-结束理结账扣减领建卡包次数");
712 //                }
713 //            }catch (Exception e){
714 //                String sysPhiskin="";
715 //                switch (synHisOrderType){
716 //                    case 1:
717 //                        sysPhiskin="领建创建订单失败";
718 //                        orderNodeBuilder.append("-领建创建订单失败,异常原因:"+e.getMessage());break;
719 //                    case 2:
720 //                        sysPhiskin="领建结账同步失败";
721 //                        orderNodeBuilder.append("-领建结账同步失败,异常原因:"+e.getMessage());break;
722 //                    case 3:
723 //                        sysPhiskin="领建扣减卡包同步失败";
724 //                        orderNodeBuilder.append("-领建扣减卡包同步失败,异常原因:"+e.getMessage());break;
725 //                }
726 //                logger.info("同步订单到领建异常(创建、结账、卡包扣减)!,异常原因:{}",e.getMessage(),e);
727 //                JSONObject object = new JSONObject();
728 //                object.put("ordersTotal",ordersTotal);
729 //                object.put("type",0);
730 //                object.put("operator",operator.toString());
731 //                object.put("shopApiId",shop.getApiId());
732 //                object.put("hisPayList",hisPayList.toString());
733 //                //同步结账或扣减领建卡包次数异常失败,保存重发记录,发送企业微信通知给开发人
734 //                OrderCreateUtil.orderSendNoticeResendRecord(ordersTotal, e, object,"/phip/resend/order/create/pay/cardBag","同步订单到领建异常(创建、结账、卡包扣减)!",synHisOrderType,commonService,customParameter);
735 //                //发送企业微信通知给工作人员
736 //                SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),sysPhiskin,commonService,customParameter);
737 //                message=e.getMessage();
738 //            }
d63b45 739             try {
Z 740                 //同步结账-同步到康博佳
741                 if(PlatformPattern.PROD.equals(customParameter.getPlatformPattern()) && StringUtils.noNull(ordersTotal.getKoapOrderId())){
94bf3f 742                     orderNodeBuilder.append("-开始处理同步康博佳结账");
d63b45 743                     //将p-his结账的订单同步到康博佳系统
Z 744                     SynOrderUtil.synKoapPayOrder(operator, ordersTotal, hisPayList,customParameter,commonService);
94bf3f 745                     orderNodeBuilder.append("-结束处理同步康博佳结账");
d63b45 746                 }
Z 747             }catch (Exception e){
748                 String koapPay="处理同步康博佳结账失败";
b294bc 749                 orderNodeBuilder.append("-处理同步康博佳结账失败,异常原因:"+e.getMessage());
d63b45 750                 logger.info("同步结账-同步订单到康博佳异常!,异常原因:{}",e.getMessage(),e);
Z 751                 //封装请求参数
752                 JSONObject object = new JSONObject();
753                 object.put("ordersTotal",ordersTotal);
754                 object.put("operator",operator.toString());
755                 object.put("hisPayList",hisPayList.toString());
756                 //结账同步到康博佳失败,保存重发记录,发送企业微信通知给开发人
757                 OrderCreateUtil.orderSendNoticeResendRecord(ordersTotal, e, object,"接口名称","同步结账-同步订单到康博佳异常!",synHisOrderType,commonService,customParameter);
758                 //发送企业微信通知给工作人员
759                 SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),koapPay,commonService,customParameter);
374c64 760                 message=e.getMessage();
d63b45 761             }
Z 762
572fd8 763             // 结账成功发送公众号通知给用户 -异步
e32db7 764             try {
57f2bf 765                 sendPublicNo(ordersTotal.getId(),commonService);
6cefae 766             } catch (TipsException | PlatTipsException e){
A 767                 logger.info("结账成功发送公众号通知给用户异常 -异步:{}", e.getMessage());
768             } catch (Exception e){
769                 logger.info("结账成功发送公众号通知给用户异常 -异步:{}", e.getMessage(),e);
e32db7 770             }
236a02 771
572fd8 772             // 结账成功发送短信通知给用户 -异步
A 773             try {
774                 sentSMSInfo(ordersTotal.getId(), commonService);
775             } catch (Exception e){
776                 logger.info("结账成功发送短信通知给用户异常 -异步:{}", e.getMessage(),e);
777             }
7a8652 778
d63b45 779             //返回phis订单号、phis订单id
Z 780             data.put("orderId",ordersTotal.getId());
781             data.put("orderCode",ordersTotal.getOrderNo());
7b1698 782
Z 783             //记录日志(处理到具体节点(成功和失败))
784             orderNodeBuilder.append("-结束结账订单");
785             ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_PAY);
786             ordersNodeLog.setContent(orderNodeBuilder.toString());
787             ordersNodeLog.setOrderId(ordersTotal.getId());
788             commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
789
d63b45 790         }catch (Exception e){
b1fcb2 791             String mainBusiness="结账失败";
b294bc 792             orderNodeBuilder.append("-结账失败,异常原因:"+e.getMessage());
b1fcb2 793             logger.info("结账异常:{}",e.getMessage(),e);
Z 794             //异常发送企业微信通知给工作人员
795             SendNoticeUtil.failOrderSendNotice(ordersTotal,e.getMessage(),mainBusiness,commonService,customParameter);
374c64 796             message=e.getMessage();
7b1698 797
Z 798             //记录日志(处理到具体节点(成功和失败))
799             orderNodeBuilder.append("-结束结账订单");
800             ordersNodeLog.setCommonType(OrdersNodeLog.TYPE_COMMON_ORDER_PAY);
801             ordersNodeLog.setContent(orderNodeBuilder.toString());
802             ordersNodeLog.setOrderId(ordersTotal.getId());
803             commonService.insert(OrdersNodeLogMapper.class,ordersNodeLog);
804
805             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账失败,异常原因:"+e.getMessage());
d63b45 806         }
6a4f14 807
374c64 808         data.put("message",message);
Z 809
7b1698 810
d63b45 811
Z 812         return data;
813     }
a24ca9 814
Z 815     @Override
816     public String getHisOrderNo(String hisOrderId, String orderId, SqlSentence sqlSentence, Map<String, Object> paramMap, SyncOrderService syncOrderService, CommonService commonService) {
817         String hisOrderNo="";
818         OrdersTotal ordersTotal=commonService.selectOneByKeyBlob(OrdersTotalMapper.class,orderId);
819         if (ordersTotal != null && StringUtils.noNull(hisOrderId)) {
820             try {
821                 hisOrderNo = SynOrderUtil.getOrderById(hisOrderId, orderId, sqlSentence, paramMap, syncOrderService, commonService);
822             } catch (Exception ex) {
823                 logger.info("查询领建订单号异常:领建订单标识{},预约订单标识:{}",hisOrderId,orderId,ex);
824             }
825         }
826         return hisOrderNo;
823513 827     }
6942c5 828
Z 829
830
831     @Override
832     @Async
833     public void getExecution(Object orderId,User user) {
834         Map<String,Object> map=new HashMap<>();
835         SqlSentence sqlSentence = new SqlSentence();
836         StringBuilder sql = new StringBuilder();
837         sqlSentence.setM(map);
838
839         map.put("orderId",orderId);
840         map.put("type", OrderItemConstants.TYPE_PROJECT);
841         sqlSentence.setSqlSentence(" type=#{m.type} and orderId=#{m.orderId}");
842         int itemCount = commonService.selectCount(OrderItemMapper.class, sqlSentence);
843         int sonCount = commonService.selectCount(OrderItemSonMapper.class, sqlSentence);
844         if(itemCount==0 && sonCount==0){
845             logger.info("异步获取未执行划扣itemId提示:一级子订单符合项目条数:{},二级子订单条数:{}",itemCount,sonCount);
846             return;
847         }
848
849         OrdersTotal ordersTotal=commonService.selectOneByKeyBlob(OrdersTotalMapper.class,orderId);
850         if(ordersTotal==null){
851             logger.info("异步获取未执行划扣itemId提示:根据订单标识未找到订单信息!");
852             return;
853         }
854         if(StringUtils.isEmpty(ordersTotal.getHisOrderId())){
855             logger.info("异步获取未执行划扣itemId提示:该订单没有领建标识!p-his订单标识:{}",ordersTotal.getId());
856             return;
857         }
858
859         sqlSentence.setSqlSentence("SELECT id,commonId,type FROM order_item WHERE orderId=#{m.orderId} ");
860         List<OrderItem> orderItems=commonService.selectList(OrderItemMapper.class,sqlSentence);
861         if(orderItems==null || orderItems.size()==0){
862             logger.info("异步获取未执行划扣itemId提示:根据订单标识未找到一级子订单信息!");
863             return;
864         }
865         List<String> itemIds = orderItems.stream().map(o -> o.getId()).collect(Collectors.toList());
866
867         sqlSentence.setSqlSentence("SELECT id,goodsId,type FROM order_item_source WHERE orderId=#{m.orderId} ");
868         List<OrderItemSon> orderItemSons=commonService.selectList(OrderItemSonMapper.class,sqlSentence);
869         if(orderItemSons!=null && orderItemSons.size()>0){
870             itemIds.addAll(orderItemSons.stream().map(o->o.getId()).collect(Collectors.toList()));
871         }
872
873         sql.append("SELECT id,orderItemId,commonId FROM user_project_item WHERE commonId in( ");
874         SqlSplicingTool.selectBuilderIn(sql,itemIds);
875         sqlSentence.setSqlSentence(sql.toString());
876         List<UserProjectItem> userProjectItems=commonService.selectList(UserProjectItemMapper.class,sqlSentence);
877         if(userProjectItems==null || userProjectItems.size()==0){
878             logger.info("异步获取未执行划扣itemId提示:根据订单的一级子订单标识未找到用户未划扣信息!");
879             return;
880         }
881         Map<String, UserProjectItem> userProjectItemMap = userProjectItems.stream().collect(Collectors.toMap(o -> o.getCommonId(),o->o));
882
883         JSONObject object = new JSONObject();
884         object.put("start", DateUtil.formatDate_3(new Date()));
885         object.put("end",DateUtil.formatDate_3(new Date()));
886         object.put("customerId",user.getApiId());
887         String returnData = ApiPlatformUtil.getExecution(customParameter, object.toJSONString());
888
889         if(StringUtils.noNull(returnData)){
890             JSONObject jsonObject = JSONObject.parseObject(returnData);
891             String code = jsonObject.getString("code");
892             if("100".equals(code)){
893                 JSONObject data = jsonObject.getJSONObject("data");
894                 if(!data.isEmpty()){
895                     JSONArray content = data.getJSONArray("content");
896                     for(int j=0;j<content.size();j++){
897                         JSONObject item = content.getJSONObject(j);
898                         //订单领建标识
899                         String hisOrderId = item.getString("orderId");
900                         if(ordersTotal.getHisOrderId().equals(hisOrderId)){
901                             //未执行划扣itemId
902                             String itemId = item.getString("id");
903                             JSONObject itemSon = item.getJSONObject("item");
904                             if(itemSon!=null){
905                                 //项目领建标识
906                                 String hisProjectId = itemSon.getString("id");
907                                 map.put("hisProjectId",hisProjectId);
908                                 sqlSentence.setSqlSentence("SELECT id FROM project WHERE apiId=#{m.hisProjectId} and isDel=0 ");
909                                 Project project=commonService.selectOne(ProjectMapper.class,sqlSentence);
910                                 if(project!=null){
911                                     for (OrderItem orderItem : orderItems) {
912                                         map.clear();
913                                         map.put("itemId",itemId);
914                                         if(OrderItemConstants.TYPE_PROJECT.equals(orderItem.getType())){
915                                             if(orderItem.getCommonId().equals(project.getId())){
916                                                 UserProjectItem userProjectItem = userProjectItemMap.get(orderItem.getId());
917                                                 if(userProjectItem!=null){
918                                                     map.put("id",userProjectItem.getId());
919                                                     sqlSentence.setSqlSentence(" itemId=#{m.itemId} where id=#{m.id} and isDel=0 ");
920                                                     commonService.updateWhere(UserProjectItemMapper.class,sqlSentence);
921                                                 }
922                                             }
923                                         }else if(OrderItemConstants.TYPE_PROMOTION.equals(orderItem.getType()) || OrderItemConstants.CARD_BAG.equals(orderItem.getType())){
924                                             for (OrderItemSon orderItemSon : orderItemSons) {
925                                                 if(orderItemSon.getGoodsId().equals(project.getId())){
926                                                     UserProjectItem userProjectItem = userProjectItemMap.get(orderItemSon.getId());
927                                                     if(userProjectItem!=null){
928                                                         map.put("id",userProjectItem.getId());
929                                                         sqlSentence.setSqlSentence(" itemId=#{m.itemId} where id=#{m.id} and isDel=0 ");
930                                                         commonService.updateWhere(UserProjectItemMapper.class,sqlSentence);
931                                                     }
932                                                 }
933                                             }
934                                         }
935                                     }
936                                 }else{
937                                     logger.info("异步获取未执行划扣itemId提示:未找到项目信息!领建标识:{}",hisProjectId);
938                                 }
939                             }
940                         }
941
942                     }
943                 }
944             }else{
945                 logger.info("获取卡包标识:根据订单获取卡包信息"+returnData);
946             }
947         }else{
948             logger.info("获取卡包信息操作解析第三方参数为空"+returnData);
949         }
950     }
951
952     @Override
fd269d 953     @Async
6942c5 954     public void sendPublicNo(String  orderId, CommonService commonService) {
Z 955         try {
956             OrdersTotal ordersTotal=commonService.selectOneByKeyBlob(OrdersTotalMapper.class,orderId);
c1d896 957             SqlSentence sqlSentence = new SqlSentence();
Z 958             Map<String,Object> map=new HashMap<>();
959             sqlSentence.setM(map);
960             map.put("isDel",BaseEntity.NO);
961             map.put("orderId",orderId);
962             sqlSentence.setSqlSentence("select * from consume_pay where orderId=#{m.orderId} and isDel=#{m.isDel}");
963             List<ConsumePay> consumePays=commonService.selectList(ConsumePayMapper.class,sqlSentence);
964             sqlSentence.setSqlSentence("select * from coupon_order_discount_log where orderId=#{m.orderId} and isDel=#{m.isDel}");
177066 965             List<CouponOrderDiscountLog> couponOrderDiscountLog=commonService.selectList(CouponOrderDiscountLogMapper.class,sqlSentence);
c1d896 966             String payMethod="";
Z 967             String ln="\r\n";
968             if(consumePays==null ||consumePays.size()==0){
969                 payMethod=payMethod.concat("实付:").concat(ln).concat("1、储值金:0,").concat(ln).concat("2、增值金:0").concat(ln).concat("3、优惠券抵扣:0");
970             }if(consumePays!=null && consumePays.size()>0){
971                 String storedValueFund="0";
972                 String valueAddedFund="0";
973                 String couponDisAmout="0";
974                 for (int i = 0; i < consumePays.size(); i++) {
975                     ConsumePay consumePay = consumePays.get(i);
976                     if(PayMethodTypeConstants.PAY_ADD_FUND.equals(consumePay.getNumberNo())){
977                         valueAddedFund=consumePay.getActualTotal().toString();
978                     }
979                     if(PayMethodTypeConstants.PAY_STORED.equals(consumePay.getNumberNo())){
980                         storedValueFund=consumePay.getActualTotal().toString();
981                     }
982                     if(!(PayMethodTypeConstants.PAY_ADD_FUND.equals(consumePay.getNumberNo()) || PayMethodTypeConstants.PAY_STORED.equals(consumePay.getNumberNo()))){
983                         int num=i+4;
984                         if(i==consumePays.size()-1){
985                             if(PayMethodTypeConstants.PAY_CARD.equals(consumePay.getNumberNo())){
986                                 payMethod=payMethod+num+"、"+consumePay.getName()+":"+"-";
987                             }else{
988                                 payMethod=payMethod+num+"、"+consumePay.getName()+":"+consumePay.getActualTotal();
989                             }
990                         }else {
991                             payMethod=payMethod+num+"、"+consumePay.getName()+":"+consumePay.getActualTotal()+ln;
992                         }
993                     }
994                 }
177066 995                 if(couponOrderDiscountLog!=null && couponOrderDiscountLog.size()>0){
Z 996                     couponDisAmout=couponOrderDiscountLog.stream().collect(Collectors.summingDouble(o->o.getDiscountTotal().doubleValue())).toString();
997 //                    couponDisAmout=couponOrderDiscountLog.getDiscountTotal().toString();
c1d896 998                 }
Z 999                 payMethod="实付:"+ln+String.format("1、储值金: %s "+ln+"2、增值金: %s "+ln+"3、优惠券抵扣: %s "+ln,storedValueFund,valueAddedFund,couponDisAmout).concat(payMethod);
1000             }
6942c5 1001             if(ordersTotal!=null) {
Z 1002                 GzhTemplateVO gzhTemplateVO = new GzhTemplateVO();
1003
1004                 UserUnionHis unionHis = getUserUnionHisByUserId(ordersTotal.getUserId());
1005                 if (unionHis ==null || StringUtils.isEmpty(unionHis.getOpenId())) {
5cf697 1006                     logger.info("结账发送用户公众号消息失败,该用户没有openId,用户标识:{}", ordersTotal.getUserId());
045258 1007                     return;
6942c5 1008                 }
Z 1009                 JSONObject object = new JSONObject();
1010                 JSONObject first = new JSONObject();
c1d896 1011                 first.put("value", "您好,您的订单已付款成功,点击查看明细");
6942c5 1012                 object.put("first", first);
Z 1013
c1d896 1014                 String status = OrderTotalConstants.STATUS_PAY == ordersTotal.getStatus() ? "已支付" : "";
6942c5 1015
Z 1016                 JSONObject keyword1 = new JSONObject();
c1d896 1017                 keyword1.put("value", ordersTotal.getOrderNo());
6942c5 1018                 object.put("keyword1", keyword1);
Z 1019
1020                 JSONObject keyword2 = new JSONObject();
c1d896 1021                 keyword2.put("value", status);
6942c5 1022                 object.put("keyword2", keyword2);
c1d896 1023
Z 1024                 JSONObject keyword3 = new JSONObject();
903388 1025                 // 卡包订单不显示金额
A 1026                 Object shouldTotal;
1027                 if (OrderTotalConstants.TYPE_CARD_BAG.equals(ordersTotal.getType())){
1028                     shouldTotal = "-";
1029                 } else {
36ca20 1030                     // 保留两位小数处理
986118 1031                     DecimalFormat df = new DecimalFormat("#,##0.00");
36ca20 1032                     shouldTotal = df.format(ordersTotal.getShouldTotal());
903388 1033                 }
A 1034                 keyword3.put("value", shouldTotal);
c1d896 1035                 object.put("keyword3", keyword3);
Z 1036
1037                 JSONObject keyword4 = new JSONObject();
1038                 keyword4.put("value", DateUtil.formatDate(ordersTotal.getCreateTime(),"yyyy-MM-dd HH:mm"));
1039                 object.put("keyword4", keyword4);
6942c5 1040
Z 1041                 // remark 备注
1042                 JSONObject remark = new JSONObject();
c1d896 1043                 remark.put("value", payMethod);
6942c5 1044                 object.put("remark", remark);
Z 1045
4b9a7c 1046                 //String url = String.format("/pages/Order_Description/order_payment?hisId=%s", ordersTotal.getId());
W 1047                 //2023-02-06 批量确定订单
1048                 String url = "/packages/order/orderConfirm";
6942c5 1049
Z 1050                 gzhTemplateVO.setTouser(unionHis.getOpenId());
1051                 if(PlatformPattern.PROD.equals(customParameter.getPlatformPattern())){
1052                     gzhTemplateVO.setTemplateId("NWnxYJ_3gNV0OAxtmYWcf5cB12qFMUnLYmqoKFrkp4I");
c1d896 1053 //                    gzhTemplateVO.setTemplateId("5GqBNAWzbln7IlGR0I0SouA8IU8xVciy7w2iLt-zxBI");
6942c5 1054                 }else{
Z 1055                     gzhTemplateVO.setTemplateId("5GqBNAWzbln7IlGR0I0SouA8IU8xVciy7w2iLt-zxBI");
1056                 }
1057                 gzhTemplateVO.setUrl(url);
1058                 gzhTemplateVO.setType(1);
1059                 gzhTemplateVO.setData(object.toJSONString());
1060                 logger.info("请求发送公众号通知方法-打印请求发送公众号通知参数:{}", JSONObject.toJSONString(gzhTemplateVO));
1061                 Result result = sGzhTemplateService.template(gzhTemplateVO);
1062                 logger.info("请求发送公众号通知方法-返回数据:{}", JSONObject.toJSONString(result));
1063                 if (result != null) {
1064                     result.checkTips();
1065                 } else {
1066                     throw new TipsException("请求发送公众号通知方法,返回数据为空!");
1067                 }
1068             }
1069         }catch (Exception e){
1070             logger.error("结账发送用户公众号消息失败",e.getMessage(),e);
e32db7 1071             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账发送用户公众号消息失败!");
fd269d 1072         }
Z 1073     }
1074
1075     @Override
1076     @Async
572fd8 1077     public void sentSMSInfo(String  orderId, CommonService commonService){
A 1078         // 跳转链接
1079         String secondaryItemStr = getSMSUrl();
1080         // 添加定时器任务处理
1081         TimerHandleTool.addTask(commonService, TimerHandleItem.TYPE_ORDER_CONFIRM_SMS_INFO, orderId, secondaryItemStr);
1082     }
1083
1084     /**
1085      * 生成需要发送短信的地址
1086      * @return 返回
1087      */
1088     private String getSMSUrl() {
1089         // 生成小程序链接
1090         String urlLink = null;
1091         // 正式区在拿取链接
1092         if (PlatformPattern.PROD.equals(customParameter.getPlatformPatternMoney())) {
1093             // 获取用户CRM小程序token
1094             ApplyParameter applyParameter = ApplyParameterTool.getMpParameter("wx71e6babac80abcee", commonService);
1095             if (applyParameter == null) {
1096                 throw new PlatTipsException(PlatformCode.ERROR_TIPS, "mpId is error");
1097             }
1098             // 获取范围密钥
1099             SysParameter sysParameter = systemParameterService.getAccessToken(applyParameter.getMpAppId(), applyParameter.getMpSecretKey());
1100             if (sysParameter == null) {
1101                 throw new PlatTipsException(PlatformCode.ERROR_SYSTEM, "服务错误" + SystemCode.ERROR_GET_CORP_TOKEN);
1102             }
1103
1104             // 更换链接 原CRM 1.0 /pages/recharge/incrementInfo
1105             String result = SendSMSTool.getAooLetUrl(sysParameter.getParamValue(), "/packages/order/orderConfirm", "", "release");
1106             if (!StringUtils.isEmpty(result)) {
1107                 JSONObject jsonObject = JSON.parseObject(result);
1108                 if (jsonObject.getInteger("errcode") != 0) {
1109                     throw new PlatTipsException(PlatformCode.ERROR_SYSTEM, "生成短信小程序路径错误:" + jsonObject.getString("msg") + SystemCode.ERROR_GET_CORP_TOKEN);
1110                 }
1111                 urlLink = jsonObject.getString("url_link");
1112             }
1113         } else {
1114             // 测试区跳转百度
1115             urlLink = "https://wxaurl.cn/6666";
1116         }
1117         return urlLink;
1118     }
1119
1120     @Override
1121     @Async
5a9658 1122     public void sendUserConsultant(String userId,String orderNo,String orderId,JSONObject commissionObject, CommonService commonService) {
fd269d 1123         OrdersTotal ordersTotal=commonService.selectOneByKeyBlob(OrdersTotalMapper.class,orderId);
Z 1124         if(ordersTotal!=null){
cd588c 1125             try {
334568 1126                 SqlSentence sqlSentence = new SqlSentence();
Z 1127                 Map<String,Object> map=new HashMap<>();
1128                 sqlSentence.setM(map);
1129                 map.put("orderId",ordersTotal.getId());
1130                 map.put("isDel",BaseEntity.NO);
1131                 sqlSentence.setSqlSentence("select * from orders_info where orderId=#{m.orderId} and isDel=#{m.isDel}");
1132                 OrderInfo orderInfo = commonService.selectOne(OrderInfoMapper.class, sqlSentence);
1133                 if(orderInfo!=null && orderInfo.getIsOldBringNew()==null){
1134                     orderInfo.setIsOldBringNew(BaseEntity.NO);
1135                 }
cd588c 1136                 User user=commonService.selectOneByKeyBlob(UserMapper.class,userId);
Z 1137                 if(user!=null && StringUtils.noNull(user.getHisCorpUserId())){
1138                     Employee employee=commonService.selectOneByKeyBlob(EmployeeMapper.class,user.getHisCorpUserId());
1139                     if(employee!=null && StringUtils.noNull(employee.getUserId())){
1140                         // 企业微信员工标识有更新时推送企业微信消息
1141                         // 获取token
1142                         String at = AppoitmentWeiXinCorpMpUtil.getApplicationAccessToken(customParameter.getCorpAppId(),customParameter.getCorpMpSecret(),commonService);
334568 1143                         if (at != null && orderInfo.getIsOldBringNew()==BaseEntity.YES) {
5a9658 1144                             BigDecimal newMoney=commissionObject.getBigDecimal("beInviterMoney")==null?BigDecimal.ZERO:commissionObject.getBigDecimal("beInviterMoney");
Z 1145                             BigDecimal oldMoney=commissionObject.getBigDecimal("inviterMoney")==null?BigDecimal.ZERO:commissionObject.getBigDecimal("inviterMoney");
1146                             String oldUserName=StringUtils.isEmpty(commissionObject.getString("oldUserName"))?"":commissionObject.getString("oldUserName");
1147                             String newUserNmae=StringUtils.isEmpty(commissionObject.getString("newUserName"))?"":commissionObject.getString("newUserName");
1148                             String sendDate = MessageTemplate.sendIsOldUserConsultant(employee.getUserId(),orderNo, customParameter.getCorpMpAppId(), newMoney,oldMoney,oldUserName,newUserNmae);
1149                             SendMessageTool.sendMessge(sendDate,at);
1150                         }else if(at!=null){
cd588c 1151                             String sendDate = MessageTemplate.sendUserConsultant(employee.getUserId(),orderNo, customParameter.getCorpMpAppId(), user.getName());
Z 1152                             SendMessageTool.sendMessge(sendDate,at);
fd269d 1153                         }
Z 1154                     }else{
c46e95 1155                         throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账成功发送企业微信通知给用户所属顾问,员工找不到userId!");
fd269d 1156                     }
cd588c 1157                 }else{
c46e95 1158                     throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账成功发送企业微信通知给用户所属顾问,用户找不到或者用户所属顾问为空!");
fd269d 1159                 }
cd588c 1160             }catch (Exception e){
a98994 1161                 logger.error("结账成功发送企业微信通知给用户所属顾问消息失败",e);
e32db7 1162                 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账成功发送企业微信通知给用户所属顾问消息失败!");
fd269d 1163             }
Z 1164         }else{
1165             logger.error("结账成功发送企业微信通知给用户所属顾问消息失败,未找到总订单信息!订单标识:{}",orderId);
e32db7 1166             throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账成功发送企业微信通知给用户所属顾问消息失败,未找到总订单信息!");
6942c5 1167         }
Z 1168     }
1169
b0bef0 1170     @Override
314764 1171     public void newMarketingRejectAduit(Integer type,String commonId, Integer commonType, String examEmplId, String examEmplName) {
F 1172         JbpmParamUtil.newMarketingRejectAduit(type,commonId,commonType,examEmplId,examEmplName,commonService);
b0bef0 1173     }
Z 1174
af959d 1175     @Override
314764 1176     public void newMarketingSuccessAduit(Integer type,String commonId, Integer commonType, String examEmplId, String examEmplName) {
F 1177         JbpmParamUtil.newMarketingSuccessAduit(type,commonId,commonType,examEmplId,examEmplName,commonService);
af959d 1178     }
Z 1179
f8f3c5 1180     @Override
c0bd9d 1181     public void statementPerformanceInfo(String orderId) {
Z 1182         logger.info("进入保存报表");
f8f3c5 1183
c0bd9d 1184         //新增收录确认表
Z 1185         PerformanceInfoTool.handOrderPerformanceInfo(commonService,orderId ,BaseEntity.NO);
1186     }
1187
1188     @Override
1189     public void statementConsultantCash(String orderId) {
f8f3c5 1190         //记录咨询师现金业绩报表数据
c0bd9d 1191         ConsultantCashReportTool.handConsultantCash(commonService, orderId);
f8f3c5 1192     }
Z 1193
6942c5 1194     /**
Z 1195      * 获取用户的openId
1196      * @param userId 用户id
1197      * @return 返回
1198      */
1199     private UserUnionHis getUserUnionHisByUserId(String userId){
1200         SqlSentence sqlSentence = new SqlSentence();
1201         Map<String, Object> sqlValue = new HashMap<>();
1202         sqlValue.put("isDel", BaseEntity.NO);
1203         sqlValue.put("userId", userId);
b7f93b 1204         String sql = "SELECT openId from gzh_focus_record WHERE userId = #{m.userId} AND isDel = #{m.isDel} ORDER BY createTime DESC LIMIT 1";
6942c5 1205         sqlSentence.sqlSentence(sql, sqlValue);
Z 1206         return commonService.selectOne(UserUnionHisMapper.class, sqlSentence);
1207     }
386c9d 1208
A 1209     /**
1210      * 订单操作后自动打标签
1211      * @param userId 用户id
1212      */
1213     @Override
1214     public void autoTag(String userId) {
1215         try {
1216             logger.info("处理订单操作后自动打标签, 用户id:{}", userId);
1217             // 创建用户已消费项目标签
c3d8f9 1218             UserLabelTool.builderOrderProjectTag(sUserTagInfoService, commonService, userId);
386c9d 1219         }  catch (Exception ex) {
A 1220             logger.error("处理订单操作后自动打标签失败,用户id:{}", userId, ex);
1221         }
1222     }
98fd5f 1223
F 1224     /** 计算订单应付金额 */
1225     @Override
1226     public Map<String, Object> countOrderShouldTotal(Shop shop, List<OrderItem> orderItemList) {
1227         //总订单订单售价总金额
1228         BigDecimal totalPrice=BigDecimal.ZERO;
1229         //总订单订单原价总金额
1230         BigDecimal oriTotal=BigDecimal.ZERO;
1231         //总订单应付支付总金额
1232         BigDecimal shouldOrderTotal=BigDecimal.ZERO;
1233         //总订单的折扣金额
1234         BigDecimal discountTotal=BigDecimal.ZERO;
1235         //调用处理方法获取计算后的金额信息
e2c918 1236         Map<String, Object> handOrderItemMap = OrderCreateUtil.handOrderItem(null, shop,null, orderItemList, totalPrice, shouldOrderTotal,discountTotal,oriTotal, commonService, systemParameterMapper);
98fd5f 1237         return handOrderItemMap;
F 1238     }
a24ca9 1239 }