Procházet zdrojové kódy

feat:ios服务端代码优化整理

hidewnd před 3 dny
rodič
revize
e151006404

+ 13 - 2
yt-common/src/main/java/com/ytpm/app/param/IosLoginParam.java

@@ -3,10 +3,15 @@ package com.ytpm.app.param;
 import io.swagger.annotations.ApiModel;
 import io.swagger.annotations.ApiModelProperty;
 import lombok.Data;
+import lombok.EqualsAndHashCode;
+
+import java.util.Date;
+import java.util.List;
 
-@ApiModel("IOS登录参数")
 @Data
-public class IosLoginParam {
+@ApiModel("IOS登录参数")
+@EqualsAndHashCode(callSuper = true)
+public class IosLoginParam extends LoginParam {
     @ApiModelProperty(value = "IOSId")
     private String iosId;
     @ApiModelProperty(value = "手机号")
@@ -37,4 +42,10 @@ public class IosLoginParam {
     private String phoneJson;
     @ApiModelProperty(value = "幂等ID")
     private String requestId;
+
+    @ApiModelProperty("登陆前广告记录")
+    private List<DyzAdRecordParam> preAdList;
+
+    @ApiModelProperty("登陆广告风控")
+    private Date adStartTime;
 }

+ 19 - 14
yt-ios-lemon/lemon-ios-service/src/main/java/com/ytpm/lemonios/controller/AdController.java

@@ -12,9 +12,14 @@ import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiImplicitParam;
 import io.swagger.annotations.ApiImplicitParams;
 import io.swagger.annotations.ApiOperation;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.*;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
 
+import javax.annotation.Resource;
 import java.math.BigDecimal;
 import java.util.List;
 import java.util.Map;
@@ -25,7 +30,7 @@ import java.util.Map;
 @RequestMapping("/ad")
 public class AdController {
 
-    @Autowired
+    @Resource
     private AdService adService;
 
     /**
@@ -33,7 +38,7 @@ public class AdController {
      */
     @ApiOperation("保存")
     @PostMapping("/saveRecord")
-    public Result<?> saveRecord(@RequestBody DyzAdRecordParam param){
+    public Result<?> saveRecord(@RequestBody DyzAdRecordParam param) {
         return adService.saveRecord(param);
     }
 
@@ -42,7 +47,7 @@ public class AdController {
      */
     @ApiOperation("根据应用ID查询广告数")
     @GetMapping("/getAdCount")
-    public Map<String, BigDecimal> getAdCount(@RequestParam(name = "appIds")String appIds){
+    public Map<String, BigDecimal> getAdCount(@RequestParam(name = "appIds") String appIds) {
         return adService.getAdCount(appIds);
     }
 
@@ -50,40 +55,40 @@ public class AdController {
      * 查询应用排行榜信息
      */
     @ApiImplicitParams({
-            @ApiImplicitParam(name = "sortBy", value = "排行榜排序规则",required = true),
-            @ApiImplicitParam(name = "limit", value = "排行榜显示数量",required = true),
+            @ApiImplicitParam(name = "sortBy", value = "排行榜排序规则", required = true),
+            @ApiImplicitParam(name = "limit", value = "排行榜显示数量", required = true),
     })
     @ApiOperation("查询应用排行榜信息")
     @GetMapping("/getAppRankingList")
-    public DashboardRankingListVO queryRankingList(@RequestParam(name = "sortBy")Integer sortBy,@RequestParam(name = "limit")Integer limit){
-        return adService.queryRankingList(sortBy,limit);
+    public DashboardRankingListVO queryRankingList(@RequestParam(name = "sortBy") Integer sortBy, @RequestParam(name = "limit") Integer limit) {
+        return adService.queryRankingList(sortBy, limit);
     }
 
     /**
      * 查询各渠道应用收益分时统计
      */
-    @ApiImplicitParam(name = "apkIds", value = "渠道应用ID(,拼接)",required = true)
+    @ApiImplicitParam(name = "apkIds", value = "渠道应用ID(,拼接)", required = true)
     @ApiOperation("查询各渠道应用收益分时统计")
     @GetMapping("/revenueStatics")
-    public DashboardRevenueVO revenueStatics(@RequestParam(name = "apkIds")String apkIds){
+    public DashboardRevenueVO revenueStatics(@RequestParam(name = "apkIds") String apkIds) {
         return adService.revenueStatics(apkIds);
     }
 
     @ApiOperation("查询渠道商顶部数据")
     @GetMapping("/getAppTopCount")
-    public AgentTopCountView getAppTopCount(@RequestParam(name = "appIds")String appIds){
+    public AgentTopCountView getAppTopCount(@RequestParam(name = "appIds") String appIds) {
         return adService.getAppTopCount(appIds);
     }
 
     @ApiOperation("查询用户风控分时数据统计")
     @GetMapping("/userStatics")
-    public DashboardRiskVO userStatics(@RequestParam(name = "appId")String appId){
+    public DashboardRiskVO userStatics(@RequestParam(name = "appId") String appId) {
         return adService.userStatics(appId);
     }
 
     @ApiOperation("查询代理商首页统计广告数据")
     @GetMapping("/getAgentProfit")
-    public List<AgentAdGroupStaticsVO> getAgentProfit(@RequestParam(name = "appIds")String appIds){
+    public List<AgentAdGroupStaticsVO> getAgentProfit(@RequestParam(name = "appIds") String appIds) {
         return adService.getAgentProfit(appIds);
     }
 }

+ 3 - 2
yt-ios-lemon/lemon-ios-service/src/main/java/com/ytpm/lemonios/controller/QuestionController.java

@@ -8,16 +8,17 @@ import com.ytpm.general.ResultTable;
 import com.ytpm.lemonios.service.QuestionService;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 
+import javax.annotation.Resource;
+
 
 @Api(tags = "题目管理模块")
 @RestController
 @RequestMapping("/question")
 public class QuestionController {
 
-    @Autowired
+    @Resource
     private QuestionService questionService;
 
     /**

+ 6 - 5
yt-ios-lemon/lemon-ios-service/src/main/java/com/ytpm/lemonios/controller/UserController.java

@@ -32,7 +32,6 @@ import com.ytpm.risk.view.RiskTemplateView;
 import com.ytpm.util.DateUtil;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.validation.Errors;
 import org.springframework.web.bind.annotation.*;
 
 import java.math.BigDecimal;
@@ -201,7 +200,8 @@ public class UserController {
      * 查询用户的广告记录
      */
     @GetMapping("/adRecords")
-    public ResultTable<YtDyzAdRecord> adRecords(@RequestParam(name = "userId",required = true) String userId,@RequestParam(name = "adsourceType",required = false)Integer adsourceType) {
+    public ResultTable<YtDyzAdRecord> adRecords(@RequestParam(name = "userId",required = true) String userId,
+                                                @RequestParam(name = "adsourceType",required = false)Integer adsourceType) {
         List<YtDyzAdRecord> result = new ArrayList<>();
         List<YtDyzAdRecord> adrecords = adRecordMapper.getByUserId(userId, adsourceType);
         if(CollUtil.isNotEmpty(adrecords)){
@@ -253,7 +253,8 @@ public class UserController {
 
     @PostMapping("/queryUserByTime")
     public List<YtDyzUser> queryUserByTime(@RequestBody AppUserQueryParam appUserQueryParam) {
-        List<YtDyzUser> ytDyzUsers = appUserMapper.queryAllByTime(appUserQueryParam.getStartTime(), appUserQueryParam.getEndTime(),appUserQueryParam.getAppIdList());
+        List<YtDyzUser> ytDyzUsers = appUserMapper.queryAllByTime(appUserQueryParam.getStartTime(),
+                appUserQueryParam.getEndTime(),appUserQueryParam.getAppIdList());
         return ytDyzUsers;
     }
 
@@ -295,14 +296,14 @@ public class UserController {
     }
     @PostMapping("/queryTodayBanned")
     public List<YtDyzUser> queryTodayBanned(@RequestBody AppUserTodayBannedParam appUserTodayBannedParam){
-        return appUserMapper.queryTodayBanned(appUserTodayBannedParam.getStartTime(), appUserTodayBannedParam.getEndTime(), appUserTodayBannedParam.getUserIdList());
+        return appUserMapper.queryTodayBanned(appUserTodayBannedParam.getStartTime(),
+                appUserTodayBannedParam.getEndTime(), appUserTodayBannedParam.getUserIdList());
     }
     @PostMapping("/unLockUser")
     public void unLockUser(@RequestParam("userIds")String userIds){
         List<YtDyzUser> dyzUsers = appUserMapper.queryByUserIds(userIds);
         if(CollUtil.isNotEmpty(dyzUsers)){
             appUserMapper.unlockUser(userIds);
-            return;
         }
     }
     @GetMapping("/lockUser")

+ 153 - 95
yt-ios-lemon/lemon-ios-service/src/main/java/com/ytpm/lemonios/controller/WxController.java

@@ -5,14 +5,15 @@ import cn.hutool.core.util.IdUtil;
 import cn.hutool.core.util.StrUtil;
 import cn.hutool.http.HttpUtil;
 import com.alibaba.fastjson.JSON;
+import com.ytpm.agent.enums.AdRecordEnum;
 import com.ytpm.agent.enums.UserStatusEnum;
 import com.ytpm.agent.model.YtDitch;
-import com.ytpm.app.enums.AppTypeEnums;
 import com.ytpm.app.enums.LoginType;
 import com.ytpm.app.model.YtAppDefaultConfig;
 import com.ytpm.app.model.YtDyzAdRecord;
 import com.ytpm.app.model.YtDyzUser;
 import com.ytpm.app.param.AppConfigUpdateParam;
+import com.ytpm.app.param.DyzAdRecordParam;
 import com.ytpm.app.param.IosLoginParam;
 import com.ytpm.app.param.WxLoginParam;
 import com.ytpm.app.view.IosPowerResView;
@@ -28,6 +29,7 @@ import com.ytpm.lemonios.dao.AdRecordMapper;
 import com.ytpm.lemonios.dao.AppUserMapper;
 import com.ytpm.lemonios.dao.DitchMapper;
 import com.ytpm.lemonios.redis.RedisService;
+import com.ytpm.lemonios.service.AdService;
 import com.ytpm.lemonios.service.AppUserService;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
@@ -45,6 +47,7 @@ import org.springframework.web.bind.annotation.RestController;
 
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
+import java.math.BigDecimal;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.List;
@@ -58,12 +61,14 @@ import java.util.concurrent.TimeUnit;
 @RefreshScope
 @RequestMapping("/wx")
 public class WxController {
-    private final static String GRANT_TYPE = "authorization_code";
+
     @Resource
     private AppUserMapper appUserMapper;
     @Resource
     private AdRecordMapper recordMapper;
     @Resource
+    private AdService adService;
+    @Resource
     private RiskFeign riskFeign;
     @Resource
     private AppUserService appUserService;
@@ -71,9 +76,13 @@ public class WxController {
     private DitchMapper ditchMapper;
     @Resource
     private RedisService redisService;
+
     @Value("${yt.ios.appid:}")
     private String appId;
+    private final static String GRANT_TYPE = "authorization_code";
+
 
+    @Deprecated
     @PostMapping("/login")
     @ApiOperation("微信登录")
     @Transactional
@@ -84,9 +93,10 @@ public class WxController {
             return new Result<>(StatusCode.ACCESS_ERR,"微信登录失败,未找到相应配置!");
         }
         param.setAppId(defaultConfig.getPlatformAppId());
-        WxLoginResult loginResult = getWechatLoginInfo(param.getWxCode(),param.getAppType(),defaultConfig.getAppId(),defaultConfig.getSecret());
-        if(Objects.isNull(loginResult)|| StrUtil.isBlank(loginResult.getOpenid())){
-            return new Result<>(StatusCode.ACCESS_ERR,"微信登录失败,请刷新授权码!");
+        WxLoginResult loginResult = getWechatLoginInfo(param.getWxCode(), param.getAppType(),
+                defaultConfig.getAppId(), defaultConfig.getSecret());
+        if (Objects.isNull(loginResult) || StrUtil.isBlank(loginResult.getOpenid())) {
+            return new Result<>(StatusCode.ACCESS_ERR, "微信登录失败,请刷新授权码!");
         }
         WxUserInfo wxUserInfo = getWechatUserInfo(loginResult.getAccess_token(),loginResult.getOpenid());
         if(Objects.isNull(wxUserInfo)) {
@@ -103,6 +113,35 @@ public class WxController {
         return Result.resultOk(RepMessage.LOGIN_SUCCESS, old);
     }
 
+
+    /**
+     * 获取微信用户信息
+     */
+    private WxUserInfo getWechatUserInfo(String accessToken, String openid) {
+        // 根据token和openid 获取用户信息
+        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={}&openid={}&lang=zh_CN";
+        userInfoUrl = StrUtil.format(userInfoUrl, accessToken, openid);
+        String curUser = HttpUtil.get(userInfoUrl);
+        WxUserInfo wxUserInfo = JSON.parseObject(curUser, WxUserInfo.class);
+        log.error("获取的用户信息:{}",wxUserInfo);
+        return wxUserInfo;
+    }
+
+
+    /**
+     * 微信登录
+     */
+    private WxLoginResult getWechatLoginInfo(String wxCode, int appType, String appId, String secret) {
+        String wxLoginUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={}&secret={}&code={}&grant_type={}";
+        wxLoginUrl = StrUtil.format(wxLoginUrl, appId, secret, wxCode, GRANT_TYPE);
+        //拿到授权码 请求微信登录返回access_token
+        String result = HttpUtil.get(wxLoginUrl);
+        WxLoginResult loginResult = JSON.parseObject(result, WxLoginResult.class);
+        log.error("授权码获取的登录结果:{}", loginResult);
+        return loginResult;
+    }
+
+
     @ApiOperation("获取IOS登陆幂等Token")
     @GetMapping("/get/requestId")
     public Result<String> getRequestId(@RequestParam("ditchId") String ditchId, @RequestParam("iosId") String iosId){
@@ -127,9 +166,65 @@ public class WxController {
         return Result.resultObjOk(requestId);
     }
 
-    @PostMapping("/iosLogin")
-    @ApiOperation("IOS登录")
+    @Deprecated
     @Transactional
+    @ApiOperation("IOS登录校验")
+    @PostMapping("/iosLoginCheck")
+    public Result<?> iosLoginCheck(@RequestBody IosLoginParam param) {
+        YtDyzUser user = appUserMapper.selectByIosId(param.getIosId());
+        if (user == null) {
+            IosUserInfo userInfo = setIosUserInfo(param);
+            user = appUserService.crudForNewTransIos(param, userInfo, LoginType.VISITOR);
+        }
+        //2.拿3条记录 设置到user
+        // TODO 当前仅截取最新三条记录,可能遗漏本次登陆前的风控记录(停落时间过长记录超过三条)
+        List<YtDyzAdRecord> adRecordList = recordMapper.getByIosIdBeforeLogin(param.getIosId());
+
+        user.setPreAdRecordList(adRecordList);
+        user.setLoginType(LoginType.VISITOR);
+        user.setAppId(appId);
+        Result<?> result = riskFeign.checkLoginRisk(user);
+        if (result.getCode() != 200) {
+            String errorMessage = result.getMessage();
+            if (user.getLoginType() == LoginType.VISITOR && RepMessage.RISK_VISITOR_LOWER_VALUE.equals(errorMessage)) {
+                WxDefaultConfig defaultConfig = appUserMapper.getLastDefaultConfig();
+                return Result.resultErr(StrUtil.emptyToDefault(defaultConfig.getLowValueTip(), errorMessage));
+            }
+            return Result.resultErr(errorMessage);
+        }
+        YtDyzUser newUser = new YtDyzUser();
+        newUser.setUserId(user.getUserId());
+        newUser.setUserStatus(UserStatusEnum.NORMAL.getCode());
+        appUserMapper.updateUser(newUser);
+        return Result.resultObjOk(user);
+    }
+
+    private IosUserInfo setIosUserInfo(IosLoginParam param){
+        IosUserInfo userInfo = new IosUserInfo();
+        userInfo.setOpenid(param.getIosId() ==  null ? "" : param.getIosId());
+        userInfo.setHeadimgurl(param.getIconUrl()  ==  null ? "" : param.getIconUrl());
+        if (StrUtil.isEmpty(param.getAlias())){
+            YtDyzUser user;
+            if (param.getDitchId() == null){
+                user = appUserMapper.selectByIosId(param.getIosId());
+            } else {
+                user = appUserMapper.getYtAppUserForIos(param.getIosId(), param.getDitchId());
+            }
+            if (user == null  || StrUtil.isEmpty(user.getNickName())) {
+                userInfo.setNickname("Tourists" + IdUtil.fastSimpleUUID().substring(0, 8));
+            } else {
+                userInfo.setNickname(user.getNickName());
+            }
+        } else {
+            userInfo.setNickname(param.getAlias());
+        }
+        return userInfo;
+    }
+
+
+    @ApiOperation("IOS登录")
+    @PostMapping("/iosLogin")
+    @Transactional(rollbackFor = Exception.class)
     public Result<YtDyzUser> iosLogin(@RequestBody IosLoginParam param, HttpServletRequest request) {
         //根据应用ID获取配置调用接口登录
         WxDefaultConfig defaultConfig = appUserMapper.getDefaultConfigByDitchId(param.getDitchId());
@@ -159,51 +254,67 @@ public class WxController {
         }
         IosUserInfo userInfo = setIosUserInfo(param);
         param.setLoginIp(getClientIp(request));
-        YtDyzUser old = appUserService.crudForNewTransIos(param, userInfo, LoginType.IOS.getTypeName());
+        // 获取或注册用户
+        YtDyzUser dyzUser = appUserService.crudForNewTransIos(param, userInfo, LoginType.IOS);
+        // 如果传入游客广告记录,执行游客登陆校验
+        if (CollUtil.isNotEmpty(param.getPreAdList())) {
+            dyzUser.setLoginType(LoginType.VISITOR);
+            List<YtDyzAdRecord> preAdRecordList = saveVisitorAdRecord(dyzUser, param);
+            dyzUser.setPreAdRecordList(preAdRecordList);
+            Result<?> result = riskFeign.checkLoginRisk(dyzUser);
+            if (result.getCode() != 200) {
+                String errorMessage = result.getMessage();
+                if (RepMessage.RISK_VISITOR_LOWER_VALUE.equals(errorMessage)) {
+                    errorMessage = StrUtil.emptyToDefault(defaultConfig.getLowValueTip(), errorMessage);
+                }
+                return new Result<>(StatusCode.ACCESS_ERR, errorMessage);
+            }
+        }
+        // 状态更新 游客登陆前风控 -> 正常
+        YtDyzUser newUser = new YtDyzUser();
+        newUser.setUserId(dyzUser.getUserId());
+        dyzUser.setUserStatus(UserStatusEnum.NORMAL.getCode());
+        newUser.setUserStatus(UserStatusEnum.NORMAL.getCode());
+        appUserMapper.updateUser(newUser);
         //调用风控服务校验默认风控配置
-        old.setRiskCode("313");
-        Result<?> result = riskFeign.checkRisk(old);
+        dyzUser.setLoginType(LoginType.IOS);
+        dyzUser.setRiskCode("313");
+        Result<?> result = riskFeign.checkRisk(dyzUser);
         if (result.getCode() != 200) {
             return new Result<>(StatusCode.ACCESS_ERR, result.getMessage());
         }
-        if (old.getLastLoginTime() != null && old.getRegistryTime() != null) {
+        if (dyzUser.getLastLoginTime() != null && dyzUser.getRegistryTime() != null) {
             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
-            old.setLastLoginTimeStr(sdf.format(old.getLastLoginTime()));
-            old.setRegistryTimeStr(sdf.format(old.getRegistryTime()));
+            dyzUser.setLastLoginTimeStr(sdf.format(dyzUser.getLastLoginTime()));
+            dyzUser.setRegistryTimeStr(sdf.format(dyzUser.getRegistryTime()));
         }
         //调用风控服务校验默认风控配置
-        return Result.resultOk(RepMessage.LOGIN_SUCCESS, old);
+        return Result.resultOk(RepMessage.LOGIN_SUCCESS, dyzUser);
     }
 
-    @PostMapping("/iosLoginCheck")
-    @ApiOperation("IOS登录校验")
-    @Transactional
-    public Result<?> iosLoginCheck(@RequestBody IosLoginParam param) {
-        YtDyzUser user = appUserMapper.selectByIosId(param.getIosId());
-        if (user == null) {
-            IosUserInfo userInfo = setIosUserInfo(param);
-            user = appUserService.crudForNewTransIos(param, userInfo, LoginType.VISITOR.getTypeName());
-        }
-        //2.拿3条记录 设置到user
-        List<YtDyzAdRecord> adRecordList = recordMapper.getByIosIdBeforeLogin(param.getIosId());
-
-        user.setPreAdRecordList(adRecordList);
-        user.setLoginType(LoginType.VISITOR);
-        user.setAppId(appId);
-        Result<?> result = riskFeign.checkLoginRisk(user);
-        if (result.getCode() != 200) {
-            String errorMessage = result.getMessage();
-            if (user.getLoginType() == LoginType.VISITOR && RepMessage.RISK_VISITOR_LOWER_VALUE.equals(errorMessage)) {
-                WxDefaultConfig defaultConfig = appUserMapper.getLastDefaultConfig();
-                return Result.resultErr(StrUtil.emptyToDefault(defaultConfig.getLowValueTip(), errorMessage));
+    private List<YtDyzAdRecord> saveVisitorAdRecord(YtDyzUser ytDyzUser, IosLoginParam visitorLoginParam) {
+        List<DyzAdRecordParam> preAdList = visitorLoginParam.getPreAdList();
+        // 保存登陆前传递的广告记录
+        List<String> adRecordIds = new ArrayList<>();
+        if (CollUtil.isNotEmpty(preAdList)) {
+            BigDecimal totalRevenue = BigDecimal.ZERO;
+            for (DyzAdRecordParam adRecordParam : preAdList) {
+                if (adRecordParam == null) {
+                    continue;
+                }
+                adRecordParam.setUserId(ytDyzUser.getUserId());
+                adRecordParam.setNickName(ytDyzUser.getNickName());
+                adRecordParam.setAppId(ytDyzUser.getAppId());
+                adRecordParam.setLoginStatus(AdRecordEnum.LOGIN_BEFORE.getCode());
+                String recordId = adService.saveRecordAndChangeUser(adRecordParam, ytDyzUser);
+                adRecordIds.add(recordId);
+                totalRevenue = adRecordParam.getRevenue() == null ? totalRevenue : totalRevenue.add(adRecordParam.getRevenue());
             }
-            return Result.resultErr(errorMessage);
+            log.info(StrUtil.format("[visitor adRecords]userId:{} recordCount:{} revenue:{}",
+                    ytDyzUser.getUserId(), adRecordIds.size(), totalRevenue.toPlainString()));
         }
-        YtDyzUser newUser = new YtDyzUser();
-        newUser.setUserId(user.getUserId());
-        newUser.setUserStatus(UserStatusEnum.NORMAL.getCode());
-        appUserMapper.updateUser(newUser);
-        return Result.resultObjOk(user);
+        return CollUtil.isEmpty(adRecordIds) ? new ArrayList<>()
+                : recordMapper.selectRecordByIds(AdRecordEnum.LOGIN_BEFORE.getCode(), adRecordIds);
     }
 
     @PostMapping("/getByDitchId")
@@ -229,59 +340,6 @@ public class WxController {
         return xfHeader.split(",")[0]; // 可能会有多个IP,这里取第一个逗号前的IP
     }
 
-    /**
-     * 获取微信用户信息
-     */
-    private WxUserInfo getWechatUserInfo(String accessToken, String openid) {
-        // 根据token和openid 获取用户信息
-        String userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+accessToken+"&openid="+openid+"&lang=zh_CN";
-        String curUser = HttpUtil.get(userInfoUrl);
-        WxUserInfo wxUserInfo = JSON.parseObject(curUser, WxUserInfo.class);
-        log.error("获取的用户信息:{}",wxUserInfo);
-        return wxUserInfo;
-    }
-
-    private IosUserInfo setIosUserInfo(IosLoginParam param){
-        IosUserInfo userInfo = new IosUserInfo();
-        userInfo.setOpenid(param.getIosId() ==  null ? "" : param.getIosId());
-        userInfo.setHeadimgurl(param.getIconUrl()  ==  null ? "" : param.getIconUrl());
-        if (StrUtil.isEmpty(param.getAlias())){
-            YtDyzUser user;
-            if (param.getDitchId() == null){
-                user = appUserMapper.selectByIosId(param.getIosId());
-            } else {
-                user = appUserMapper.getYtAppUserForIos(param.getIosId(), param.getDitchId());
-            }
-            if (user == null  || StrUtil.isEmpty(user.getNickName())) {
-                userInfo.setNickname("Tourists" + IdUtil.fastSimpleUUID().substring(0, 8));
-            } else {
-                userInfo.setNickname(user.getNickName());
-            }
-        } else {
-            userInfo.setNickname(param.getAlias());
-        }
-        return userInfo;
-    }
-
-    /**
-     * 微信登录
-     */
-    private WxLoginResult getWechatLoginInfo(String wxCode,int appType,String appId,String secret) {
-
-        String wxLoginUrl;
-        if(AppTypeEnums.QNJZ.getCode() == appType){
-            wxLoginUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
-                    +appId+"&secret="+secret+"&code="+wxCode+"&grant_type="+GRANT_TYPE;
-        }else{
-            wxLoginUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appId
-                    +"&secret="+secret+"&code="+wxCode+"&grant_type="+GRANT_TYPE;
-        }
-        //拿到授权码 请求微信登录返回access_token
-        String result = HttpUtil.get(wxLoginUrl);
-        WxLoginResult loginResult = JSON.parseObject(result, WxLoginResult.class);
-        log.error("授权码获取的登录结果:{}",loginResult);
-        return loginResult;
-    }
 
     @Deprecated
     @ApiOperation("获取微信默认配置项")
@@ -291,7 +349,7 @@ public class WxController {
         if(Objects.isNull(config)){
             return Result.resultErr("应用类型有误!");
         }
-       return Result.resultObjOk(config);
+        return Result.resultObjOk(config);
     }
 
     @ApiOperation("体力增加")

+ 6 - 0
yt-ios-lemon/lemon-ios-service/src/main/java/com/ytpm/lemonios/dao/AdRecordMapper.java

@@ -75,4 +75,10 @@ public interface AdRecordMapper {
     Integer getRecordMonthCount(@Param("userId") String userId,
                                 @Param("adSourceType") Integer adSourceType,
                                 @Param("startTime") Date startTime);
+
+    /**
+     * 查询指定广告记录
+     */
+    List<YtDyzAdRecord> selectRecordByIds(@Param("loginStatus") Integer loginStatus, @Param("ids") List<String> adRecordIds);
+
 }

+ 76 - 57
yt-ios-lemon/lemon-ios-service/src/main/java/com/ytpm/lemonios/redis/RedisService.java

@@ -15,22 +15,20 @@ import java.util.Calendar;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
 
+
 @Service
 public class RedisService {
+
     @Autowired
     StringRedisTemplate stringRedisTemplate;
 
-
-    @Resource(name = "stringRedisTemplate")
-    ValueOperations<String, String> valOpsStr;
-
     @Autowired
     RedisTemplate<Object, Object> redisTemplate;
 
     @Autowired(required = false)
-    public void setRedisTemplate(RedisTemplate redisTemplate) {
+    public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
         //序列化key值,防止key值前面乱码
-        RedisSerializer stringSerializer = new StringRedisSerializer();
+        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
         redisTemplate.setKeySerializer(stringSerializer);
         redisTemplate.setHashKeySerializer(stringSerializer);
         this.redisTemplate = redisTemplate;
@@ -41,11 +39,12 @@ public class RedisService {
 
     /**
      * 根据指定key获取String
+     *
      * @param key
      * @return
      */
-    public String getStr(String key){
-        return valOpsStr.get(key);
+    public String getStr(String key) {
+        return stringRedisTemplate.opsForValue().get(key);
     }
 
 
@@ -58,24 +57,27 @@ public class RedisService {
 
     /**
      * 设置Str缓存
+     *
      * @param key
      * @param val
      */
-    public void setStr(String key, String val){
-        valOpsStr.set(key,val);
+    public void setStr(String key, String val) {
+        stringRedisTemplate.opsForValue().set(key, val);
     }
 
     /**
      * 设置Str缓存 timeOut单位  毫秒
+     *
      * @param key
      * @param val
      */
-    public void setTimeOutStr(String key, String val ,long timeOut){
-        valOpsStr.set(key,val,timeOut, TimeUnit.MILLISECONDS);
+    public void setTimeOutStr(String key, String val, long timeOut) {
+        stringRedisTemplate.opsForValue().set(key, val, timeOut, TimeUnit.MILLISECONDS);
     }
 
     /**
      * 判断是否存在key
+     *
      * @param key
      * @return
      */
@@ -85,38 +87,42 @@ public class RedisService {
 
     /**
      * 设置Str缓存 timeOut单位  小时
+     *
      * @param key
      * @param val
      * @param timeOut
      */
-    public void setTimeOutHoursStr(String key, String val ,long timeOut){
-        valOpsStr.set(key,val,timeOut, TimeUnit.HOURS);
+    public void setTimeOutHoursStr(String key, String val, long timeOut) {
+        stringRedisTemplate.opsForValue().set(key, val, timeOut, TimeUnit.HOURS);
     }
 
     /**
      * 设置Str缓存 timeOut单位  分钟
+     *
      * @param key
      * @param val
      * @param timeOut
      */
-    public void setTimeOutMinutesStr(String key, String val ,long timeOut){
-        valOpsStr.set(key,val,timeOut, TimeUnit.MINUTES);
+    public void setTimeOutMinutesStr(String key, String val, long timeOut) {
+        stringRedisTemplate.opsForValue().set(key, val, timeOut, TimeUnit.MINUTES);
     }
 
     public boolean setIfAbsent(String key, String val ,long timeOut, TimeUnit timeUnit){
-        return Boolean.TRUE.equals(valOpsStr.setIfAbsent(key, val, timeOut, timeUnit));
+        return Boolean.TRUE.equals(valOpsObj.setIfAbsent(key, val, timeOut, timeUnit));
     }
 
     /**
      * 删除指定key
+     *
      * @param key
      */
-    public void del(String key){
+    public void del(String key) {
         stringRedisTemplate.delete(key);
     }
 
     /**
      * 设置指定key值的超时时间
+     *
      * @param key
      */
     public void expire(String key, long timeOut) {
@@ -130,91 +136,103 @@ public class RedisService {
 
     /**
      * 根据前缀批量删除
+     *
      * @param keysPrefix
      */
-    public void delKeys(String keysPrefix){
+    public void delKeys(String keysPrefix) {
         Set<String> set = stringRedisTemplate.keys(keysPrefix);
         stringRedisTemplate.delete(set);
     }
 
 
-
     /**
      * 根据指定o获取Object
+     *
      * @param o
      * @return
      */
-    public Object getObj(Object o){
+    public Object getObj(Object o) {
         return valOpsObj.get(o);
     }
 
     /**
      * 设置obj缓存
+     *
      * @param o1
      * @param o2
      */
-    public void setObj(Object o1, Object o2){
+    public void setObj(Object o1, Object o2) {
         valOpsObj.set(o1, o2);
     }
+
     /**
      * 设置obj缓存
+     *
      * @param o1
      * @param o2
      */
-    public void setObj(Object o1, Object o2,long timeout){
-        valOpsObj.set(o1, o2,timeout);
+    public void setObj(Object o1, Object o2, long timeout) {
+        valOpsObj.set(o1, o2, timeout);
     }
 
 
     /**
      * 删除Obj缓存
+     *
      * @param o
      */
-    public void delObj(Object o){
+    public void delObj(Object o) {
         redisTemplate.delete(o);
     }
 
 
     /**
      * 自增1
+     *
      * @param key
      * @return
      */
-    public long incr(String key){
-        long num = valOpsStr.increment(key,1);
+    public long incr(String key) {
+        long num = stringRedisTemplate.opsForValue().increment(key, 1);
         return num;
     }
+
     /**
      * 自增1
+     *
      * @param key
      * @return
      */
-    public long incrByExp(String key,long timeout){
-        long num = valOpsStr.increment(key,1);
-        TimeUnit timeUnit=TimeUnit.MILLISECONDS;
-        stringRedisTemplate.expire(key,timeout, timeUnit);
+    public long incrByExp(String key, long timeout) {
+        long num = stringRedisTemplate.opsForValue().increment(key, 1);
+        TimeUnit timeUnit = TimeUnit.MILLISECONDS;
+        stringRedisTemplate.expire(key, timeout, timeUnit);
         return num;
     }
+
     /**
      * 自增
+     *
      * @param key
-     * @param delta  自增值
+     * @param delta 自增值
      * @return
      */
-    public long incrByExp(String key,int delta,long timeout){
-        long num = valOpsStr.increment(key,delta);
-        TimeUnit timeUnit=TimeUnit.MILLISECONDS;
-        stringRedisTemplate.expire(key,timeout, timeUnit);
+    public long incrByExp(String key, int delta, long timeout) {
+        long num = stringRedisTemplate.opsForValue().increment(key, delta);
+        TimeUnit timeUnit = TimeUnit.MILLISECONDS;
+        stringRedisTemplate.expire(key, timeout, timeUnit);
         return num;
     }
+
     /**
      * 自增
+     *
      * @param key
-     * @param delta  自增值
+     * @param delta 自增值
      * @return
      */
-    public long incr(String key,long delta){
-        return valOpsStr.increment(key,delta);
+    public long incr(String key, long delta) {
+        return stringRedisTemplate.opsForValue().increment(key, delta);
     }
 
     /**
@@ -226,58 +244,59 @@ public class RedisService {
         LocalDate yesterday = currentDate.minusDays(1);
         String todayKey = currentDate.format(formatter);
         String yesterdayKey = yesterday.format(formatter);
-        if(this.hasKey(todayKey)){
+        if (this.hasKey(todayKey)) {
             this.incr(todayKey);
             return this.getStr(todayKey);
         }
         this.del(yesterdayKey);
-        this.setStr(todayKey, todayKey+"00001");
+        this.setStr(todayKey, todayKey + "00001");
         return this.getStr(todayKey);
     }
 
-    public Long getDitchId(){
+    public Long getDitchId() {
         DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
         LocalDate currentDate = LocalDate.now();
         LocalDate yesterday = currentDate.minusDays(1);
         String todayKey = currentDate.format(formatter);
         String yesterdayKey = yesterday.format(formatter);
         String prefix = "Ditch_";
-        if(this.hasKey(prefix+todayKey)){
-            this.incr(prefix+todayKey);
-            return Long.parseLong(this.getStr(prefix+todayKey));
+        if (this.hasKey(prefix + todayKey)) {
+            this.incr(prefix + todayKey);
+            return Long.parseLong(this.getStr(prefix + todayKey));
         }
         this.del(yesterdayKey);
-        this.setStr(prefix+todayKey, todayKey+"01");
-        return Long.parseLong(this.getStr(prefix+todayKey));
+        this.setStr(prefix + todayKey, todayKey + "01");
+        return Long.parseLong(this.getStr(prefix + todayKey));
     }
 
     /**
      *
      * 生成业务单编号
+     *
      * @return
      */
-    public String generateOrderNo(String key){
+    public String generateOrderNo(String key) {
         Calendar cl = Calendar.getInstance();
         int year = cl.get(Calendar.YEAR);
         int month = cl.get(Calendar.MONTH) + 1;
         int day = cl.get(Calendar.DATE);
-        String orderNoPrefix = getTimeStr(year)+getTimeStr(month)+getTimeStr(day);
-        if(this.hasKey(key)){
+        String orderNoPrefix = getTimeStr(year) + getTimeStr(month) + getTimeStr(day);
+        if (this.hasKey(key)) {
             String old = this.getStr(key);
-            String sub = old.substring(0,8);
-            if(sub.equals(orderNoPrefix)){
+            String sub = old.substring(0, 8);
+            if (sub.equals(orderNoPrefix)) {
                 long incr = this.incr(key);
                 return String.valueOf(incr);
             }
         }
-        this.setStr(key,orderNoPrefix+"001");
-        return orderNoPrefix+"001";
+        this.setStr(key, orderNoPrefix + "001");
+        return orderNoPrefix + "001";
     }
 
-    private String getTimeStr(int num){
-        if(num>9) {
+    private String getTimeStr(int num) {
+        if (num > 9) {
             return String.valueOf(num);
         }
-        return "0"+num;
+        return "0" + num;
     }
 }

+ 5 - 0
yt-ios-lemon/lemon-ios-service/src/main/java/com/ytpm/lemonios/service/AdService.java

@@ -2,6 +2,7 @@ package com.ytpm.lemonios.service;
 
 import com.ytpm.agent.view.AgentAdGroupStaticsVO;
 import com.ytpm.agent.view.AgentTopCountView;
+import com.ytpm.app.model.YtDyzUser;
 import com.ytpm.app.param.DyzAdRecordParam;
 import com.ytpm.general.Result;
 import com.ytpm.middle.view.DashboardRankingListVO;
@@ -18,6 +19,10 @@ public interface AdService {
      */
     Result<?> saveRecord(DyzAdRecordParam param);
 
+    //    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
+    String saveRecordAndChangeUser(DyzAdRecordParam param, YtDyzUser user);
+
+
     /**
      * 根据应用查询广告数量
      */

+ 2 - 1
yt-ios-lemon/lemon-ios-service/src/main/java/com/ytpm/lemonios/service/AppUserService.java

@@ -1,6 +1,7 @@
 package com.ytpm.lemonios.service;
 
 import com.ytpm.agent.model.YtDitch;
+import com.ytpm.app.enums.LoginType;
 import com.ytpm.app.model.YtDyzUser;
 import com.ytpm.app.param.IosLoginParam;
 import com.ytpm.app.param.WxLoginParam;
@@ -23,7 +24,7 @@ public interface AppUserService {
     /**
      * 子事务处理用户crud
      */
-    YtDyzUser crudForNewTransIos(IosLoginParam param, IosUserInfo userInfo, String loginType);
+    YtDyzUser crudForNewTransIos(IosLoginParam param, IosUserInfo userInfo, LoginType loginType);
 
     Result<?> addDefaultConfig(YtDitch param);
 

+ 35 - 42
yt-ios-lemon/lemon-ios-service/src/main/java/com/ytpm/lemonios/service/impl/AdServiceImpl.java

@@ -32,7 +32,6 @@ import com.ytpm.middle.view.DashboardRiskVO;
 import com.ytpm.middle.view.UserRankingListVO;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.BeanUtils;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.cloud.context.config.annotation.RefreshScope;
 import org.springframework.stereotype.Service;
@@ -59,21 +58,20 @@ import java.util.stream.Collectors;
 @RefreshScope
 public class AdServiceImpl implements AdService {
 
-    @Autowired
+    @Resource
     private AdRecordMapper adRecordMapper;
-    @Autowired
+    @Resource
     private AppUserMapper appUserMapper;
+    @Resource
+    private RiskFeign riskFeign;
+    @Resource
+    private AppUserService appUserService;
 
     @Value(" ${risk.config.banned.tips}")
     private String tips;
-    @Autowired
-    private RiskFeign riskFeign;
     @Value("${yt.ios.appid:}")
     private String appId;
 
-    @Resource
-    private AppUserService appUserService;
-
     /**
      * 保存广告记录
      */
@@ -106,20 +104,46 @@ public class AdServiceImpl implements AdService {
         return Result.resultOk(RepMessage.SAVE_SUCCESS);
     }
 
+    /**
+     * 保存记录
+     *  始终创建新的事务以保障子方法的独立事务
+     */
+    @Override
+    public String saveRecordAndChangeUser(DyzAdRecordParam param, YtDyzUser user) {
+        //增加广告记录
+        handleParam(param);
+        String recordId = IdUtil.fastSimpleUUID();
+        YtDyzAdRecord adRecord = new YtDyzAdRecord();
+        BeanUtils.copyProperties(param, adRecord);
+        adRecord.setRecordId(recordId);
+        adRecord.setIosId(param.getIosId());
+        adRecord.setNetworkName(AdPlatformTypeEnum.getDesc(Integer.parseInt(param.getNetworkFormId())));
+        if (user == null) {
+            adRecord.setAppId(appId);
+            adRecordMapper.addOneVisitor(adRecord);
+        } else {
+            adRecord.setAppId(user.getAppId());
+            adRecord.setUserId(user.getUserId());
+            adRecordMapper.addOne(adRecord);
+            if (param.getRevenue() == null) {
+                param.setRevenue(BigDecimal.ZERO);
+            }
+            appUserMapper.updateTotal(user.getUserId(), 1, param.getRevenue());
+        }
+        return recordId;
+    }
+
     /**
      * 统一处理入参时间
      */
     private void handleParam(DyzAdRecordParam param){
         String timeFormat = "yyyy-MM-dd HH:mm:ss";
         if (param.getBegintimestamp() != null && param.getFinishtimestamp() != null) {
-            // 处理 begintimestamp(兼容秒级和毫秒级)
             long beginTimestamp = param.getBegintimestamp();
             if (String.valueOf(beginTimestamp).length() == 10) { // 秒级时间戳(10位)
                 beginTimestamp *= 1000; // 转为毫秒级
             }
             param.setBeginTime(DateUtil.format(new Date(beginTimestamp), timeFormat));
-
-            // 处理 finishtimestamp(兼容秒级和毫秒级)
             long finishTimestamp = param.getFinishtimestamp();
             if (String.valueOf(finishTimestamp).length() == 10) { // 秒级时间戳(10位)
                 finishTimestamp *= 1000; // 转为毫秒级
@@ -145,37 +169,6 @@ public class AdServiceImpl implements AdService {
         }
     }
 
-    /**
-     * 保存记录
-     *  始终创建新的事务以保障子方法的独立事务
-     */
-//    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
-    public void saveRecordAndChangeUser(DyzAdRecordParam param, YtDyzUser user) {
-        //增加广告记录
-        //修改用户信息, 广告次数+1  总收益 + revenue
-//        YtDyzUser dyzUser = new YtDyzUser();
-//        dyzUser.setUserId(user.getUserId());
-//        dyzUser.setTotalVideo(Objects.isNull(user.getTotalVideo())?1:(user.getTotalVideo()+1));
-//        dyzUser.setTotalIncome(user.getTotalIncome().add(param.getRevenue()));
-//        appUserMapper.updateUser(dyzUser);
-        YtDyzAdRecord adRecord = new YtDyzAdRecord();
-        handleParam(param);
-        BeanUtils.copyProperties(param, adRecord);
-        adRecord.setRecordId(IdUtil.fastSimpleUUID());
-        adRecord.setIosId(param.getIosId());
-        adRecord.setNetworkName(AdPlatformTypeEnum.getDesc(Integer.parseInt(param.getNetworkFormId())));
-        if (user == null) {
-            adRecord.setAppId(appId);
-            adRecordMapper.addOneVisitor(adRecord);
-        } else {
-            adRecord.setUserId(user.getUserId());
-            adRecordMapper.addOne(adRecord);
-            if (param.getRevenue() == null) {
-                param.setRevenue(BigDecimal.ZERO);
-            }
-            appUserMapper.updateTotal(user.getUserId(), 1, param.getRevenue());
-        }
-    }
 
     private String getTipsMsg(){
         String[] split = tips.split(",");

+ 182 - 193
yt-ios-lemon/lemon-ios-service/src/main/java/com/ytpm/lemonios/service/impl/AppUserServiceImpl.java

@@ -6,8 +6,14 @@ import cn.hutool.core.util.RandomUtil;
 import cn.hutool.core.util.StrUtil;
 import com.ytpm.agent.enums.UserStatusEnum;
 import com.ytpm.agent.model.YtDitch;
-import com.ytpm.app.model.*;
+import com.ytpm.app.enums.LoginType;
+import com.ytpm.app.model.YtAppDefaultConfig;
+import com.ytpm.app.model.YtDyzAnswerRecord;
+import com.ytpm.app.model.YtDyzLoginRecord;
+import com.ytpm.app.model.YtDyzPowerRecord;
+import com.ytpm.app.model.YtDyzUser;
 import com.ytpm.app.param.IosLoginParam;
+import com.ytpm.app.param.LoginParam;
 import com.ytpm.app.param.WxLoginParam;
 import com.ytpm.app.view.IosUserInfo;
 import com.ytpm.app.view.WxDefaultConfig;
@@ -23,13 +29,13 @@ import com.ytpm.lemonios.dao.LoginRecordMapper;
 import com.ytpm.lemonios.dao.QuestionMapper;
 import com.ytpm.lemonios.redis.RedisService;
 import com.ytpm.lemonios.service.AppUserService;
-import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.cloud.context.config.annotation.RefreshScope;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Propagation;
 import org.springframework.transaction.annotation.Transactional;
 
+import javax.annotation.Resource;
 import java.math.BigDecimal;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
@@ -41,18 +47,21 @@ import java.util.Objects;
 @RefreshScope
 public class AppUserServiceImpl implements AppUserService {
 
-    @Autowired
+    @Resource
     private AppUserMapper appUserMapper;
-    @Autowired
+    @Resource
     private LoginRecordMapper loginRecordMapper;
-    @Autowired
+    @Resource
     private QuestionMapper questionMapper;
-    @Autowired
+    @Resource
     private RedisService redisService;
+    @Resource
+    private DitchMapper ditchMapper;
+
     @Value("${risk.config.banned.tips}")
     private String tips;
-    @Autowired
-    private DitchMapper ditchMapper;
+    @Value("${yt.ios.appid:}")
+    private String appId;
 
     /**
      * openid查询用户信息
@@ -67,91 +76,103 @@ public class AppUserServiceImpl implements AppUserService {
     public YtDyzUser crudForNewTrans(WxLoginParam param, WxUserInfo wxUserInfo, WxLoginResult loginResult) {
         //处理用户注册或登录更新信息
         YtDyzUser old = appUserMapper.getYtAppUser(loginResult.getOpenid(), param.getDitchId());
-        if(Objects.isNull(old)) {
-            old = new YtDyzUser();
-            registryUser(param,wxUserInfo,loginResult, old);
-        }else{
-            deadWithUserCrud(old,wxUserInfo,param);
+        if (Objects.isNull(old)) {
+            old = registryUserByWx(param, wxUserInfo, loginResult);
+        } else {
+            deadWithUserCrud(old, wxUserInfo, param);
         }
         //设置最后一次答题问题ID、今日答题数、历史答题数
         setExtInfo(old,wxUserInfo.getHeadimgurl());
         // 添加用户登录记录
-        addLoginRecord(param,old.getUserId());
+        addLoginRecord(param,old.getUserId(), LoginType.WX);
         return old;
     }
 
-    @Override
-    public YtDyzUser crudForNewTransIos(IosLoginParam param, IosUserInfo userInfo, String loginType) {
-        YtDyzUser old = appUserMapper.selectByIosId(param.getIosId());
-        if(Objects.isNull(old)) {
-            old = new YtDyzUser();
-            registryUserForIos(param,userInfo, old);
-        }else{
-            deadWithUserCrudForIos(old,userInfo,param);
-        }
-        //设置最后一次答题问题ID、今日答题数、历史答题数
-        setExtInfoForIos(old, userInfo.getHeadimgurl());
-        // 添加用户登录记录
-        addLoginRecordForIos(param,old.getUserId(), loginType);
+    /**
+     * 微信渠道 注册用户
+     */
+    private YtDyzUser registryUserByWx(WxLoginParam param, WxUserInfo wxUserInfo, WxLoginResult loginResult) {
+        YtDyzUser old = new YtDyzUser();
+        old.setUserId(redisService.getAppUserId());
+        old.setPhone(param.getPhone());
+        old.setDeviceId(param.getDeviceId());
+        old.setNickName(wxUserInfo.getNickname());
+        old.setLastLoginTime(new Date());
+        old.setRegistryTime(new Date());
+        old.setLastLoginIp(param.getLoginIp());
+        old.setLoginDays(1);
+        old.setPower(0);
+        old.setTotalVideo(0);
+        old.setTotalIncome(BigDecimal.ZERO);
+        old.setRedPacketAmount(BigDecimal.ZERO);
+        old.setRedPacketBalance(BigDecimal.ZERO);
+        old.setPointsBalance(BigDecimal.ZERO);
+        old.setPointsTotal(BigDecimal.ZERO);
+        old.setWithdrawTotal(BigDecimal.ZERO);
+        old.setSignDays(0);
+        old.setDitchId(param.getDitchId());
+        old.setAppId(param.getAppId());
+        old.setUserStatus(UserStatusEnum.NORMAL.getCode());
+        old.setWxOpenId(loginResult.getOpenid());
+        old.setHeadImg(wxUserInfo.getHeadimgurl());
+        //根据设备ID获取平台ID 获取不到再生成平台ID
+        String platformId = appUserMapper.getByDeviceId(param.getDeviceId(),wxUserInfo.getOpenid());
+        old.setPlatformId(StrUtil.isBlank(platformId)?
+                (StrConstant.PLATFORM_ID_PREFIX + IdUtil.getSnowflakeNextIdStr()):platformId);
+        appUserMapper.addOne(old);
         return old;
     }
 
-    @Override
-    public Result<?> addDefaultConfig(YtDitch param) {
-        ditchMapper.insertOne(param);
-        WxDefaultConfig lastOne = appUserMapper.getLastOne(param.getAppId());
-        YtAppDefaultConfig appDefaultConfig = new YtAppDefaultConfig();
-        appDefaultConfig.setConfigName(param.getDitchName());
-        appDefaultConfig.setDitchId(param.getDitchId().toString());
-        appDefaultConfig.setOpenId("");
-        appDefaultConfig.setSecret(lastOne.getSecret());
-        appDefaultConfig.setAppKey("");
-        appDefaultConfig.setAppType(lastOne.getAppType());
-        appDefaultConfig.setAppId(lastOne.getAppId());
-        appDefaultConfig.setCanUseRoot(lastOne.getCanUseRoot());
-        appDefaultConfig.setCanUseAdb(lastOne.getCanUseAdb());
-        appDefaultConfig.setCanAccumulation(lastOne.getCanAccumulation());
-        appDefaultConfig.setCanSimulator(lastOne.getCanSimulator());
-        appDefaultConfig.setPowerWaitTime(lastOne.getPowerWaitTime());
-        appDefaultConfig.setInterstitialIntervalTime(lastOne.getInterstitialIntervalTime());
-        appUserMapper.saveAppConfig(appDefaultConfig);
-        return Result.resultOk(RepMessage.ADD_SUCCESS);
-    }
 
-    @Override
-    public void addPower(String userId) {
-        appUserMapper.addOnePower(userId);
-        YtDyzPowerRecord record = new YtDyzPowerRecord();
-        record.setUserId(userId);
-        record.setRecordId(IdUtil.fastSimpleUUID());
-        record.setAddTime(new Date());
-        record.setType(2);
-        record.setRemark("增加体力");
-        appUserMapper.addPowerRecord(record);
+    /**
+     * 处理用户数据
+     */
+    private void deadWithUserCrud(YtDyzUser old, WxUserInfo wxUserInfo, LoginParam param) {
+        //处于风控状态的用户不允许登录
+        if(!UserStatusEnum.NORMAL.getCode().equals(old.getUserStatus())
+                && !UserStatusEnum.VISITOR_LOCK.getCode().equals(old.getUserStatus())){
+            throw new CustomerException(getTipsMsg());
+        }
+        YtDyzUser newUser = new YtDyzUser();
+        newUser.setUserId(old.getUserId());
+        newUser.setNickName(wxUserInfo.getNickname());
+        newUser.setHeadImg(wxUserInfo.getHeadimgurl());
+        newUser.setLastLoginTime(new Date());
+        newUser.setLastLoginIp(param.getLoginIp());
+        newUser.setPhone(param.getPhone());
+        newUser.setDeviceId(param.getDeviceId());
+        setNewLoginDays(newUser, old);
+        appUserMapper.updateUser(newUser);
     }
 
+
     /**
-     * 设置扩展信息
+     * 更新登陆天数
      */
-    private void setExtInfo(YtDyzUser old, String headimgurl) {
-        old.setHeadImg(headimgurl);
-            old.setLastQuestionId(questionMapper.getLastQuestionId(old.getUserId()));
-        old.setTodayAnswerCount(questionMapper.getAnswerCount(old.getUserId(),1));
-        old.setHistoryAnswerCount(questionMapper.getAnswerCount(old.getUserId(),2));
-        old.setAnswerRecordList(questionMapper.getAnswerRecords(old.getUserId()));
-        old.setLoginRecordList(loginRecordMapper.getLoginRecords(old.getUserId()));
+    private void setNewLoginDays(YtDyzUser newUser, YtDyzUser dyzUser) {
+        YtDyzLoginRecord wxLoginRecord = loginRecordMapper.getLastLoginRecord(dyzUser.getUserId(), 0);
+        YtDyzLoginRecord visitorLoginRecord = loginRecordMapper.getLastLoginRecord(dyzUser.getUserId(), 1);
+        if (wxLoginRecord == null && visitorLoginRecord == null
+                || wxLoginRecord != null && wxLoginRecord.getLoginTime() != null
+                && DateUtil.compare(wxLoginRecord.getLoginTime(), newUser.getLastLoginTime(), "yyyy-MM-dd") < 0) {
+            newUser.setLoginDays(dyzUser.getLoginDays() + 1);
+        }
     }
 
+
     /**
      * 设置扩展信息
      */
-    private void setExtInfoForIos(YtDyzUser old, String headimgurl) {
-        old.setHeadImg(headimgurl);
+    private void setExtInfo(YtDyzUser old, String headImgUrl) {
+        old.setHeadImg(headImgUrl);
         old.setLastQuestionId(questionMapper.getLastQuestionId(old.getUserId()));
         old.setTodayAnswerCount(questionMapper.getAnswerCount(old.getUserId(),1));
         old.setHistoryAnswerCount(questionMapper.getAnswerCount(old.getUserId(),2));
+        old.setAnswerRecordList(questionMapper.getAnswerRecords(old.getUserId()));
+        old.setLoginRecordList(loginRecordMapper.getLoginRecords(old.getUserId()));
+        // 构建答题历史记录简易版
         List<YtDyzAnswerRecord> recordList = questionMapper.getAnswerRecords(old.getUserId());
-        List<String> viewList  = new ArrayList<>();
+        List<String> viewList = new ArrayList<>();
         int count = recordList.size();
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
         for (YtDyzAnswerRecord ytDyzAnswerRecord : recordList) {
@@ -160,31 +181,13 @@ public class AppUserServiceImpl implements AppUserService {
             viewList.add(timeStr);
         }
         old.setAnswerRecordTimeList(viewList);
-        old.setAnswerRecordList(questionMapper.getAnswerRecords(old.getUserId()));
-        old.setLoginRecordList(loginRecordMapper.getLoginRecords(old.getUserId()));
     }
 
-    /**
-     * 增加用户登录记录
-     */
-    private void addLoginRecord(WxLoginParam param,String userId) {
-        YtDyzLoginRecord loginRecord = new YtDyzLoginRecord();
-        loginRecord.setRecordId(IdUtil.fastSimpleUUID());
-        loginRecord.setUserId(userId);
-        loginRecord.setLoginTime(new Date());
-        loginRecord.setDeviceBrand(param.getBrand());
-        loginRecord.setDeviceModel(param.getModel());
-        loginRecord.setLoginIp(param.getLoginIp());
-        loginRecord.setOperator(param.getIpOperator());
-        loginRecord.setIpAddr(param.getIpLocation());
-        loginRecord.setPhoneJson(param.getPhoneJson());
-        loginRecordMapper.insertOne(loginRecord);
-    }
 
     /**
      * 增加用户登录记录
      */
-    private void addLoginRecordForIos(IosLoginParam param,String userId, String loginType) {
+    private void addLoginRecord(LoginParam param, String userId, LoginType loginType) {
         YtDyzLoginRecord loginRecord = new YtDyzLoginRecord();
         loginRecord.setRecordId(IdUtil.fastSimpleUUID());
         loginRecord.setUserId(userId);
@@ -195,114 +198,33 @@ public class AppUserServiceImpl implements AppUserService {
         loginRecord.setOperator(param.getIpOperator());
         loginRecord.setIpAddr(param.getIpLocation());
         loginRecord.setPhoneJson(param.getPhoneJson());
-        loginRecord.setLoginType(loginType);
+        loginRecord.setLoginType(loginType.getTypeName());
         loginRecordMapper.insertOne(loginRecord);
     }
 
-    private String getTipsMsg(){
-        String[] split = tips.split(",");
-        return split[RandomUtil.randomInt(split.length)];
-    }
-    /**
-     * 处理用户数据
-     */
-    private void deadWithUserCrud(YtDyzUser old, WxUserInfo wxUserInfo, WxLoginParam param) {
-        //处于风控状态的用户不允许登录
-        if(!old.getUserStatus().equals(UserStatusEnum.NORMAL.getCode())){
-            throw new CustomerException(getTipsMsg());
-        }
-        YtDyzUser newUser = new YtDyzUser();
-        newUser.setUserId(old.getUserId());
-        newUser.setNickName(wxUserInfo.getNickname());
-        newUser.setHeadImg(wxUserInfo.getHeadimgurl());
-        newUser.setLastLoginTime(new Date());
-        newUser.setLastLoginIp(param.getLoginIp());
-        newUser.setPhone(param.getPhone());
-        newUser.setDeviceId(param.getDeviceId());
-        YtDyzLoginRecord wxLoginRecord = loginRecordMapper.getLastLoginRecord(old.getUserId(), 0);
-        YtDyzLoginRecord visitorLoginRecord = loginRecordMapper.getLastLoginRecord(old.getUserId(), 1);
-        if (wxLoginRecord == null && visitorLoginRecord == null
-                || wxLoginRecord != null && wxLoginRecord.getLoginTime() != null
-                && DateUtil.compare(wxLoginRecord.getLoginTime(), newUser.getLastLoginTime(), "yyyy-MM-dd") < 0) {
-            newUser.setLoginDays(old.getLoginDays() + 1);
-        }
-        appUserMapper.updateUser(newUser);
-    }
 
-    /**
-     * 处理用户数据
-     */
-    private void deadWithUserCrudForIos(YtDyzUser old, IosUserInfo userInfo, IosLoginParam param) {
-        //处于风控状态的用户不允许登录
-        if(!old.getUserStatus().equals(UserStatusEnum.NORMAL.getCode())){
-            throw new CustomerException(getTipsMsg());
-        }
-        YtDyzUser newUser = new YtDyzUser();
-        if (old.getDitchId() == null) {
-            newUser.setDitchId(param.getDitchId());
-            YtDitch ditch = ditchMapper.selectById(param.getDitchId());
-            newUser.setAppId(ditch.getAppId());
-        }
-        if (param.getDitchId() != null){
-            newUser.setDitchId(param.getDitchId());
-            YtDitch ditch = ditchMapper.selectById(param.getDitchId());
-            newUser.setAppId(ditch.getAppId());
-        }
 
-        newUser.setUserId(old.getUserId());
-        newUser.setNickName(userInfo.getNickname());
-        newUser.setHeadImg(userInfo.getHeadimgurl());
-        newUser.setLastLoginTime(new Date());
-        newUser.setLastLoginIp(param.getLoginIp());
-        newUser.setPhone(param.getPhone());
-        newUser.setDeviceId(param.getDeviceId());
-        YtDyzLoginRecord wxLoginRecord = loginRecordMapper.getLastLoginRecord(old.getUserId(), 0);
-        YtDyzLoginRecord visitorLoginRecord = loginRecordMapper.getLastLoginRecord(old.getUserId(), 1);
-        if (wxLoginRecord == null && visitorLoginRecord == null
-                || wxLoginRecord != null && wxLoginRecord.getLoginTime() != null
-                && DateUtil.compare(wxLoginRecord.getLoginTime(), newUser.getLastLoginTime(), "yyyy-MM-dd") < 0) {
-            newUser.setLoginDays(old.getLoginDays() + 1);
+    @Override
+    public YtDyzUser crudForNewTransIos(IosLoginParam param, IosUserInfo userInfo, LoginType loginType) {
+        YtDyzUser old = appUserMapper.selectByIosId(param.getIosId());
+        if (Objects.isNull(old)) {
+            old = registryUserByIos(param, userInfo);
+        } else {
+            deadWithUserByIos(old, userInfo, param);
         }
-        appUserMapper.updateUser(newUser);
+        //设置最后一次答题问题ID、今日答题数、历史答题数
+        setExtInfo(old, userInfo.getHeadimgurl());
+        // 添加用户登录记录
+        addLoginRecord(param,old.getUserId(), loginType);
+        return old;
     }
 
-    /**
-     * 注册用户
-     */
-    private void registryUser(WxLoginParam param,WxUserInfo wxUserInfo,WxLoginResult loginResult, YtDyzUser old) {
-        old.setUserId(redisService.getAppUserId());
-        old.setPhone(param.getPhone());
-        old.setDeviceId(param.getDeviceId());
-        old.setNickName(wxUserInfo.getNickname());
-        old.setLastLoginTime(new Date());
-        old.setRegistryTime(new Date());
-        old.setLastLoginIp(param.getLoginIp());
-        old.setLoginDays(1);
-        old.setPower(0);
-        old.setTotalVideo(0);
-        old.setTotalIncome(BigDecimal.ZERO);
-        old.setRedPacketAmount(BigDecimal.ZERO);
-        old.setRedPacketBalance(BigDecimal.ZERO);
-        old.setPointsBalance(BigDecimal.ZERO);
-        old.setPointsTotal(BigDecimal.ZERO);
-        old.setWithdrawTotal(BigDecimal.ZERO);
-        old.setDitchId(param.getDitchId());
-        old.setSignDays(0);
-        old.setAppId(param.getAppId());
-        old.setUserStatus(UserStatusEnum.NORMAL.getCode());
-        old.setWxOpenId(loginResult.getOpenid());
-        old.setHeadImg(wxUserInfo.getHeadimgurl());
-        //根据设备ID获取平台ID 获取不到再生成平台ID
-        String platformId = appUserMapper.getByDeviceId(param.getDeviceId(),wxUserInfo.getOpenid());
-        old.setPlatformId(StrUtil.isBlank(platformId)?
-                (StrConstant.PLATFORM_ID_PREFIX + IdUtil.getSnowflakeNextIdStr()):platformId);
-        appUserMapper.addOne(old);
-    }
 
     /**
      * 注册用户
      */
-    private void registryUserForIos(IosLoginParam param,IosUserInfo userInfo, YtDyzUser old) {
+    private YtDyzUser registryUserByIos(IosLoginParam param, IosUserInfo userInfo) {
+        YtDyzUser old = new YtDyzUser();
         old.setUserId(redisService.getAppUserId());
         old.setPhone(param.getPhone());
         old.setDeviceId(param.getDeviceId());
@@ -321,22 +243,89 @@ public class AppUserServiceImpl implements AppUserService {
         old.setWithdrawTotal(BigDecimal.ZERO);
         old.setDitchId(param.getDitchId());
         old.setSignDays(0);
-        YtDitch ditch;
-        if (param.getDitchId() == null){
-            old.setDitchId(2025062500193L);
-            old.setAppId("251be4dff0fd408fbc1fe2c47bf515eb");
-        } else {
-            ditch = ditchMapper.selectById(param.getDitchId());
-            old.setDitchId(param.getDitchId());
-            old.setAppId(ditch.getAppId());
-        }
         old.setUserStatus(UserStatusEnum.NORMAL.getCode());
         old.setIosId(param.getIosId());
         old.setHeadImg(userInfo.getHeadimgurl());
+        old.setAppId(appId);
+        if (param.getDitchId() != null){
+            YtDitch ditch = ditchMapper.selectById(param.getDitchId());
+            old.setDitchId(param.getDitchId());
+            old.setAppId(ditch.getAppId());
+        }
         //根据设备ID获取平台ID 获取不到再生成平台ID
         String platformId = appUserMapper.getByDeviceId(param.getDeviceId(),userInfo.getOpenid());
         old.setPlatformId(StrUtil.isBlank(platformId)?
                 (StrConstant.PLATFORM_ID_PREFIX + IdUtil.getSnowflakeNextIdStr()):platformId);
         appUserMapper.addOne(old);
+        return old;
     }
+
+    /**
+     * 处理用户数据
+     */
+    private void deadWithUserByIos(YtDyzUser dyzUser, IosUserInfo userInfo, LoginParam param) {
+        //处于风控状态的用户不允许登录
+        if(!UserStatusEnum.NORMAL.getCode().equals(dyzUser.getUserStatus())
+                && !UserStatusEnum.VISITOR_LOCK.getCode().equals(dyzUser.getUserStatus())){
+            throw new CustomerException(getTipsMsg());
+        }
+        YtDyzUser newUser = new YtDyzUser();
+        newUser.setNickName(userInfo.getNickname());
+        newUser.setHeadImg(userInfo.getHeadimgurl());
+        newUser.setLastLoginTime(new Date());
+        newUser.setLastLoginIp(param.getLoginIp());
+        newUser.setPhone(param.getPhone());
+        newUser.setDeviceId(param.getDeviceId());
+        // 更新用户渠道信息
+        if (param.getDitchId() != null){
+            newUser.setDitchId(param.getDitchId());
+            YtDitch ditch = ditchMapper.selectById(param.getDitchId());
+            newUser.setAppId(ditch.getAppId());
+        }
+        setNewLoginDays(newUser, dyzUser);
+        appUserMapper.updateUser(newUser);
+    }
+
+
+    @Override
+    public Result<?> addDefaultConfig(YtDitch param) {
+        ditchMapper.insertOne(param);
+        WxDefaultConfig lastOne = appUserMapper.getLastOne(param.getAppId());
+        YtAppDefaultConfig appDefaultConfig = new YtAppDefaultConfig();
+        appDefaultConfig.setConfigName(param.getDitchName());
+        appDefaultConfig.setDitchId(param.getDitchId().toString());
+        appDefaultConfig.setOpenId("");
+        appDefaultConfig.setSecret(lastOne.getSecret());
+        appDefaultConfig.setAppKey("");
+        appDefaultConfig.setAppType(lastOne.getAppType());
+        appDefaultConfig.setAppId(lastOne.getAppId());
+        appDefaultConfig.setCanUseRoot(lastOne.getCanUseRoot());
+        appDefaultConfig.setCanUseAdb(lastOne.getCanUseAdb());
+        appDefaultConfig.setCanAccumulation(lastOne.getCanAccumulation());
+        appDefaultConfig.setCanSimulator(lastOne.getCanSimulator());
+        appDefaultConfig.setPowerWaitTime(lastOne.getPowerWaitTime());
+        appDefaultConfig.setInterstitialIntervalTime(lastOne.getInterstitialIntervalTime());
+        appUserMapper.saveAppConfig(appDefaultConfig);
+        return Result.resultOk(RepMessage.ADD_SUCCESS);
+    }
+
+    @Override
+    public void addPower(String userId) {
+        appUserMapper.addOnePower(userId);
+        YtDyzPowerRecord record = new YtDyzPowerRecord();
+        record.setUserId(userId);
+        record.setRecordId(IdUtil.fastSimpleUUID());
+        record.setAddTime(new Date());
+        record.setType(2);
+        record.setRemark("增加体力");
+        appUserMapper.addPowerRecord(record);
+    }
+
+
+    private String getTipsMsg(){
+        String[] split = tips.split(",");
+        return split[RandomUtil.randomInt(split.length)];
+    }
+
+
 }

+ 0 - 1
yt-ios-lemon/lemon-ios-service/src/main/java/com/ytpm/lemonios/service/impl/QuestionServiceImpl.java

@@ -23,7 +23,6 @@ import org.springframework.transaction.annotation.Transactional;
 
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.Date;
 import java.util.List;
 import java.util.Objects;

+ 12 - 0
yt-ios-lemon/lemon-ios-service/src/main/resources/mapper/AdRecordMapper.xml

@@ -257,4 +257,16 @@
             and finish_time > #{startTime}
         </if>
     </select>
+    <select id="selectRecordByIds" resultType="com.ytpm.app.model.YtDyzAdRecord">
+        select
+        record_id, user_id, app_id, nick_name, placement_id, ad_source_id, ad_source_type, ad_source_index,
+        revenue, ecpm, network_form_id, network_name, network_placement_id, finish_time, begin_time, result_json
+        <if test="loginStatus != null and loginStatus == 1">
+            from yt_dyz_ad_record_visitor
+        </if>
+        <if test="loginStatus == null or loginStatus != 1">
+            from yt_dyz_ad_record
+        </if>
+        where record_id in <foreach collection="ids" item="id" open="(" close=")" separator=",">#{id}</foreach>
+    </select>
 </mapper>

+ 1 - 0
yt-ios-lemon/lemon-ios-service/src/main/resources/mapper/AppUserMapper.xml

@@ -282,6 +282,7 @@
             user_id, app_id,phone,device_id, ditch_id, nick_name,head_img, power, registry_time, last_login_time, last_login_ip, login_days, total_video, total_income, red_packet_balance, red_packet_amount, points_balance, points_total, withdraw_total, sign_days, user_status, risk_reason, wx_open_id, ios_id, platform_id
         from yt_dyz_user
         where ios_id = #{iosId}
+
         Limit 1
     </select>
     <select id="getYtAppUserForIos" resultType="com.ytpm.app.model.YtDyzUser">