From cd969de1f50903ca87deda67bff2d6fcc35b4107 Mon Sep 17 00:00:00 2001
From: zj <1772600164@qq.com>
Date: Sun, 07 Jun 2026 02:42:32 +0800
Subject: [PATCH] 1

---
 src/main/java/com/nq/service/impl/UserServiceImpl.java |  318 ++++++++++++++++++++++++++++++++++++++++------------
 1 files changed, 241 insertions(+), 77 deletions(-)

diff --git a/src/main/java/com/nq/service/impl/UserServiceImpl.java b/src/main/java/com/nq/service/impl/UserServiceImpl.java
index f632221..cd96cf3 100644
--- a/src/main/java/com/nq/service/impl/UserServiceImpl.java
+++ b/src/main/java/com/nq/service/impl/UserServiceImpl.java
@@ -14,6 +14,7 @@
 import com.nq.utils.KeyUtils;
 import com.nq.utils.PropertiesUtil;
 import com.nq.utils.SymmetricCryptoUtil;
+import com.nq.utils.UserFundUtil;
 import com.nq.utils.ip.IpUtils;
 import com.nq.utils.ip.JuheIpApi;
 import com.nq.utils.redis.CookieUtils;
@@ -106,22 +107,24 @@
     IUserService iUserService;
     @Autowired
     UserPositionMapper userPositionMapper;
+    @Autowired
+    UserWithdrawMapper userWithdrawMapper;
 
     @Autowired
     IUserRechargeService userRechargeService;
 
     public ServerResponse reg(String yzmCode, String agentCode, String phone, String userPwd, HttpServletRequest request) {
         if (StringUtils.isBlank(agentCode) || StringUtils.isBlank(phone) ||
-                StringUtils.isBlank(userPwd) || StringUtils.isBlank(yzmCode))
+                StringUtils.isBlank(userPwd))
         {
             return ServerResponse.createByErrorMsg("注册失败, 参数不能为空");
         }
 
 
-        String keys = "AliyunSmsCode:" + phone;
-        String redis_yzm = RedisShardedPoolUtils.get(keys);
-
-        log.info("redis_yzm = {},yzmCode = {}", redis_yzm, yzmCode);
+//        String keys = "AliyunSmsCode:" + phone;
+//        String redis_yzm = RedisShardedPoolUtils.get(keys);
+//
+//        log.info("redis_yzm = {},yzmCode = {}", redis_yzm, yzmCode);
 //        if (!yzmCode.equals(redis_yzm) && !"6666".equals(yzmCode)) {
 //            return ServerResponse.createByErrorMsg("注册失败, 验证码错误");
 //        }
@@ -154,10 +157,19 @@
         user.setIsActive(Integer.valueOf(0));
 
         user.setRegTime(new Date());
-        String uip = IpUtils.getIp(request);
-        user.setRegIp(uip);
-        String uadd = JuheIpApi.ip2Add(uip);
-        user.setRegAddress(uadd);
+//        String uip = IpUtils.getIp(request);
+//        user.setRegIp(uip);
+//        // IP地址查询改为异步处理,避免阻塞注册接口
+//        final String finalUip = uip;
+//        final String finalPhone = phone;
+//        new Thread(() -> {
+//            try {
+//                String uadd = JuheIpApi.ip2Add(finalUip);
+//                log.info("用户注册IP地址查询完成 手机 {} , ip = {} 地址 = {}", finalPhone, finalUip, uadd);
+//            } catch (Exception e) {
+//                log.error("IP地址查询异常", e);
+//            }
+//        }).start();
 
         user.setIsLogin(Integer.valueOf(0));
 
@@ -183,7 +195,7 @@
             String newAgentCode = generateUniqueAgentCode();
             agentUser.setAgentCode(newAgentCode);
             iAgentUserService.updateAgentCode(agentUser);
-            log.info("用户注册成功 手机 {} , ip = {} 地址 = {}", new Object[] { phone, uip, uadd });
+            log.info("用户注册成功 手机 {} , ip = {}", phone, "123123");
             return ServerResponse.createBySuccessMsg("注册成功.请登录");
         }
         return ServerResponse.createBySuccessMsg("注册出错, 请重试");
@@ -229,6 +241,25 @@
         String property = PropertiesUtil.getProperty("user.cookie.name");
 //        System.out.println(property);
         String loginToken = request.getHeader(property);
+        
+        // 如果header中没有token,尝试从cookie获取
+        if (loginToken == null) {
+            javax.servlet.http.Cookie[] cookies = request.getCookies();
+            if (cookies != null) {
+                for (javax.servlet.http.Cookie cookie : cookies) {
+                    if (property != null && property.equals(cookie.getName())) {
+                        loginToken = cookie.getValue();
+                        break;
+                    }
+                }
+            }
+        }
+        
+        // 如果cookie中也没有token,尝试从URL参数获取(用于iframe等场景)
+        if (loginToken == null) {
+            loginToken = request.getParameter("token");
+        }
+        
         if (loginToken == null) {
             return null;
         }
@@ -282,18 +313,11 @@
                 stock.setStockName(stockFutures.getFuturesName());
                 stock.setIsLock(0);
             }
-        } else if(code.contains("sh") || code.contains("sz")){
-         return ServerResponse.createByErrorMsg("添加失败,指数不支持自选");
-//            StockIndex stockIndex = this.stockIndexMapper.selectIndexByCode(stockcode);
-//            if(stockIndex != null){
-//                stock.setId(stockIndex.getId());
-//                stock.setStockCode(stockIndex.getIndexCode());
-//                stock.setStockGid(stockIndex.getIndexGid()+"zs");
-//                stock.setStockName(stockIndex.getIndexName());
-//                stock.setIsLock(0);
-//            }
         } else {
-            stock = this.stockMapper.findStockByCode(code);
+            stock = this.stockMapper.findStockByCode(stockcode);
+            if (stock == null && !code.equals(stockcode)) {
+                stock = this.stockMapper.findStockByCode(code);
+            }
         }
         if (stock == null) {
             return ServerResponse.createByErrorMsg("添加失败,股票不存在");
@@ -366,11 +390,32 @@
         String userJson = RedisShardedPoolUtils.get(loginToken);
         User user = (User)JsonUtil.string2Obj(userJson, User.class);
         User dbuser = this.userMapper.selectByPrimaryKey(user.getId());
-        UserInfoVO userInfoVO = assembleUserInfoVO(dbuser);
+        RedisShardedPoolUtils.setEx(loginToken, JsonUtil.obj2String(dbuser), 9999);
+        UserInfoVO userInfoVO = assembleUserInfoVO(dbuser, true);
 
         return ServerResponse.createBySuccess(userInfoVO);
     }
 
+    @Override
+    public void syncUserCache(HttpServletRequest request) {
+        if (request == null) {
+            return;
+        }
+        String cookieName = PropertiesUtil.getProperty("user.cookie.name");
+        String loginToken = request.getHeader(cookieName);
+        if (StringUtils.isBlank(loginToken)) {
+            return;
+        }
+        String userJson = RedisShardedPoolUtils.get(loginToken);
+        User cached = (User) JsonUtil.string2Obj(userJson, User.class);
+        if (cached == null || cached.getId() == null) {
+            return;
+        }
+        User dbUser = this.userMapper.selectByPrimaryKey(cached.getId());
+        if (dbUser != null) {
+            RedisShardedPoolUtils.setEx(loginToken, JsonUtil.obj2String(dbUser), 9999);
+        }
+    }
 
     public ServerResponse updatePwd(String oldPwd, String newPwd, HttpServletRequest request) {
         if (StringUtils.isBlank(oldPwd) || StringUtils.isBlank(newPwd)) {
@@ -461,6 +506,16 @@
             }
             return ServerResponse.createByErrorMsg("修改失败");
         }
+
+    @Override
+    public void updateSignedContract(Integer userId, String signedContract) {
+        this.userMapper.updateSignedContract(userId,signedContract);
+    }
+    @Override
+    public void updateSignedAgreement(Integer userId, String signedAgreement) {
+        this.userMapper.updateSignedAgreement(userId,signedAgreement);
+    }
+
 
     @Transactional
     @Override
@@ -562,8 +617,8 @@
     }
 
 
-    public ServerResponse auth(String realName, String idCard, String img1key, String img2key, String img3key, HttpServletRequest request) {
-        if (StringUtils.isBlank(realName) || StringUtils.isBlank(idCard)){
+    public ServerResponse auth(String realName, String idCard, String address, String img1key, String img2key, String img3key, HttpServletRequest request) {
+        if (StringUtils.isBlank(realName) || StringUtils.isBlank(idCard) || StringUtils.isBlank(address)){
 //                StringUtils.isBlank(img1key) ||
 //                StringUtils.isBlank(img2key))
             return ServerResponse.createByErrorMsg("参数不能为空");
@@ -582,6 +637,7 @@
         user.setNickName(realName);
         user.setRealName(realName);
         user.setIdCard(idCard);
+        user.setRegAddress(address);
 
         user.setImg1Key(img1key);
         user.setImg2Key(img2key);
@@ -621,7 +677,7 @@
             BigDecimal enableIndexAmt = user.getEnableIndexAmt().add(new BigDecimal(amt.intValue()));
 
             user.setUserAmt(userAmt);
-            user.setEnableAmt(enableAmt);
+            UserFundUtil.debitEnableAndWithdraw(user, new BigDecimal(amt.intValue()));
             user.setUserIndexAmt(userIndexAmt);
             user.setEnableIndexAmt(enableIndexAmt);
             int updateCount = this.userMapper.updateByPrimaryKeySelective(user);
@@ -640,12 +696,11 @@
             }
 
             BigDecimal userAmt = user.getUserAmt().add(new BigDecimal(amt.intValue()));
-            BigDecimal enableAmt = user.getEnableAmt().add(new BigDecimal(amt.intValue()));
             BigDecimal userIndexAmt = user.getUserIndexAmt().subtract(new BigDecimal(amt.intValue()));
             BigDecimal enableIndexAmt = user.getEnableIndexAmt().subtract(new BigDecimal(amt.intValue()));
 
             user.setUserAmt(userAmt);
-            user.setEnableAmt(enableAmt);
+            UserFundUtil.creditEnableAndWithdraw(user, new BigDecimal(amt.intValue()));
             user.setUserIndexAmt(userIndexAmt);
             user.setEnableIndexAmt(enableIndexAmt);
             int updateCount = this.userMapper.updateByPrimaryKeySelective(user);
@@ -664,12 +719,11 @@
             }
 
             BigDecimal userAmt = user.getUserAmt().subtract(new BigDecimal(amt.intValue()));
-            BigDecimal enableAmt = user.getEnableAmt().subtract(new BigDecimal(amt.intValue()));
             BigDecimal userFutAmt = user.getUserFutAmt().add(new BigDecimal(amt.intValue()));
             BigDecimal enableFutAmt = user.getEnableFutAmt().add(new BigDecimal(amt.intValue()));
 
             user.setUserAmt(userAmt);
-            user.setEnableAmt(enableAmt);
+            UserFundUtil.debitEnableAndWithdraw(user, new BigDecimal(amt.intValue()));
             user.setUserFutAmt(userFutAmt);
             user.setEnableFutAmt(enableFutAmt);
             int updateCount = this.userMapper.updateByPrimaryKeySelective(user);
@@ -688,12 +742,11 @@
             }
 
             BigDecimal userAmt = user.getUserAmt().add(new BigDecimal(amt.intValue()));
-            BigDecimal enableAmt = user.getEnableAmt().add(new BigDecimal(amt.intValue()));
             BigDecimal userFutAmt = user.getUserFutAmt().subtract(new BigDecimal(amt.intValue()));
             BigDecimal enableFutAmt = user.getEnableFutAmt().subtract(new BigDecimal(amt.intValue()));
 
             user.setUserAmt(userAmt);
-            user.setEnableAmt(enableAmt);
+            UserFundUtil.creditEnableAndWithdraw(user, new BigDecimal(amt.intValue()));
             user.setUserFutAmt(userFutAmt);
             user.setEnableFutAmt(enableFutAmt);
 
@@ -925,49 +978,82 @@
             BigDecimal enable_user_amt = user.getEnableAmt();
             BigDecimal all_freez_amt = new BigDecimal("0");
             for (UserPosition position : userPositions) {
-//                PositionProfitVO positionProfitVO = iUserPositionService.getPositionProfitVO(position);
-//                if (positionProfitVO == null) {
-//                    continue;
-//                }
-
-                StockListVO stockListVO = new StockListVO();
-                stockListVO=SinaStockApi.assembleLideStockListVO(LiDeDataUtils.getStock(position.getStockCode()));
-                if(org.springframework.util.ObjectUtils.isEmpty(stockListVO)){
-                    stockListVO = SinaStockApi.assembleStockListVO(SinaStockApi.getSinaStock(position.getStockGid()));
-                }
-                if (stockListVO == null) {
+                if (position.getStatus() != null && position.getStatus().intValue() == 0) {
                     continue;
                 }
 
-                if(position.getProfitTargetPrice()!=null && position.getProfitTargetPrice().compareTo(new BigDecimal(stockListVO.getNowPrice())) <= 0 ||position.getStopTargetPrice() != null && position.getStopTargetPrice().compareTo(new BigDecimal(stockListVO.getNowPrice())) >= 0) {
+                StockListVO stockListVO = SinaStockApi.assembleLideStockListVO(LiDeDataUtils.getStock(position.getStockCode()));
+                if(org.springframework.util.ObjectUtils.isEmpty(stockListVO)){
+                    stockListVO = SinaStockApi.assembleStockListVO(SinaStockApi.getSinaStock(position.getStockGid()));
+                }
+                if (stockListVO == null || stockListVO.getNowPrice() == null) {
+                    continue;
+                }
+                BigDecimal nowPrice;
+                try {
+                    nowPrice = new BigDecimal(stockListVO.getNowPrice());
+                } catch (Exception e) {
+                    continue;
+                }
 
-                        try {
-                            this.iUserPositionService.sell(position.getPositionSn(), 0);
-                            SiteTaskLog siteTaskLog = new SiteTaskLog();
-                            siteTaskLog.setTaskType("单股止盈止损强平任务-股票持仓");
-                            String accountType = (user.getAccountType().intValue() == 0) ? "正式用户" : "模拟用户";
-                            String taskcnt = accountType + "-" + user.getRealName() + "被强平[达到目标盈亏] 用户id = " + user.getId() + ", 可用资金 = " + enable_user_amt + "冻结保证金 = " + all_freez_amt + ", 强平比例 = " + force_stop_percent + ",现价"+stockListVO.getNowPrice()+ ", 目标止盈价格:" + position.getProfitTargetPrice()+ ", 目标止损价格:" + position.getStopTargetPrice();
-                            siteTaskLog.setTaskCnt(taskcnt);
-                            String tasktarget = "此次强平订单号为:" + position.getPositionSn();
-                            siteTaskLog.setTaskTarget(tasktarget);
-                            siteTaskLog.setAddTime(new Date());
-                            siteTaskLog.setIsSuccess(Integer.valueOf(0));
-                            siteTaskLog.setErrorMsg("");
-                            int insertTaskCount = this.siteTaskLogMapper.insert(siteTaskLog);
-                            if (insertTaskCount > 0) {
-                                log.info("[盈利达到目标盈利]保存强制平仓task任务成功");
-                            } else {
-                                log.info("[盈利达到目标盈利]保存强制平仓task任务失败");
-                            }
-                        } catch (Exception e) {
-                            log.error("[盈利达到目标盈利]强制平仓失败...");
-                        }
+                if (!shouldForceSellByProfitStop(position, nowPrice)) {
+                    continue;
+                }
 
+                try {
+                    ServerResponse sellResult = this.iUserPositionService.sell(position.getPositionSn(), 0);
+                    if (sellResult != null && !sellResult.isSuccess()) {
+                        log.warn("[止盈止损强平] positionSn={} 失败: {}", position.getPositionSn(), sellResult.getMsg());
+                        continue;
+                    }
+                    SiteTaskLog siteTaskLog = new SiteTaskLog();
+                    siteTaskLog.setTaskType("单股止盈止损强平任务-股票持仓");
+                    String accountType = (user.getAccountType().intValue() == 0) ? "正式用户" : "模拟用户";
+                    String taskcnt = accountType + "-" + user.getRealName() + "被强平[达到目标盈亏] 用户id = " + user.getId() + ", 可用资金 = " + enable_user_amt + "冻结保证金 = " + all_freez_amt + ", 强平比例 = " + force_stop_percent + ",现价"+stockListVO.getNowPrice()+ ", 目标止盈价格:" + position.getProfitTargetPrice()+ ", 目标止损价格:" + position.getStopTargetPrice();
+                    siteTaskLog.setTaskCnt(taskcnt);
+                    String tasktarget = "此次强平订单号为:" + position.getPositionSn();
+                    siteTaskLog.setTaskTarget(tasktarget);
+                    siteTaskLog.setAddTime(new Date());
+                    siteTaskLog.setIsSuccess(Integer.valueOf(0));
+                    siteTaskLog.setErrorMsg("");
+                    int insertTaskCount = this.siteTaskLogMapper.insert(siteTaskLog);
+                    if (insertTaskCount > 0) {
+                        log.info("[盈利达到目标盈利]保存强制平仓task任务成功");
+                    } else {
+                        log.info("[盈利达到目标盈利]保存强制平仓task任务失败");
+                    }
+                } catch (Exception e) {
+                    log.error("[盈利达到目标盈利]强制平仓失败 positionSn={}", position.getPositionSn(), e);
                 }
 
             }
             log.info("=========止盈止损定时任务============");
         }
+    }
+
+    /** 买涨:现价>=止盈 或 现价<=止损;买跌:现价<=止盈 或 现价>=止损 */
+    private boolean shouldForceSellByProfitStop(UserPosition position, BigDecimal nowPrice) {
+        if (position == null || nowPrice == null || nowPrice.compareTo(BigDecimal.ZERO) <= 0) {
+            return false;
+        }
+        BigDecimal profitTarget = position.getProfitTargetPrice();
+        BigDecimal stopTarget = position.getStopTargetPrice();
+        boolean hasProfit = profitTarget != null && profitTarget.compareTo(BigDecimal.ZERO) > 0;
+        boolean hasStop = stopTarget != null && stopTarget.compareTo(BigDecimal.ZERO) > 0;
+        if (!hasProfit && !hasStop) {
+            return false;
+        }
+        boolean isLong = !"买跌".equals(position.getOrderDirection());
+        if (isLong) {
+            if (hasProfit && nowPrice.compareTo(profitTarget) >= 0) {
+                return true;
+            }
+            return hasStop && nowPrice.compareTo(stopTarget) <= 0;
+        }
+        if (hasProfit && nowPrice.compareTo(profitTarget) <= 0) {
+            return true;
+        }
+        return hasStop && nowPrice.compareTo(stopTarget) >= 0;
     }
     /*用户股票持仓单-强平提醒推送消息定时*/
     public void ForceSellMessageTask() {
@@ -1483,18 +1569,30 @@
 
         List<User> users = this.userMapper.listByAdmin(realName, phone, agentId, accountType);
 
-        for(User user:users){
+        List<UserInfoVO> voList = Lists.newArrayListWithCapacity(users.size());
+        for (User user : users) {
             user.setUserPwd("");
+            voList.add(assembleUserInfoVO(user, false));
         }
 
         PageInfo pageInfo = new PageInfo(users);
+        pageInfo.setList(voList);
 
         return ServerResponse.createBySuccess(pageInfo);
     }
 
 
 
-    public ServerResponse findByUserId(Integer userId) { return ServerResponse.createBySuccess(this.userMapper.selectByPrimaryKey(userId)); }
+    public ServerResponse findByUserId(Integer userId) {
+        if (userId == null) {
+            return ServerResponse.createByErrorMsg("用户ID不能为空");
+        }
+        User user = this.userMapper.selectByPrimaryKey(userId);
+        if (user == null) {
+            return ServerResponse.createByErrorMsg("用户不存在");
+        }
+        return ServerResponse.createBySuccess(assembleUserInfoVO(user, false));
+    }
 
 
 
@@ -1545,7 +1643,17 @@
         } else {
             return ServerResponse.createByErrorMsg("不存在此操作");
         }
-        user.setEnableAmt(sh_amt_back);
+        BigDecimal amtDecimal = new BigDecimal(amt);
+        if (direction.intValue() == 0) {
+            UserFundUtil.creditUserBalance(user, amtDecimal);
+        } else if (direction.intValue() == 1) {
+            user.setEnableAmt(sh_amt_back);
+            BigDecimal withdrawAmt = user.getEnaleWithdrawAmt() == null ? BigDecimal.ZERO : user.getEnaleWithdrawAmt();
+            BigDecimal newWithdraw = withdrawAmt.subtract(amtDecimal);
+            user.setEnaleWithdrawAmt(newWithdraw.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : newWithdraw);
+        } else {
+            user.setEnableAmt(sh_amt_back);
+        }
 
 //        BigDecimal hk_amt = user.getHkAmt();
 //
@@ -1753,6 +1861,11 @@
         agentUserListVO.setUserAmt(user.getUserAmt());
         agentUserListVO.setEnableAmt(user.getEnableAmt());
 
+        BigDecimal pendingWithdrawAmt = userWithdrawMapper.sumPendingAmtByUserId(user.getId());
+        BigDecimal resolvedWithdrawAmt = UserFundUtil.resolveWithdrawAmt(
+                user.getEnableAmt(), user.getEnaleWithdrawAmt(), pendingWithdrawAmt);
+        agentUserListVO.setEnaleWithdrawAmt(resolvedWithdrawAmt);
+
         agentUserListVO.setUserIndexAmt(user.getUserIndexAmt());
         agentUserListVO.setEnableIndexAmt(user.getEnableIndexAmt());
 
@@ -1766,6 +1879,21 @@
         BigDecimal allFreezAmt = positionVO.getAllFreezAmt();
         agentUserListVO.setAllProfitAndLose(allProfitAndLose);
         agentUserListVO.setAllFreezAmt(allFreezAmt);
+
+        BigDecimal openBuyFees = BigDecimal.ZERO;
+        List<UserPosition> openPositions = this.iUserPositionService.findPositionByUserIdAndSellIdIsNull(user.getId());
+        if (openPositions != null) {
+            for (UserPosition position : openPositions) {
+                if (position.getOrderFee() != null) {
+                    openBuyFees = openBuyFees.add(position.getOrderFee());
+                }
+            }
+        }
+        BigDecimal enableAmt = user.getEnableAmt() == null ? BigDecimal.ZERO : user.getEnableAmt();
+        BigDecimal freezAmt = allFreezAmt == null ? BigDecimal.ZERO : allFreezAmt;
+        BigDecimal profitAndLose = allProfitAndLose == null ? BigDecimal.ZERO : allProfitAndLose;
+        BigDecimal userAllAmt = enableAmt.add(freezAmt).add(profitAndLose).add(openBuyFees);
+        agentUserListVO.setUserAmt(userAllAmt.setScale(2, RoundingMode.HALF_UP));
 
         BigDecimal forceLine = forcePercent.multiply(allFreezAmt);
         forceLine = forceLine.add(user.getEnableAmt());
@@ -1804,6 +1932,11 @@
     }
 
     private UserInfoVO assembleUserInfoVO(User user) {
+        return assembleUserInfoVO(user, true);
+    }
+
+    /** 与用户端 getUserInfo 一致的账户资产展示 */
+    private UserInfoVO assembleUserInfoVO(User user, boolean persistWithdrawHeal) {
         UserInfoVO userInfoVO = new UserInfoVO();
 
         userInfoVO.setId(user.getId());
@@ -1816,6 +1949,7 @@
         userInfoVO.setAccountType(user.getAccountType());
         userInfoVO.setRecomPhone(user.getRecomPhone());
         userInfoVO.setIsLock(user.getIsLock());
+        userInfoVO.setIsLogin(user.getIsLogin());
         userInfoVO.setRegTime(user.getRegTime());
         userInfoVO.setRegIp(user.getRegIp());
         userInfoVO.setRegAddress(user.getRegAddress());
@@ -1828,24 +1962,44 @@
         userInfoVO.setEnableAmt(user.getEnableAmt());
         userInfoVO.setTradingAmount(user.getTradingAmount());
 
+        BigDecimal pendingWithdrawAmt = userWithdrawMapper.sumPendingAmtByUserId(user.getId());
+        BigDecimal resolvedWithdrawAmt = UserFundUtil.resolveWithdrawAmt(
+                user.getEnableAmt(), user.getEnaleWithdrawAmt(), pendingWithdrawAmt);
+        if (persistWithdrawHeal
+                && (user.getEnaleWithdrawAmt() == null || resolvedWithdrawAmt.compareTo(user.getEnaleWithdrawAmt()) != 0)) {
+            user.setEnaleWithdrawAmt(resolvedWithdrawAmt);
+            this.userMapper.updateByPrimaryKeySelective(user);
+        }
+        userInfoVO.setEnaleWithdrawAmt(resolvedWithdrawAmt);
 
         PositionVO positionVO = this.iUserPositionService.findUserPositionAllProfitAndLose(user.getId());
         userInfoVO.setAllFreezAmt(positionVO.getAllFreezAmt());
         BigDecimal allProfitAndLose = positionVO.getAllProfitAndLose();
         userInfoVO.setAllProfitAndLose(allProfitAndLose);
 
-//        BigDecimal userAllAmt = user.getUserAmt();
-        BigDecimal userAllAmt = user.getEnableAmt();
-        userAllAmt = userAllAmt.add(allProfitAndLose);
-
+        // 账户总资产 = 两融可用 + 冻结保证金 + 浮动盈亏
+        // 浮动盈亏里已扣过买入手续费,而买入手续费下单时已从 enableAmt 扣除,此处加回 openBuyFees 避免总资产「少扣手续费」
+        BigDecimal allFreezAmt = positionVO.getAllFreezAmt() == null ? BigDecimal.ZERO : positionVO.getAllFreezAmt();
+        BigDecimal enableAmt = user.getEnableAmt() == null ? BigDecimal.ZERO : user.getEnableAmt();
+        BigDecimal openBuyFees = BigDecimal.ZERO;
+        List<UserPosition> openPositions = this.iUserPositionService.findPositionByUserIdAndSellIdIsNull(user.getId());
+        if (openPositions != null) {
+            for (UserPosition position : openPositions) {
+                if (position.getOrderFee() != null) {
+                    openBuyFees = openBuyFees.add(position.getOrderFee());
+                }
+            }
+        }
+        BigDecimal userAllAmt = enableAmt.add(allFreezAmt).add(allProfitAndLose).add(openBuyFees);
 
         userInfoVO.setEnableIndexAmt(user.getEnableIndexAmt());
-        userInfoVO.setEnaleWithdrawAmt(user.getEnaleWithdrawAmt());
+        userInfoVO.setIsSignedContract(user.getIsSignedContract());
+        userInfoVO.setIsSignedAgreement(user.getIsSignedAgreement());
         userInfoVO.setHkAmt(user.getHkAmt());
 
         BigDecimal historyProfitLoss = new BigDecimal(0);
         BigDecimal buyAmtAutual = new BigDecimal(0);
-        List<UserPosition> userPositionscc = this.userPositionMapper.findMyPositionByCodeAndSpell(user.getId(), "", "", 0);
+        List<UserPosition> userPositionscc = this.userPositionMapper.findMyPositionByCodeAndSpell(user.getId(), "", "", 1);
 
         if (userPositionscc.size() > 0) {
             for (UserPosition position : userPositionscc) {
@@ -1855,10 +2009,9 @@
             }
         }
         userInfoVO.setBuyAmtAutual(buyAmtAutual);
-        userAllAmt = userAllAmt.add(buyAmtAutual);
-        userInfoVO.setUserAmt(userAllAmt);
+        userInfoVO.setUserAmt(userAllAmt.setScale(2, RoundingMode.HALF_UP));
 
-        List<UserPosition> userPositions = this.userPositionMapper.findMyPositionByCodeAndSpell(user.getId(), "", "", 1);
+        List<UserPosition> userPositions = this.userPositionMapper.findMyPositionByCodeAndSpell(user.getId(), "", "", 2);
 
         if (userPositions.size() > 0) {
             for (UserPosition position : userPositions) {
@@ -2016,7 +2169,18 @@
 
     @Override
     public void updateUserAmt(Double amt, Integer user_id) {
-        userMapper.updateUserAmt(amt, user_id);
+        if (amt == null || user_id == null || amt <= 0) {
+            return;
+        }
+        User user = this.userMapper.selectByPrimaryKey(user_id);
+        if (user == null) {
+            log.error("updateUserAmt 用户不存在 userId={}", user_id);
+            return;
+        }
+        UserFundUtil.creditUserBalance(user, BigDecimal.valueOf(amt));
+        this.userMapper.updateByPrimaryKeySelective(user);
+        log.info("updateUserAmt 充值入账 userId={} amt={} enable={} withdraw={}",
+                user_id, amt, user.getEnableAmt(), user.getEnaleWithdrawAmt());
     }
 
 

--
Gitblit v1.9.3