1
zj
2026-01-14 afb9b1cefb1c2d2f57fe8f0f3c19efa354669c66
src/main/java/com/nq/service/impl/UserServiceImpl.java
@@ -1,19 +1,21 @@
package com.nq.service.impl;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.nq.common.ServerResponse;
import com.nq.config.StockPoll;
import com.nq.dao.*;
import com.nq.enums.EConfigKey;
import com.nq.enums.EStockType;
import com.nq.enums.EUserAssets;
import com.nq.pojo.*;
import com.nq.pojo.reponse.RUserAssets;
import com.nq.service.*;
import com.nq.utils.timeutil.DateTimeUtil;
import com.nq.utils.UserPointUtil;
import com.nq.utils.PropertiesUtil;
import com.nq.utils.SymmetricCryptoUtil;
import com.nq.utils.ip.IpUtils;
@@ -21,24 +23,22 @@
import com.nq.utils.redis.CookieUtils;
import com.nq.utils.redis.JsonUtil;
import com.nq.utils.redis.RedisShardedPoolUtils;
import com.nq.utils.stock.sina.StockApi;
import com.nq.vo.agent.AgentUserListVO;
import com.nq.vo.futuresposition.FuturesPositionVO;
import com.nq.vo.indexposition.IndexPositionVO;
import com.nq.vo.position.PositionProfitVO;
import com.nq.vo.position.PositionVO;
import com.nq.vo.stock.StockListVO;
import com.nq.vo.position.UserPositionVO;
import com.nq.vo.user.UserInfoVO;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.nq.vo.user.UserOut;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -62,6 +62,9 @@
    @Resource
    StockOptionMapper stockOptionMapper;
    @Autowired
    DkMapper dkMapper;
    @Autowired
    IUserService userService;
@@ -76,8 +79,6 @@
    StockMapper stockMapper;
    @Autowired
    IUserPositionService iUserPositionService;
    @Autowired
    IUserBankService iUserBankService;
    @Resource
    AgentUserMapper agentUserMapper;
    @Resource
@@ -96,31 +97,34 @@
    IUserIndexPositionService iUserIndexPositionService;
    @Autowired
    ISiteIndexSettingService iSiteIndexSettingService;
    @Autowired
    StockPoll stockPoll;
    @Autowired
    StockSubscribeMapper stockSubscribeMapper;
    @Resource
    MoneyLogMapper mapper;
    @Resource
    IUserPositionService userPositionService;
    @Resource
    SiteAmtTransLogMapper siteAmtTransLogMapper;
    @Autowired
    IUserFuturesPositionService iUserFuturesPositionService;
    @Autowired
    ISiteFuturesSettingService iSiteFuturesSettingService;
    @Autowired
    IStockFuturesService iStockFuturesService;
    @Autowired
    ISiteMessageService iSiteMessageService;
    @Autowired
    private ApplyLeverMapper applyLeverMapper;
    @Autowired
    private UserPositionMapper userPositionMapper;
    @Autowired
    IPriceServices priceServices;
    @Autowired
    IUserService iUserService;
    @Autowired
    IStockConfigServices iStockConfigServices;
    public ServerResponse reg(String yzmCode, String agentCode, String phone, String userPwd, HttpServletRequest request) {
@@ -162,7 +166,7 @@
        user.setAccountType(Integer.valueOf(0));
        user.setIsLock(Integer.valueOf(1));
        user.setIsLock(Integer.valueOf(0));
        user.setIsActive(Integer.valueOf(0));
        user.setRegTime(new Date());
@@ -172,7 +176,7 @@
        user.setRegAddress(uadd);
        user.setIsLogin(Integer.valueOf(0));
        user.setRealType(0);
        int insertCount = this.userMapper.insert(user);
        if (insertCount > 0) {
@@ -193,7 +197,8 @@
            if (user.getIsLogin().intValue() == 1) {
                return ServerResponse.createByErrorMsg("登录失败。账户锁定",request);
            }
            userAssetsServices.assetsByTypeAndUserId(EStockType.IN.getCode(),user.getId());
            //新增账号资产
            userAssetsServices.addUserAssetsListByUserId(user.getId());
            this.iSiteLoginLogService.saveLog(user, request);
            return ServerResponse.createBySuccess(user);
        }
@@ -390,7 +395,7 @@
    }
    public ServerResponse auth(String realName, String idCard, String vaildNumber, String img1key, String img2key, String img3key, HttpServletRequest request) {
    public ServerResponse auth(String realName, String idCard, Integer realType, String vaildNumber, String img1key, String img2key, String img3key, HttpServletRequest request) {
        if (StringUtils.isBlank(realName) ||
                StringUtils.isBlank(idCard)) {
@@ -408,6 +413,7 @@
        user.setRealName(realName);
        user.setIdCard(idCard);
        user.setVaildNumber(vaildNumber);
        user.setRealType(realType);
        user.setIsActive(Integer.valueOf(1));
@@ -491,9 +497,10 @@
            RUserAssets rUserAssets  = new RUserAssets();
            UserAssets userAssets = userAssetsList.get(i);
            // 浮动盈亏
            BigDecimal profitAndLose = userAssets.getProfitAndLoss();
            String profitAndLose = getProfitAndLose(userId, userAssets.getAccectType()).toString();
            BigDecimal amt = userAssets.getAvailableBalance();
            BigDecimal totalAssets = userAssets.getAvailableBalance().add(userAssets.getFreezeMoney());
            BigDecimal totalAssets = userAssets.getAvailableBalance().add(userAssets.getFreezeMoney()).add(new BigDecimal(profitAndLose)).subtract(userAssets.getHandlingChargeWritten());
//            BigDecimal totalAssets = userAssets.getAvailableBalance().add(userAssets.getFreezeMoney()).subtract(userAssets.getCumulativeProfitAndLoss()).add(profitAndLose);
            BigDecimal freeMoney = userAssets.getFreezeMoney();
            BigDecimal hMoney = userAssets.getHandlingCharge();
            BigDecimal hProfitAndLose = userAssets.getCumulativeProfitAndLoss();
@@ -505,7 +512,9 @@
            rUserAssets.setCumulativeProfitAndLoss(hProfitAndLose.toString());
            rUserAssets.setHandlingCharge(hMoney.toString());
            rUserAssets.setProfitAndLoss(profitAndLose.toString());
            rUserAssets.setIsZf(userAssets.getIsZf());
            rUserAssets.setAmountToBeCovered((userAssets.getAmountToBeCovered().add(userAssets.getHandlingChargeWritten()).toString()));
            rUserAssets.setHandlingChargeWritten(userAssets.getHandlingChargeWritten());
            BigDecimal rate = rateServices.currencyRate(
                    EStockType.getEStockTypeByCode(userAssets.getAccectType()),EStockType.US);
@@ -533,9 +542,9 @@
            if(hMoney.compareTo(BigDecimal.ZERO)>0){
                handlingChargeUSD  =hMoney.multiply(rate);
            }
            BigDecimal  profitAndLossUSD = profitAndLose;
            if(profitAndLose.compareTo(BigDecimal.ZERO)>0){
                profitAndLossUSD  =profitAndLose.multiply(rate);
            BigDecimal  profitAndLossUSD = new BigDecimal(profitAndLose);
            if(new BigDecimal(profitAndLose).compareTo(BigDecimal.ZERO)>0){
                profitAndLossUSD  =new BigDecimal(profitAndLose).multiply(rate);
            }
@@ -548,7 +557,9 @@
            rUserAssets.setCumulativeProfitAndLossUSD(cumulativeProfitAndLossUSD.setScale(s,BigDecimal.ROUND_UP).toString());
            rUserAssets.setHandlingChargeUSD(handlingChargeUSD.setScale(s,BigDecimal.ROUND_UP).toString());
            rUserAssets.setProfitAndLossUSD(profitAndLossUSD.setScale(s,BigDecimal.ROUND_UP).toString());
            rUserAssets.setProfitAndLoss(profitAndLose);
//            BigDecimal decimal = new BigDecimal(rUserAssets.getTotalMoney()).add(new BigDecimal(rUserAssets.getProfitAndLoss()));
//            rUserAssets.setTotalMoney(decimal.toString());
            AllProfitAndLose = AllProfitAndLose.add(profitAndLossUSD);
            allTotalAssets = allTotalAssets.add(totleMoneyUSD);
            allAmt = allAmt.add(availableBalanceUSD);
@@ -559,14 +570,13 @@
            rUserAssetsList.add(rUserAssets);
        }
        RUserAssets rUserAssets  = new RUserAssets();
        /*RUserAssets rUserAssets  = new RUserAssets();
        rUserAssets.setAccectType("ALL");
        rUserAssets.setProfitAndLoss(AllProfitAndLose.setScale(s,BigDecimal.ROUND_DOWN).toString());
        rUserAssets.setProfitAndLossUSD(AllProfitAndLose.setScale(s,BigDecimal.ROUND_DOWN).toString());
@@ -582,23 +592,74 @@
        rUserAssets.setFreezeMoneyUSD(allFreeMoney.setScale(s,BigDecimal.ROUND_DOWN).toString());
        rUserAssets.setSymbol("$");
        rUserAssets.setSymbolCode("USD");
        rUserAssetsList.add(rUserAssets);
        rUserAssetsList.add(rUserAssets);*/
        return ServerResponse.createBySuccess(rUserAssetsList);
    }
    public BigDecimal getProfitAndLose(Integer userId, String accectType){
        List<UserPosition> userPositions;
        userPositions = userPositionMapper.findMyPositionByCodeAndSpell(userId,
                        "","",
                        0, accectType);
        List<UserPositionVO> userPositionVOS = Lists.newArrayList();
        if (userPositions.size() > 0) {
            for (UserPosition position : userPositions) {
                UserPositionVO userPositionVO = UserPointUtil.assembleUserPositionVO(position,priceServices.getNowPrice(position.getStockCode()));
                StockSubscribe stockSubscribe = stockSubscribeMapper.selectOne(new LambdaQueryWrapper<StockSubscribe>()
                        .eq(StockSubscribe::getCode, userPositionVO.getStockCode()));
                if(position.getSellOrderId() == null){
                    if (null != stockSubscribe && DateUtil.date().before(stockSubscribe.getListDate())) {
                        userPositionVO.setProfitAndLose(BigDecimal.ZERO);
                    }else{
                        userPositionVO.setProfitAndLose(userPositionVO.getProfitAndLose().multiply(new BigDecimal(userPositionVO.getOrderLever())));
                    }
                }else{
                    userPositionVO.setProfitAndLose(userPositionVO.getProfitAndLose().multiply(new BigDecimal(userPositionVO.getOrderLever())));
                }
                userPositionVOS.add(userPositionVO);
            }
        }
        BigDecimal profitAndLose = BigDecimal.ZERO;
        for (UserPositionVO f : userPositionVOS) {
            profitAndLose = profitAndLose.add(f.getProfitAndLose());
        }
        return profitAndLose;
    }
    @Override
    public ServerResponse transfer(String fromType, String toType, String amt,HttpServletRequest request) {
        User user =  userService.getCurrentUser(request);
        UserAssets formAssets = userAssetsServices.assetsByTypeAndUserId(fromType,user.getId());
        BigDecimal amtBig = new BigDecimal(amt);
        if(formAssets.getAvailableBalance().compareTo(amtBig)<0){
            return ServerResponse.createByErrorMsg("余额不足",request);
        try {
            User user =  userService.getCurrentUser(request);
            UserAssets formAssets = userAssetsServices.assetsByTypeAndUserId(fromType,user.getId());
            BigDecimal amtBig = new BigDecimal(amt).abs();
            // 转换手续费率
            BigDecimal siteSettingBuyFee = new BigDecimal(iStockConfigServices.queryByKey(EConfigKey.EXCHANGE_HANDLING_CHARGE.getCode()).getCValue()) ;
            BigDecimal orderFree = siteSettingBuyFee.multiply(amtBig);
            //资金校验
            BigDecimal needAmt = amtBig.add(orderFree);
            if(formAssets.getAvailableBalance().compareTo(needAmt)<0){
                return ServerResponse.createByErrorMsg("余额不足", request);
            }
            if (orderFree.compareTo(BigDecimal.ZERO) > 0) {
                userAssetsServices.availablebalanceChange(fromType, user.getId(), EUserAssets.HANDLING_CHARGE, orderFree, "", "");
            }
            userAssetsServices.availablebalanceChange(fromType, user.getId(), EUserAssets.TRANSFER, amtBig.negate(),fromType+"/"+toType,"");
            //转换金额
            amtBig = userAssetsServices.exchangeAmountByRate(fromType, toType, amtBig);
            userAssetsServices.availablebalanceChange(toType,user.getId(), EUserAssets.TRANSFER, amtBig.setScale(5,RoundingMode.HALF_DOWN),fromType+"/"+toType,"");
            return ServerResponse.createBySuccess("操作成功", request);
        } catch (Exception e) {
            return ServerResponse.createByErrorMsg(e.getMessage());
        }
        userAssetsServices.availablebalanceChange(fromType,user.getId(), EUserAssets.TRANSFER,amtBig.negate(),fromType+"/"+toType,"");
        amtBig = rateServices.currencyRate(EStockType.getEStockTypeByCode(fromType),EStockType.getEStockTypeByCode(toType)).multiply(amtBig);
        userAssetsServices.availablebalanceChange(toType,user.getId(),EUserAssets.TRANSFER,amtBig.setScale(5,RoundingMode.HALF_DOWN),fromType+"/"+toType,"");
        return ServerResponse.createBySuccess();
    }
@@ -708,10 +769,24 @@
        List<User> users = this.userMapper.listByAgent(realName, phone, searchId, accountType);
        List<AgentUserListVO> agentUserListVOS = Lists.newArrayList();
        for (User user : users) {
            ServerResponse money = iUserService.getMoney(user.getId());
            List<RUserAssets> rUserAssetsList = (List<RUserAssets>) money.getData();
            RUserAssets rUserAssets = rUserAssetsList.stream()
                    .filter(stock -> EStockType.getDefault().getCode().equals(stock.getAccectType()))
                    .findFirst()
                    .orElse(null);
            AgentUserListVO agentUserListVO = assembleAgentUserListVO(user, siteSetting
                    .getForceStopPercent(), siteIndexSetting
                    .getForceSellPercent(), siteFuturesSetting.getForceSellPercent());
            if (rUserAssets != null) {
                agentUserListVO.setUserAmt(rUserAssets.getTotalMoney().equals("0E-8") ? new BigDecimal("0") : new BigDecimal(rUserAssets.getTotalMoney()));
                agentUserListVO.setFreezeMoney(rUserAssets.getFreezeMoney().equals("0E-8") ? "0" : rUserAssets.getFreezeMoney());
                agentUserListVO.setAvailableBalance(rUserAssets.getAvailableBalance().equals("0E-8") ? "0" : rUserAssets.getAvailableBalance());
            }
            agentUserListVOS.add(agentUserListVO);
        }
@@ -722,60 +797,93 @@
    }
    @Transactional
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse addSimulatedAccount(Integer agentId, String phone, String pwd, String amt, Integer accountType, HttpServletRequest request) {
        if (StringUtils.isBlank(phone) || StringUtils.isBlank(pwd)) {
            return ServerResponse.createByErrorMsg("The parameter cannot be null");
        }
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("phone",phone);
            User dbUser = userMapper.selectOne(queryWrapper);
            if (dbUser != null) {
                return ServerResponse.createByErrorMsg("The phone number is registered");
            }
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone",phone);
        User dbUser = userMapper.selectOne(queryWrapper);
        if (dbUser != null) {
            return ServerResponse.createByErrorMsg("The phone number is registered");
            User user = new User();
            user.setAccountType(accountType);
            user.setPhone(phone);
            user.setIsLock(Integer.valueOf(0));
            user.setIsLogin(Integer.valueOf(0));
            user.setIsActive(Integer.valueOf(0));
            user.setRegTime(new Date());
            user.setRealType(0);
            user.setUserPwd(SymmetricCryptoUtil.encryptPassword(pwd));
            if (accountType.intValue() == 1) {
                user.setNickName("模拟用户");
            }
            if (agentId != null) {
                AgentUser agentUser = this.agentUserMapper.selectByPrimaryKey(agentId);
                user.setAgentName(agentUser.getAgentName());
                user.setAgentId(agentUser.getId());
            }
            int insertCount = this.userMapper.insert(user);
            dbUser = userMapper.selectOne(queryWrapper);
            userAssetsServices.getAvailableBalance(EStockType.getDefault().getCode(),dbUser.getId() );
            userAssetsServices.availablebalanceChange(EStockType.getDefault().getCode(),dbUser.getId(),EUserAssets.TOP_UP,new BigDecimal(amt),"","");
            if (insertCount > 0) {
                return ServerResponse.createBySuccessMsg("Success");
            }
            return ServerResponse.createByErrorMsg("User addition failure");
        } catch (Exception e) {
            return ServerResponse.createByErrorMsg(e.getMessage());
        }
        User user = new User();
        user.setAccountType(accountType);
        user.setPhone(phone);
        user.setIsLock(Integer.valueOf(0));
        user.setIsLogin(Integer.valueOf(0));
        user.setIsActive(Integer.valueOf(0));
        user.setRegTime(new Date());
        if (accountType.intValue() == 1) {
            user.setNickName("模拟用户");
        }
        if (agentId != null) {
            AgentUser agentUser = this.agentUserMapper.selectByPrimaryKey(agentId);
            user.setAgentName(agentUser.getAgentName());
            user.setAgentId(agentUser.getId());
        }
        int insertCount = this.userMapper.insert(user);
         dbUser = userMapper.selectOne(queryWrapper);
        userAssetsServices.getAvailableBalance(EStockType.IN.getCode(),dbUser.getId() );
        userAssetsServices.availablebalanceChange(EStockType.IN.getCode(),dbUser.getId(),EUserAssets.TOP_UP,new BigDecimal(amt),"","");
        if (insertCount > 0) {
            return ServerResponse.createBySuccessMsg("Success");
        }
        return ServerResponse.createByErrorMsg("User addition failure");
    }
    public ServerResponse listByAdmin(String realName, String phone, Integer agentId, Integer accountType, int pageNum, int pageSize, HttpServletRequest request) {
    public ServerResponse listByAdmin(String realName, String phone, Integer agentId, Integer accountType, int pageNum, int pageSize, Integer isLock, Integer isLogin, String regTime, Integer isActive, HttpServletRequest request) throws ParseException {
        PageHelper.startPage(pageNum, pageSize);
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDateString = null;
        if (StringUtils.isNotEmpty(regTime)) {
            formattedDateString = outputFormat.format(inputFormat.parse(regTime));
        }
        List<User> users = this.userMapper.listByAdmin(realName, phone, agentId, accountType, isLock, isLogin, formattedDateString, isActive);
        List<UserOut> userOuts = new ArrayList<>();
        List<User> users = this.userMapper.listByAdmin(realName, phone, agentId, accountType);
        // 获取用户资产信息并构建返回结果
        Map<Integer, UserOut> userOutMap = new HashMap<>();
        for (User user : users) {
            ServerResponse money = iUserService.getMoney(user.getId());
            List<RUserAssets> rUserAssetsList = (List<RUserAssets>) money.getData();
            RUserAssets rUserAssets = rUserAssetsList.stream()
                    .filter(stock -> EStockType.getDefault().getCode().equals(stock.getAccectType()))
                    .findFirst()
                    .orElse(null);
            UserOut userOut = Convert.convert(UserOut.class, user);
            if (rUserAssets != null) {
                userOut.setTotalMoney(rUserAssets.getTotalMoney().equals("0E-8") ? "0" : rUserAssets.getTotalMoney());
                userOut.setFreezeMoney(rUserAssets.getFreezeMoney().equals("0E-8") ? "0" : rUserAssets.getFreezeMoney());
                userOut.setAvailableBalance(rUserAssets.getAvailableBalance().equals("0E-8") ? "0" : rUserAssets.getAvailableBalance());
                userOut.setAmountToBeCovered(rUserAssets.getAmountToBeCovered());
            }
            userOutMap.put(user.getId(), userOut);
            userOuts.add(userOut);
        }
        PageInfo pageInfo = new PageInfo(users);
        pageInfo.setList(userOuts);
        return ServerResponse.createBySuccess(pageInfo);
    }
    public ServerResponse findByUserId(Integer userId) {
@@ -803,7 +911,7 @@
    }
    @Transactional
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse updateAmt(Integer userId, String amt, Integer direction) {
        if (userId == null || amt == null || direction == null) {
            return ServerResponse.createByErrorMsg("The parameter cannot be null");
@@ -986,7 +1094,9 @@
        agentUserListVO.setIsLogin(user.getIsLogin());
        agentUserListVO.setRegAddress(user.getRegAddress());
        agentUserListVO.setIsActive(user.getIsActive());
        agentUserListVO.setImg1Key(user.getImg1Key());
        agentUserListVO.setImg2Key(user.getImg2Key());
        agentUserListVO.setImg3Key(user.getImg3Key());
@@ -1018,14 +1128,6 @@
        agentUserListVO.setFuturesForceLine(futuresForceLine);
        UserBank userBank = this.iUserBankService.findUserBankByUserId(user.getId());
        if (userBank != null) {
            agentUserListVO.setBankName(userBank.getBankName());
            agentUserListVO.setBankNo(userBank.getBankNo());
            agentUserListVO.setBankAddress(userBank.getBankAddress());
        }
        return agentUserListVO;
    }
@@ -1039,6 +1141,7 @@
        userInfoVO.setNickName(user.getNickName());
        userInfoVO.setRealName(user.getRealName());
        userInfoVO.setIdCard(user.getIdCard());
        userInfoVO.setRealType(user.getRealType());
        userInfoVO.setAccountType(user.getAccountType());
        userInfoVO.setRecomPhone(user.getRecomPhone());
        userInfoVO.setIsLock(user.getIsLock());
@@ -1051,6 +1154,12 @@
        userInfoVO.setIsActive(user.getIsActive());
        userInfoVO.setAuthMsg(user.getAuthMsg());
        userInfoVO.setVaildNumber(user.getVaildNumber());
        userInfoVO.setLoanLimit(user.getLoanLimit());
        userInfoVO.setCreditScore(user.getCreditScore());
        //查询代还款金额
        BigDecimal spMoney = dkMapper.sumSpMoneyByUserIdAndRStatus(String.valueOf(user.getId()));
        userInfoVO.setRefundAmount(spMoney);
        return userInfoVO;
    }
@@ -1094,5 +1203,12 @@
        return  ServerResponse.createBySuccess(mapper.selectList(queryWrapper));
    }
    @Override
    public int countPendingAuth() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_active", 1);
        return this.userMapper.selectCount(queryWrapper).intValue();
    }
}