package com.hx.phip.controller.order; /** * 订单控制器 * * @Author: zhouxiang * @Date: 2022/09/19/11:53 * @Description: */ import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.hx.common.BaseController; import com.hx.common.service.CommonService; import com.hx.mybatisTool.SqlSentence; import com.hx.phiappt.common.*; import com.hx.phiappt.common.PlatformConstants; import com.hx.phiappt.constants.tool.ConsultantCashReportTool; import com.hx.phiappt.constants.tool.PerformanceInfoTool; import com.hx.phiappt.constants.tool.UserStatusTool; import com.hx.phiappt.dao.mapper.CouponNumberMapper; import com.hx.phiappt.model.*; import com.hx.phiappt.model.coupon.Coupon; import com.hx.phiappt.model.coupon.CouponNumber; import com.hx.phiappt.model.order.*; import com.hx.phiappt.model.performance.PerformanceInfo; import com.hx.phiappt.model.userStatus.UserStatusLog; import com.hx.phip.config.CustomParameter; import com.hx.phip.dao.mapper.*; import com.hx.phip.service.ShopService; import com.hx.phip.service.UserMoneyService; import com.hx.phip.service.UserService; import com.hx.phip.service.order.OrderService; import com.hx.phip.service.order.OrderServiceV2; import com.hx.phip.util.api.*; import com.hx.util.StringUtils; import com.hz.his.dto.order.OrderPHisDto; import com.hz.his.dto.order.PayDto; import com.hz.his.feign.service.sync.SyncOrderService; import com.platform.constants.LoginConstant; import com.platform.entity.ThirtApplication; import com.platform.exception.PlatTipsException; import com.platform.resultTool.PlatformCode; import com.platform.resultTool.PlatformResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.math.BigDecimal; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 订单控制器 * @USER: zhouxiang * @DATE: 2021/12/03 */ @RestController @RequestMapping("/order") public class OrderControllerV2 extends BaseController { //log4j日志 private static Logger logger = LoggerFactory.getLogger(OrderControllerV2.class.getName()); // 固定线程池 //ExecutorService threadPool = Executors.newFixedThreadPool(10); //订单类型集合(充值,转增充值) private static List orderTypeList= Arrays.asList(OrderTotalConstants.TYPE_RECHARGE,OrderTotalConstants.TYPE_TURN_RECHARGE); @Resource private OrderServiceV2 orderServiceV2; @Resource private OrderService orderService; @Resource private ShopService shopService; @Resource private UserMoneyService userMoneyService; @Resource private CustomParameter customParameter; @Resource private UserService userService; @Resource private SyncOrderService syncOrderService; /** * 开单接口 */ @RequestMapping(value = "/create",method = RequestMethod.POST) public PlatformResult orderCreate(HttpServletRequest request, @RequestBody OrderPHisDto dto) { //校验请求参数是否为空 if(dto==null){ throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"请传订单参数"); } //校验签名 ThirtApplication thirtApplication= (ThirtApplication) request.getSession().getAttribute(LoginConstant.LOGIN_APPLY); if(thirtApplication==null){ throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"签名失败,请检查签名!"); } //打印请求参数 logger.info("前打印新开单接口请求所有参数:{}", JSONObject.toJSONString(dto)); //解析请求参数,并校验参数必填值,赋予默认值等操作 JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(dto)); //解析总订单对象 OrdersTotal orderTotal = JSONObject.parseObject(object.getString("orderTotal"), OrdersTotal.class); //校验总订单参数 orderTotal = OrderCreateUtil.checkOrderTotalParam(orderTotal); //获取订单的子订单 List orderItem = JSONObject.parseArray(object.getString("orderItem"), OrderItem.class); //校验子订单参数 orderItem=OrderCreateUtil.checkOrderItem(orderItem,orderTotal.getType()); //获取开发人员集合 List orderDeveloperList = JSONObject.parseArray(object.getString("orderDeveloper"), OrderDeveloper.class); //操作人id,没有默认填订单用户标识 String operatorId = StringUtils.isEmpty(object.getString("operatorId"))?orderTotal.getUserId():object.getString("operatorId"); //操作类型,0:草稿 1:创建订单 2:创建订单+结账(目前结账和创建是分开的),默认1 Integer type =object.getInteger("type")==null?1:object.getInteger("type"); //获取操作人门店标识 String shopId = object.getString("shopId");//操作人的门店id //查询需求要的信息,并且判空(例如查询门店、用户、用户资金等信息) //查询操作人门店信息 Shop shop = shopService.selectOneByKey(shopId); if(shop==null){ throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到门店信息,操作人门店标识:{}",shopId); } //获取用户资金信息,用于订单快照存储用户资金信息 UserMoney userMoney = userMoneyService.selectUserId(orderTotal.getUserId()); if(userMoney==null){ throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找用户资金信息,订单用户标识:{}"+orderTotal.getUserId()); } //获取用户信息 User user = commonService.selectOneByKey(UserMapper.class,orderTotal.getUserId()); if(user==null){ throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找用户信息,订单用户标识:{}"+orderTotal.getUserId()); } //获取订单销售平台信息 PlatformApplication platformApplication = OrderCreateUtil.getPlatformApplication(orderTotal, commonService); //获取操作人信息 Map operator = ApiOrderUtil.getOperator(commonService, operatorId); //默认总订单参数 OrderCreateUtil.setDefaultOrderTotal(orderTotal,thirtApplication.getAppId(),thirtApplication.getAppIdCode(),user,commonService); //执行开单方法 Map map = orderServiceV2.orderCreate(orderTotal, orderItem, type, orderDeveloperList, operator, shop,userMoney,user,platformApplication,commonService); //返回phis订单号、phis订单id return PlatformResult.success(map); } /** * 结账 */ @RequestMapping(value = "/payMoney",method = RequestMethod.POST) public synchronized PlatformResult orderPayMoney(HttpServletRequest request,@RequestBody PayDto dto) { //校验请求参数是否为空 if(dto==null){ throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"请传订单参数"); } //校验签名 ThirtApplication thirtApplication= (ThirtApplication) request.getSession().getAttribute(LoginConstant.LOGIN_APPLY); if(thirtApplication==null){ throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"签名失败,请检查签名!"); } //打印请求参数 logger.info("前打印新结账订单请求所有参数:{}",JSONObject.toJSONString(dto)); //解析请求参数,并校验参数必填值,赋予默认值等操作 JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(dto)); //是否是按项目付款,0:否,1:是 Integer type = object.getInteger("type"); //订单id String orderId = object.getString("orderId"); //应付的总金额 String total = object.getString("total"); //用户真正支付的金额集合 JSONArray amountList = object.getJSONArray("amount"); //操作人员id String operatorId = object.getString("operatorId"); //优惠券id集合 JSONArray userCouponIds = new JSONArray(); String userCouponId = object.getString("userCouponId"); JSONArray couponIds = object.getJSONArray("userCouponIds"); if(StringUtils.noNull(userCouponId)){ userCouponIds.add(userCouponId); } if(couponIds!=null && couponIds.size()>0){ userCouponIds.addAll(couponIds); } //查询需求要的信息,并且判空(例如查询门店、订单信息、一级子订单、用户资金等信息) OrdersTotal ordersTotal=commonService.selectOneByKeyBlob(OrdersTotalMapper.class,orderId); User user = userService.selectOneByKey(ordersTotal.getUserId()); UserMoney userMoney=userMoneyService.selectUserId(ordersTotal.getUserId()); Shop shop = shopService.selectOneByKey(ordersTotal.getDeveloperShopId()); //判断订单状态是否正确 if(OrderTotalConstants.STATUS_WAIT_PAY!=ordersTotal.getStatus()){ throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单总状态不正确,只有待支付才能进行结账!"); } SqlSentence sqlSentence = new SqlSentence(); Map objectMap=new HashMap<>(); sqlSentence.setM(objectMap); objectMap.put("id",orderId); //获取订单其他信息(orderInfo) sqlSentence.setSqlSentence("SELECT * FROM orders_info where orderId=#{m.id}"); OrderInfo info = commonService.selectOne(OrderInfoMapper.class,sqlSentence); //获取一级子订单信息,注意:充值和转增充值订单没有一级子订单集合 sqlSentence.setSqlSentence("select * from order_item where isDel=0 and orderId=#{m.id}"); List orderItemList=commonService.selectList(OrderItemMapper.class,sqlSentence); //获取操作人信息map Map operator = ApiOrderUtil.getOperator(commonService, operatorId); //判断优惠券叠加使用,项目券或者现金券+生日券 if(userCouponIds!=null && userCouponIds.size()>0){ checkCoupon(userCouponIds,commonService); } //判断是否非空,订单、用户、用户资金、门店、订单其他信息(orderInfo)、订单标识、应付总金额、用户支付金额、操作人标识信息是否为空 checkIsNull(ordersTotal, user, userMoney, shop,info,orderItemList,orderId,total,amountList,operatorId); ordersTotal.setOrderInfo(info); //收银员id String cashier = object.getString("cashier"); if(PlatformConstants.TYPE_PLATFORM_CRM.equals(ordersTotal.getAppIdCode())){ cashier=ordersTotal.getUserId(); } if(StringUtils.noNull(cashier)){ Employee employee=commonService.selectOneByKeyBlob(EmployeeMapper.class,cashier); if(employee!=null){ ordersTotal.setCashierId(employee.getId()); ordersTotal.setCashierName(StringUtils.isEmpty(employee.getCnName())?"":employee.getCnName()); }else{ User cashierUser=commonService.selectOneByKeyBlob(UserMapper.class,cashier); if(cashierUser!=null){ ordersTotal.setCashierId(cashierUser.getId()); ordersTotal.setCashierName(StringUtils.isEmpty(cashierUser.getName())?"":cashierUser.getName()); } } } //收银员门店 String cashierShopId = object.getString("cashierShopId"); if(PlatformConstants.TYPE_PLATFORM_CRM.equals(ordersTotal.getAppIdCode())){ cashierShopId=ordersTotal.getDeveloperShopId(); } if(StringUtils.noNull(cashierShopId)){ Shop cashierShop=commonService.selectOneByKeyBlob(ShopMapper.class,cashierShopId); if(cashierShop!=null){ ordersTotal.setCashierShopId(cashierShop.getId()); ordersTotal.setCashierShopName(StringUtils.isEmpty(cashierShop.getName())?"":cashierShop.getName()); } } User payUser = null; //支付用户 if(StringUtils.noNull(dto.getPayUserId())){ payUser = userService.selectOneByKey(dto.getPayUserId()); if(payUser == null){ throw new PlatTipsException(PlatformCode.ERROR_TIPS,"支付人标识错误!"); } } if(payUser == null){ payUser = user; } //执行结账方法 Map map = orderServiceV2.orderPayMoney(type, ordersTotal,user,payUser,shop,info,orderItemList,operator,userMoney,total, amountList,userCouponIds,null); if(map!=null && map.containsKey("orderId")){ OrdersTotal sucOrdersTotal=commonService.selectOneByKey(OrdersTotalMapper.class,map.get("orderId")); if(OrderTotalConstants.PAY_STATUS_SUC==sucOrdersTotal.getPayStatus()){ //处理老带新 JSONObject commissionObject = handOrderOldNew(amountList, ordersTotal, user, map); //更新用户最后下单时间 updateUserLastTime(ordersTotal, user); //需求: 1.HIS助手结账成功:要通知客户所属顾问,发送企业微信通知 ,如果没有所属顾问发送给门店运营客服(三少说目前不处理crm已处理) -异步 try { orderServiceV2.sendUserConsultant(ordersTotal.getUserId(),ordersTotal.getOrderNo(),ordersTotal.getId(),commissionObject,commonService); }catch (Exception e){ logger.info("要通知客户所属顾问,发送企业微信通知异常 -异步:{}",e.getMessage(),e); } //记录收入确认表 try{ orderServiceV2.statementPerformanceInfo((String) map.get("orderId")); }catch (Exception e) { logger.info("记录收入确认表,异常:{}", e.getMessage(), e); // 添加错误日志 PerformanceInfoTool.addErrorLog(commonService, map.get("orderId").toString(), PerformanceInfo.ASSOCIATION_TYPE_GOODS_ORDER, e.getMessage()); } //咨询师现金业绩报表 try{ orderServiceV2.statementConsultantCash((String) map.get("orderId")); }catch (Exception e){ logger.info("咨询师现金业绩报表,异常:{}",e.getMessage(),e); } } //异步获取未执行划扣信息,测试环境先放开,荣爷说,记得写重发 // if(user!=null && StringUtils.noNull(user.getApiId())){ // try { // orderService.getExecution(map.get("orderId"),user); // }catch (Exception e){ // logger.info("异步获取未执行划扣信信失败!订单标识:{},用户信息:{}",map.get("orderId"),JSONObject.toJSONString(user)); // } // } //获取领建订单号 // if(map.containsKey("hisOrderId")){ // try { // Map paramMap=new HashMap<>(); // sqlSentence.setM(paramMap); // paramMap.put("orderId",map.get("orderId")); // paramMap.put("isDel",BaseEntity.NO); // String hisOrderId = orderService.getHisOrderId((String) map.get("hisOrderId"), (String) map.get("orderId"), sqlSentence, paramMap, syncOrderService, commonService); // map.put("hisOrderNo", hisOrderId); // }catch (Exception e){ // logger.info("获取领建订单号失败!订单标识:{}",map.get("orderId")); // } // } // OrdersTotal orderSum=commonService.selectOneByKey(OrdersTotalMapper.class,map.get("orderId")); // if(orderSum!=null && StringUtils.noNull(orderSum.getHisOrderId())){ // //同步卡包标识,暂时由同步中心处理,以后切掉领建由预约处理新增卡包 // if(StringUtils.isEmpty(ordersTotal.getKoapOrderId())){ // SynOrderUtil.synGetUserCard(orderSum,customParameter,commonService); // } // } //根据订单用户标识同步当前用户所有未执行划扣数据,弃用 // if(user!=null && StringUtils.noNull(user.getApiId())){ // JSONObject data = new JSONObject(); // data.put("endTime", DateUtil.formatDate_3(new Date())); // data.put("startTime",DateUtil.formatDate_3(new Date())); // data.put("customerId",user.getApiId()); // ApiPlatformUtil.sysnExecution(customParameter,data.toJSONString()); // } } // //优惠券id 单张使用优惠券废弃 // String userCouponId = object.getString("userCouponId"); // //查询优惠券信息 // if(StringUtils.noNull(userCouponId)){ // //查看用户是否有优惠券 // couponNumber = commonService.selectOneByKey(CouponNumberMapper.class, userCouponId); // if(couponNumber==null){ // throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠卷:该用户没有该优惠券"); // } // //查看用户是否有优惠券 // coupon = commonService.selectOneByKey(CouponMapper.class, couponNumber.getCouponId()); // if(coupon==null){ // throw new PlatTipsException(PlatformCode.ERROR_TIPS,"优惠卷:未找到优惠券信息"); // } // } // //结账成功发送公众号通知给用户 // threadPool.execute(() -> orderServiceV2.sendPublicNo(ordersTotal.getId(),commonService)); // //需求: 1.HIS助手结账成功:要通知客户所属顾问,发送企业微信通知 // threadPool.execute(() -> orderService.sendUserConsultant(ordersTotal.getUserId(),ordersTotal.getOrderNo(),ordersTotal.getId(),commonService)); //返回phis订单号、phis订单id、领建订单号、领建订单id return PlatformResult.success(map); } /** * 结账判断是否为空 * @param ordersTotal 总订单标识 * @param user 用户信息 * @param userMoney 用户资金 * @param shop 门店信息 * @param info 订单其他信息(orderInfo) * @param orderItemList 一级子订单集合 * @param orderId 订单标识 * @param total 应付总金额 * @param amountList 用户支付集合 * @param operatorId 操作人标识 */ private void checkIsNull(OrdersTotal ordersTotal, User user, UserMoney userMoney, Shop shop,OrderInfo info,List orderItemList, String orderId,String total,JSONArray amountList,String operatorId) { if(StringUtils.isEmpty(orderId)){ throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"请传订单id"); } if(StringUtils.isEmpty(total)){ throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"请传应付的总金额"); } if(amountList ==null || amountList.size()==0){ throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"请传用户真实付款金额"); } if(StringUtils.isEmpty(operatorId)){ throw new PlatTipsException(PlatformCode.ERROR_PARAMETER_NULL,"请传用户操作人标识"); } if(ordersTotal!=null){ // //同步用户资金信息 // UserMoneyUtil.syncHisUserMoney(commonService,customParameter,ordersTotal.getUserId()); }else{ throw new PlatTipsException(PlatformCode.ERROR_TIPS,"订单不存在"); } if(user==null){ throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账:未找到该用户信息"); } if(userMoney ==null ){ //没有用户资金信息,抛错,资金全部交给用户资金全权处理 throw new PlatTipsException(PlatformCode.ERROR_TIPS,"未找到用户资金信息!"); } if(shop==null){ throw new PlatTipsException(PlatformCode.ERROR_TIPS,"结账时:订单门店不存在"); } if(info==null){ throw new PlatTipsException(PlatformCode.ERROR_TIPS,"根据总订单未找到订单其他信息"); } if(!orderTypeList.contains(ordersTotal.getType()) && (orderItemList ==null || orderItemList.size()==0)){ throw new PlatTipsException(PlatformCode.ERROR_TIPS,"没有对应的子订单"); } } /** * 检查优惠券是否符合一张项目券或者一张现金券+生日优惠券 * 判断思路说明: * 1、只要统计用户使用优惠券集合的项目券或者现金券的张数 * 2、如果项目或者现金券大于1张肯定是不给使用的 * 3、如果都没有项目券或者现金券,代表专门使用生日优惠券,生日优惠券不进行判断限制,无限使用 @param userCouponIds */ public static void checkCoupon(JSONArray userCouponIds, CommonService commonService) { CouponNumber couponNumber=null; Coupon coupon=null; //统计项目券张数 Integer projectCoupon=0; //统计现金券张数 Integer cashCoupon=0; for(int i=0;i1){ throw new PlatTipsException(PlatformCode.ERROR_TIPS,"叠加优惠卷提示:一张订单只能使用一张现金券"); } if(projectCoupon>1){ throw new PlatTipsException(PlatformCode.ERROR_TIPS,"叠加优惠卷提示:一张订单只能使用一张项目券"); } } /** * 更新用户最后一次下单时间 * @param ordersTotal * @param user */ public void updateUserLastTime(OrdersTotal ordersTotal, User user) { try { SqlSentence sqlSentence = new SqlSentence(); Map sqlValues = new HashMap<>(); sqlValues.put("lastPayOrderTime", new Date()); sqlValues.put("editTime", new Date()); sqlValues.put("isLoss", BaseEntity.NO); sqlValues.put("isDel", BaseEntity.NO); sqlValues.put("id", user.getId()); StringBuilder sql = new StringBuilder(); sql.append(" lastPayOrderTime=#{m.lastPayOrderTime},editTime=#{m.editTime},isLoss=#{m.isLoss}"); // 会员有消费和执行就是活跃会员 String status = null; if (!UserStatusConstants.USER_STATUS_NON_MEMBER.equals(user.getUserStatus())) { status = UserStatusConstants.USER_STATUS_ACTIVE_MEMBER; sqlValues.put("userStatus", status); sql.append(",userStatus=#{m.userStatus}"); } sql.append(" WHERE id=#{m.id} AND isDel=#{m.isDel}"); sqlSentence.sqlSentence(sql.toString(), sqlValues); commonService.updateWhere(UserMapper.class, sqlSentence); // 添加调整用户状态日志 调整了用户等级在写入日志 if (!StringUtils.isEmpty(status)) { UserStatusTool.addUserStatusLog(commonService, user, UserStatusLog.CHANGE_STATUS_TYPE_ORDER, ordersTotal.getId(), UserStatusConstants.USER_STATUS_ACTIVE_MEMBER); } } catch (Exception e) { logger.info("更新用户最后下单时间,异常:{}", e.getMessage(), e); } } /** * 处理老带新 * @param amountList * @param ordersTotal * @param user * @param map * @return */ private JSONObject handOrderOldNew(JSONArray amountList, OrdersTotal ordersTotal, User user, Map map) { /** * 处理老带新(禅道为准,禅道号176) * 1.准会员、普卡、银卡: * 邀请人增值金百分比:8% * 被邀请人增值金百分比:2% * 2.金卡、钻卡、黑卡: * 邀请人增值金百分比:10% * 被邀请人增值金百分比:5% */ SqlSentence sql = new SqlSentence(); Map paramMap=new HashMap<>(); sql.setM(paramMap); JSONObject commissionObject =new JSONObject(); JSONArray hisPayList=new JSONArray(); StringBuilder orderNodeBuilder = new StringBuilder(); if(ordersTotal.getOrderInfo().getIsOldBringNew() !=null && ordersTotal.getOrderInfo().getIsOldBringNew()== BaseEntity.YES){ JSONObject hisPay ; for(int i=0;i