浏览代码

Merge remote-tracking branch 'origin/V1.1.3' into V1.1.3

syh 4 年之前
父节点
当前提交
6d44d14c37
共有 32 个文件被更改,包括 983 次插入118 次删除
  1. 1 1
      jeecg-boot-module-system/src/main/java/org/jeecg/config/ShiroConfig.java
  2. 1 3
      jeecg-boot-module-system/src/main/java/org/jeecg/modules/ctop/controller/BindAccountAuthController.java
  3. 9 10
      jeecg-boot-module-system/src/main/java/org/jeecg/modules/ctop/controller/CallbackController.java
  4. 126 2
      jeecg-boot-module-system/src/main/java/org/jeecg/modules/ctop/controller/TestController.java
  5. 31 2
      jeecg-boot-module-system/src/test/java/org/jeecg/SampleTest.java
  6. 7 9
      module-common/src/main/java/cn/com/ctop/common/module/controller/OauthConfigController.java
  7. 1 0
      module-common/src/main/java/cn/com/ctop/common/module/entity/CtopOauthToken.java
  8. 11 6
      module-common/src/main/java/cn/com/ctop/common/module/entity/OauthConfig.java
  9. 8 0
      module-common/src/main/java/cn/com/ctop/common/module/mapper/OauthConfigMapper.java
  10. 2 1
      module-common/src/main/java/cn/com/ctop/common/module/mapper/xml/CtopOauthTokenMapper.xml
  11. 14 0
      module-common/src/main/java/cn/com/ctop/common/module/mapper/xml/OauthConfigMapper.xml
  12. 4 1
      module-common/src/main/java/cn/com/ctop/common/module/service/IBindAccountAuthService.java
  13. 1 1
      module-common/src/main/java/cn/com/ctop/common/module/service/ICtopOauthTokenService.java
  14. 5 0
      module-common/src/main/java/cn/com/ctop/common/module/service/IOauthConfigService.java
  15. 21 15
      module-common/src/main/java/cn/com/ctop/common/module/service/impl/BindAccountAuthServiceImpl.java
  16. 4 10
      module-common/src/main/java/cn/com/ctop/common/module/service/impl/CtopOauthTokenServiceImpl.java
  17. 33 0
      module-common/src/main/java/cn/com/ctop/common/module/service/impl/OauthConfigServiceImpl.java
  18. 9 1
      module-common/src/main/java/cn/com/ctop/common/module/service/impl/RefreshTokenServiceImpl.java
  19. 2 2
      module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/controller/KuaishouBatchCampaignPreviewController.java
  20. 23 2
      module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/controller/KuaishouBatchCreativePreviewController.java
  21. 2 3
      module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/controller/KuaishouBatchGroupPreviewController.java
  22. 25 0
      module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/controller/KuaishouTemplateController.java
  23. 20 0
      module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/entity/KuaishouBatchCampaignPreview.java
  24. 23 0
      module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/entity/KuaishouBatchCreativePreview.java
  25. 24 0
      module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/entity/KuaishouBatchGroupPreview.java
  26. 2 0
      module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/service/IKuaishouBatchCreativePreviewService.java
  27. 3 12
      module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/service/IKuaishouInterfaceService.java
  28. 0 1
      module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/service/IKuaishouTemplateService.java
  29. 97 21
      module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/service/impl/KuaishouBatchCampaignPreviewServiceImpl.java
  30. 457 0
      module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/service/impl/KuaishouBatchCreativePreviewServiceImpl.java
  31. 10 10
      module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/service/impl/KuaishouInterfaceServiceImpl.java
  32. 7 5
      module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/service/impl/KuaishouTemplateServiceImpl.java

+ 1 - 1
jeecg-boot-module-system/src/main/java/org/jeecg/config/ShiroConfig.java

@@ -185,7 +185,7 @@ public class ShiroConfig {
         filterChainDefinitionMap.put("/kuaishou/create/*", "anon");
         filterChainDefinitionMap.put("/template/**", "anon");
         filterChainDefinitionMap.put("/batch/kuaiShouGroupTemplate/*", "anon");
-        filterChainDefinitionMap.put("/kuaishouBatchCampaignPreview/*", "anon");
+        filterChainDefinitionMap.put("/kuaishouBatch/**", "anon");
 
         // 添加自己的过滤器并且取名为jwt
         Map<String, Filter> filterMap = new HashMap<>(1);

+ 1 - 3
jeecg-boot-module-system/src/main/java/org/jeecg/modules/ctop/controller/BindAccountAuthController.java

@@ -54,10 +54,8 @@ public class BindAccountAuthController {
             }
 
             String authorizationType = json.getString("authorizationType");
-            // 0 三方代理商 1 本代理商
-            Integer agentType = json.getInteger("agentType");
             if ("kuaishou".equals(authorizationType)) {
-                codeUrl = bindAccountAuthService.getKuaishouCodeUrl(json.toJSONString(), agentType);
+                codeUrl = bindAccountAuthService.getKuaishouCodeUrl(json);
             }
             if ("bytedance".equals(authorizationType)) {
                 codeUrl = bindAccountAuthService.getByteDanceCodeUrl(json.toJSONString());

+ 9 - 10
jeecg-boot-module-system/src/main/java/org/jeecg/modules/ctop/controller/CallbackController.java

@@ -119,8 +119,9 @@ public class CallbackController {
             log.info("快手授权返回信息:{}", json);
             log.info("快手授权返回oauthCode:{}", authCode);
             Integer agentType = json.getInteger("agentType");
+            Long appId = json.getLong("appId");
             if (StringUtils.isNotBlank(authCode)) {
-                KuaishouResultToken accessToken = kuaishouInterfaceService.getAccessToken(authCode, agentType);
+                KuaishouResultToken accessToken = kuaishouInterfaceService.getAccessToken(authCode, appId);
                 if (accessToken.getCode() != 0) {
                     throw new Exception("快手回调token返回错误");
                 }
@@ -131,11 +132,14 @@ public class CallbackController {
                         return "授权绑定失败!";
                     }
 
+                    Map<String, Object> advertiseBaseInfoMap = kuaishouInterfaceService.advertiserInfo(accountId, token.getAccessToken());
+                    if ((Integer) advertiseBaseInfoMap.get("code") != 0) {
+                        return "授权绑定失败,失败原因:" + advertiseBaseInfoMap.get("message");
+                    }
                     String advertiserId = json.getString("advertiserId");
                     //指定分配人姓名
                     String userName = json.getString("userName");
-                    // 广告主名称
-                    String advertiserName = json.getString("advertiser_name");
+
                     // 媒体类型: 1 头条 2 快手
                     String mediaId = json.getString("mediaId");
                     //创建人
@@ -147,6 +151,7 @@ public class CallbackController {
 
                     CtopOauthToken topOauthToken = new CtopOauthToken();
                     topOauthToken.setId(String.valueOf(accountId));
+                    topOauthToken.setAppId(json.getLong("appId"));
                     topOauthToken.setAccountId(accountId);
                     topOauthToken.setMediaId("2");
                     topOauthToken.setAdvertiserId(advertiserId);
@@ -162,8 +167,6 @@ public class CallbackController {
                     topOauthToken.setRefreshTokenExpiresIn(refreshTokenExpireInDate);
                     topOauthToken.setUpdateTime(new Date());
                     ctopOauthTokenService.saveOrUpdate(topOauthToken);
-
-
                     QueryWrapper<UserAllocation> userAllocationQueryWrapper = new QueryWrapper<>();
                     userAllocationQueryWrapper.eq("account_id", accountId);
                     userAllocationQueryWrapper.eq("media_id", 2);
@@ -179,10 +182,7 @@ public class CallbackController {
                     userAllocation.setAdvertiserId(advertiserId);
                     userAllocation.setSystemType(systemType);
                     // 获取快手昵称
-                    Map<String, Object> advertiseBaseInfoMap = kuaishouInterfaceService.advertiserInfo(accountId, token.getAccessToken());
-                    if ((Integer) advertiseBaseInfoMap.get("code") == 0) {
-                        userAllocation.setAuthName((String) advertiseBaseInfoMap.get("userName"));
-                    }
+                    userAllocation.setAuthName((String) advertiseBaseInfoMap.get("userName"));
                     userAllocation.setMediaId(mediaId);
                     userAllocation.setAccountId(accountId);
                     userAllocation.setProjectId(projectId);
@@ -199,7 +199,6 @@ public class CallbackController {
                     if (i > 0) {
                         log.info("同步分配用户表完成,task_id:{},accountId:{}", state, accountId);
                     }
-
                     //账号绑定
                     bindAccountAuthService.addBindAccount(accountId, KuaishouInterfaceConstant.LOGIN_TYPE_KUAISHOU, advertiserId);
                     Thread t = new Thread() {

+ 126 - 2
jeecg-boot-module-system/src/main/java/org/jeecg/modules/ctop/controller/TestController.java

@@ -2,6 +2,7 @@ package org.jeecg.modules.ctop.controller;
 
 import cn.com.ctop.common.module.entity.*;
 import cn.com.ctop.common.module.mapper.CtopOauthTokenMapper;
+import cn.com.ctop.common.module.mapper.UserAllocationMapper;
 import cn.com.ctop.common.module.service.*;
 import cn.com.ctop.common.module.utils.*;
 import cn.com.ctop.common.module.vo.ResFileDTO;
@@ -11,6 +12,8 @@ import cn.com.ctop.crawler.modules.douyin.service.DouyinMusicService;
 import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouTemplate;
 import cn.com.ctop.kuaishou.modules.batch.service.*;
 import cn.com.ctop.kuaishou.modules.graphql.service.IKuaishouWebInterfaceService;
+import cn.com.ctop.kuaishou.modules.material.entity.KuaishouAccessToken;
+import cn.com.ctop.kuaishou.modules.material.entity.KuaishouResultToken;
 import cn.com.ctop.kuaishou.modules.report.service.IKuaiShouDailyAgentService;
 import cn.com.ctop.toutiao.modules.material.service.IByteDanceAdvertiserDataService;
 import cn.com.ctop.toutiao.modules.material.service.IBytedanceEffectVideoInfoService;
@@ -29,11 +32,15 @@ import org.quartz.JobExecutionException;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.GetMapping;
 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 javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
 import java.io.InputStream;
+import java.math.BigDecimal;
 import java.text.ParseException;
 import java.text.SimpleDateFormat;
 import java.util.*;
@@ -102,6 +109,123 @@ public class TestController {
     private IBytedanceAccountReportTaskRecordService reportTaskRecordService;
     @Resource
     private BytedanceReportMaterialDailyMapper bytedanceReportMaterialDailyMapper;
+    @Autowired
+    private ICtopOauthTokenService ctopOauthTokenService;
+
+    @Autowired
+    private IBindAccountAuthService bindAccountAuthService;
+    @Autowired
+    private UserAllocationMapper allocationMapper;
+
+    @GetMapping("/testKuaishou")
+    public String kuaishouCallback( @RequestParam("auth_code") String authCode, @RequestParam("state") String state) {
+        try {
+            JSONObject json = JSONObject.parseObject(state);
+            if (Check.isNull(json)) {
+                throw new Exception("回调信息为空");
+            }
+            log.info("快手授权返回信息:{}", json);
+            log.info("快手授权返回oauthCode:{}", authCode);
+            Integer agentType = json.getInteger("agentType");
+            Long appId = json.getLong("appId");
+            if (org.apache.commons.lang.StringUtils.isNotBlank(authCode)) {
+                KuaishouResultToken accessToken = kuaishouInterfaceService.getAccessToken(authCode, appId);
+                if (accessToken.getCode() != 0) {
+                    throw new Exception("快手回调token返回错误");
+                }
+                KuaishouAccessToken token = accessToken.getData();
+                if (token != null) {
+                    Long accountId = token.getAccountId();
+                    if (Check.isNull(accountId)) {
+                        return "授权绑定失败!";
+                    }
+                    Map<String, Object> advertiseBaseInfoMap = kuaishouInterfaceService.advertiserInfo(accountId, token.getAccessToken());
+                    if ((Integer) advertiseBaseInfoMap.get("code") != 0) {
+                        return "授权绑定失败,失败原因:" + advertiseBaseInfoMap.get("message");
+                    }
+                    String advertiserId = json.getString("advertiserId");
+                    //指定分配人姓名
+                    String userName = json.getString("userName");
+                    // 媒体类型: 1 头条 2 快手
+                    String mediaId = json.getString("mediaId");
+                    //创建人
+                    String userId = json.getString("userId");
+                    Long projectId = json.getLong("projectId");
+                    BigDecimal warningProportion = json.getBigDecimal("WarningProportion");
+                    BigDecimal warningAmount = json.getBigDecimal("WarningAmount");
+                    String systemType = json.getString("systemType");
+                    CtopOauthToken topOauthToken = new CtopOauthToken();
+                    topOauthToken.setId(String.valueOf(accountId));
+                    topOauthToken.setAppId(json.getLong("appId"));
+                    topOauthToken.setAccountId(accountId);
+                    topOauthToken.setMediaId("2");
+                    topOauthToken.setAdvertiserId(advertiserId);
+                    topOauthToken.setAgentType(agentType);
+                    topOauthToken.setAccessToken(token.getAccessToken());
+                    long accessTokenExpireIn = token.getAccessTokenExpiresIn() * 1000L;
+                    long now = System.currentTimeMillis();
+                    Date accessTokenExpireInDate = new Date(now + accessTokenExpireIn);
+                    topOauthToken.setAccessTokenExpiresIn(accessTokenExpireInDate);
+                    topOauthToken.setRefreshToken(token.getRefreshToken());
+                    long refreshTokenExpireIn = token.getRefreshTokenExpiresIn() * 1000L;
+                    Date refreshTokenExpireInDate = new Date(now + refreshTokenExpireIn);
+                    topOauthToken.setRefreshTokenExpiresIn(refreshTokenExpireInDate);
+                    topOauthToken.setUpdateTime(new Date());
+                    ctopOauthTokenService.saveOrUpdate(topOauthToken);
+                    QueryWrapper<UserAllocation> userAllocationQueryWrapper = new QueryWrapper<>();
+                    userAllocationQueryWrapper.eq("account_id", accountId);
+                    userAllocationQueryWrapper.eq("media_id", 2);
+                    userAllocationQueryWrapper.orderByDesc("create_time");
+                    userAllocationQueryWrapper.last("limit 1");
+                    UserAllocation checkUserAllocation = allocationMapper.selectOne(userAllocationQueryWrapper);
+                    if (!Check.isNull(checkUserAllocation)) {
+                        return "授权失败,该账号已被:" + checkUserAllocation.getUserName() + " 绑定!";
+                    }
+                    UserAllocation userAllocation = new UserAllocation();
+                    userAllocation.setUserName(userName);
+                    userAllocation.setUserId(userId);
+                    userAllocation.setAdvertiserId(advertiserId);
+                    userAllocation.setSystemType(systemType);
+                    // 获取快手昵称
+                    userAllocation.setAuthName((String) advertiseBaseInfoMap.get("userName"));
+                    userAllocation.setMediaId(mediaId);
+                    userAllocation.setAccountId(accountId);
+                    userAllocation.setProjectId(projectId);
+                    userAllocation.setWarningProportion(warningProportion);
+                    userAllocation.setWarningAmount(warningAmount);
+                    userAllocation.setCreateTime(new Date());
+                    userAllocation.setUpdateTime(new Date());
+                    allocationMapper.deleteById(userAllocation.getId());
+                    Map<String, Object> deleteUserMap = new HashMap<>();
+                    deleteUserMap.put("advertiser_id", advertiserId);
+                    deleteUserMap.put("account_id", accountId);
+                    allocationMapper.deleteByMap(deleteUserMap);
+                    int i = allocationMapper.insert(userAllocation);
+                    if (i > 0) {
+                        log.info("同步分配用户表完成,task_id:{},accountId:{}", state, accountId);
+                    }
+                    //账号绑定
+                    bindAccountAuthService.addBindAccount(accountId, KuaishouInterfaceConstant.LOGIN_TYPE_KUAISHOU, advertiserId);
+                    Thread t = new Thread() {
+                        @Override
+                        public void run() {
+                            try {
+                                kuaishouInterfaceService.loadKuaishouDataSingle(topOauthToken);
+                            } catch (ParseException e) {
+                                e.printStackTrace();
+                            }
+                        }
+                    };
+                    t.start();
+                }
+                return "授权绑定成功";
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return "授权绑定失败!";
+    }
+
 
     @GetMapping("/getBytedanceMatReport")
     public Map<String,Object>getData(){
@@ -710,11 +834,11 @@ public class TestController {
     }
 
 
-    @GetMapping(value = "/getToken")
+   /* @GetMapping(value = "/getToken")
     public String getToken(Long accountId, String token, String refreshToken, Integer agentType) {
         oauthTokenService.getKuaiShouRefreshToken(accountId, token, refreshToken, agentType);
         return "Success";
-    }
+    }*/
 
 
     @GetMapping(value = "/getAccountReport")

+ 31 - 2
jeecg-boot-module-system/src/test/java/org/jeecg/SampleTest.java

@@ -3,8 +3,10 @@ package org.jeecg;
 import cn.com.ctop.common.module.entity.BindAccountLogin;
 import cn.com.ctop.common.module.entity.CtopOauthToken;
 import cn.com.ctop.common.module.entity.UserAllocation;
+import cn.com.ctop.common.module.mapper.CtopOauthTokenMapper;
 import cn.com.ctop.common.module.service.IBindAccountLoginService;
 import cn.com.ctop.common.module.service.ICtopOauthTokenService;
+import cn.com.ctop.common.module.service.IOauthConfigService;
 import cn.com.ctop.common.module.service.IUserAllocationService;
 import cn.com.ctop.common.module.utils.Check;
 import cn.com.ctop.common.module.utils.CtopAdConstant;
@@ -25,6 +27,7 @@ import cn.com.ctop.toutiao.modules.report.entity.BytedanceAccountReportTaskRecor
 import cn.com.ctop.toutiao.modules.report.mapper.BytedanceReportMaterialDailyMapper;
 import cn.com.ctop.toutiao.modules.report.service.*;
 import com.alibaba.fastjson.JSONArray;
+import com.xxl.job.core.context.XxlJobHelper;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.catalina.User;
 import org.jeecg.common.util.DateUtils;
@@ -70,12 +73,38 @@ public class SampleTest {
     private IBindAccountLoginService bindAccountLoginService;
     @Autowired
     private IKuaishouWebInterfaceService kuaishouWebInterfaceService;
+    @Autowired
+    private IOauthConfigService configService;
+    @Autowired
+    private CtopOauthTokenMapper oauthTokenMapper;
 
 
     @Test
     public void loadBytedanceCreativeData() throws ParseException {
 
-        List<KuaiShouVideoGet> KuaiShouVideoGets = videoGetService.selectPhotoIdsByAccountId(9743746L);
+
+        List<CtopOauthToken> oauthTokens = oauthTokenMapper.selectKuaiShouTokens(CtopAdConstant.PLATFORM_TYPE_KUAISHOU);
+        if (!Check.isNull(oauthTokens)) {
+            Map<Long, String> configMap = configService.getConfigMapByMediaId(CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT);
+            for (CtopOauthToken oauthToken : oauthTokens) {
+                XxlJobHelper.log("刷新token,accountId:{}", oauthToken.getAccountId());
+                //快手
+                if (CtopAdConstant.PLATFORM_TYPE_KUAISHOU.equals(oauthToken.getMediaId().trim())) {
+                    String secret = configMap.get(oauthToken.getAppId());
+                    System.err.println(secret);
+                    oauthTokenService.getKuaiShouRefreshToken(oauthToken.getAccountId(), oauthToken.getAccessToken(), oauthToken.getRefreshToken(), oauthToken.getAppId(), secret);
+                }
+            }
+        } else {
+            XxlJobHelper.log("----------------------刷新token获取数据返回结果为空----------------------------------");
+        }
+
+
+      /*  Map<Long, String> configMap = configService.getConfigMapByMediaId(CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT);
+        System.err.println(configMap);*/
+
+
+      /*  List<KuaiShouVideoGet> KuaiShouVideoGets = videoGetService.selectPhotoIdsByAccountId(9743746L);
         if (!Check.isNull(KuaiShouVideoGets)) {
             JSONArray dateList = new JSONArray();
             JSONArray photoIds = new JSONArray();
@@ -96,7 +125,7 @@ public class SampleTest {
             }
             dateList.add(photoIds);
             kuaishouVideoRelateCreativesService.videoRelateCreatives(9743746L, dateList, statdateMap);
-        }
+        }*/
     }
 
     @Test

+ 7 - 9
module-common/src/main/java/cn/com/ctop/common/module/controller/OauthConfigController.java

@@ -5,8 +5,6 @@ import cn.com.ctop.common.module.entity.OauthConfig;
 import cn.com.ctop.common.module.service.IOauthConfigService;
 import com.alibaba.fastjson.JSON;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
-import com.baomidou.mybatisplus.core.metadata.IPage;
-import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 import io.swagger.annotations.Api;
 import io.swagger.annotations.ApiOperation;
 import lombok.extern.slf4j.Slf4j;
@@ -60,14 +58,14 @@ public class OauthConfigController {
     @AutoLog(value = "授权配置信息-分页列表查询")
     @ApiOperation(value = "授权配置信息-分页列表查询", notes = "授权配置信息-分页列表查询")
     @GetMapping(value = "/list")
-    public Result<IPage<OauthConfig>> queryPageList(OauthConfig oauthConfig,
-                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
-                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
-                                                    HttpServletRequest req) {
-        Result<IPage<OauthConfig>> result = new Result<>();
+    public Result<List<OauthConfig>> queryPageList(OauthConfig oauthConfig,
+                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
+                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
+                                                   HttpServletRequest req) {
+        Result<List<OauthConfig>> result = new Result<>();
         QueryWrapper<OauthConfig> queryWrapper = QueryGenerator.initQueryWrapper(oauthConfig, req.getParameterMap());
-        Page<OauthConfig> page = new Page<OauthConfig>(pageNo, pageSize);
-        IPage<OauthConfig> pageList = oauthConfigService.page(page, queryWrapper);
+        queryWrapper.orderByAsc("rank");
+        List<OauthConfig> pageList = oauthConfigService.list(queryWrapper);
         result.setSuccess(true);
         result.setResult(pageList);
         return result;

+ 1 - 0
module-common/src/main/java/cn/com/ctop/common/module/entity/CtopOauthToken.java

@@ -76,6 +76,7 @@ public class CtopOauthToken {
 
 
     private Integer agentType;
+    private Long appId;
 
     /**
      * 刷新令牌有效期

+ 11 - 6
module-common/src/main/java/cn/com/ctop/common/module/entity/OauthConfig.java

@@ -34,6 +34,9 @@ public class OauthConfig {
     @TableId(type = IdType.AUTO)
     @ApiModelProperty(value = "主键ID")
     private Long id;
+
+
+    private Integer mediaId;
     /**
      * 代理商名称
      */
@@ -58,18 +61,20 @@ public class OauthConfig {
     @Excel(name = "回调地址", width = 15)
     @ApiModelProperty(value = "回调地址")
     private String redirectUri;
-    /**
-     * 所用公司名称
-     */
-    @Excel(name = "所用公司名称", width = 15)
-    @ApiModelProperty(value = "所用公司名称")
-    private String companyName;
+
+
+    private Integer status;
+
+    private Integer oauthType;
+
     /**
      * 排序
      */
     @Excel(name = "排序", width = 15)
     @ApiModelProperty(value = "排序")
     private Integer rank;
+
+    String callbackUrl;
     /**
      * 创建时间
      */

+ 8 - 0
module-common/src/main/java/cn/com/ctop/common/module/mapper/OauthConfigMapper.java

@@ -1,7 +1,12 @@
 package cn.com.ctop.common.module.mapper;
 
 import cn.com.ctop.common.module.entity.OauthConfig;
+import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import org.apache.ibatis.annotations.Param;
+
+import java.util.List;
+import java.util.Map;
 
 /**
  * 授权配置信息
@@ -12,4 +17,7 @@ import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  */
 public interface OauthConfigMapper extends BaseMapper<OauthConfig> {
 
+    Map<Long, String> getConfigMapByMediaId(@Param("mediaId") int mediaId);
+
+    List<JSONObject> getListByMediaId(@Param("mediaId") int mediaId);
 }

+ 2 - 1
module-common/src/main/java/cn/com/ctop/common/module/mapper/xml/CtopOauthTokenMapper.xml

@@ -12,12 +12,13 @@
         <result column="access_token_expires_in" property="accessTokenExpiresIn" jdbcType="TIMESTAMP"/>
         <result column="refresh_token_expires_in" property="refreshTokenExpiresIn" jdbcType="TIMESTAMP"/>
         <result column="agent_type" property="agentType" jdbcType="INTEGER"/>
+        <result column="app_id" property="appId" jdbcType="INTEGER"/>
         <result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
         <result column="update_time" property="updateTime" jdbcType="TIMESTAMP"/>
     </resultMap>
 
     <sql id="Base_Column_List">
-        id,media_id,advertiser_id,account_id,access_token,refresh_token,access_token_expires_in,refresh_token_expires_in,agent_type,create_time,update_time
+        id,media_id,advertiser_id,account_id,access_token,refresh_token,access_token_expires_in,refresh_token_expires_in,agent_type,app_id,create_time,update_time
    </sql>
 
     <select id="selectByteDanceTokens" resultMap="BaseResultMap">

+ 14 - 0
module-common/src/main/java/cn/com/ctop/common/module/mapper/xml/OauthConfigMapper.xml

@@ -2,4 +2,18 @@
 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 <mapper namespace="cn.com.ctop.common.module.mapper.OauthConfigMapper">
 
+    <select id="getConfigMapByMediaId" resultType="map">
+       select
+       app_id,
+       secret
+       from ctop_oauth_config
+       where media_id = #{mediaId}
+    </select>
+    <select id="getListByMediaId" resultType="com.alibaba.fastjson.JSONObject">
+       select
+       app_id,
+       secret
+       from ctop_oauth_config
+       where media_id = #{mediaId}
+    </select>
 </mapper>

+ 4 - 1
module-common/src/main/java/cn/com/ctop/common/module/service/IBindAccountAuthService.java

@@ -1,6 +1,7 @@
 package cn.com.ctop.common.module.service;
 
 import cn.com.ctop.common.module.entity.BindAccountAuth;
+import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.extension.service.IService;
 
 import java.io.UnsupportedEncodingException;
@@ -20,10 +21,11 @@ public interface IBindAccountAuthService extends IService<BindAccountAuth> {
      * @return
      * @throws UnsupportedEncodingException
      */
-    String getKuaishouCodeUrl(String state,Integer  agentType ) throws UnsupportedEncodingException;
+    String getKuaishouCodeUrl(JSONObject state) throws UnsupportedEncodingException;
 
     /**
      * 获取头条url
+     *
      * @param state
      * @return
      * @throws UnsupportedEncodingException
@@ -32,6 +34,7 @@ public interface IBindAccountAuthService extends IService<BindAccountAuth> {
 
     /**
      * 绑定账号
+     *
      * @param accountId
      * @param type
      * @param state

+ 1 - 1
module-common/src/main/java/cn/com/ctop/common/module/service/ICtopOauthTokenService.java

@@ -20,7 +20,7 @@ public interface ICtopOauthTokenService extends IService<CtopOauthToken> {
 
     Map<String, Object> getByteDanceAccessToken(CtopOauthToken token);
 
-    void getKuaiShouRefreshToken(Long accountId, String token, String refreshToken, Integer agentType);
+    void getKuaiShouRefreshToken(Long accountId, String token, String refreshToken, Long appId, String secret);
 
     List<CtopOauthToken> getTokenListByType(String platformTypeBytedance);
 

+ 5 - 0
module-common/src/main/java/cn/com/ctop/common/module/service/IOauthConfigService.java

@@ -3,6 +3,8 @@ package cn.com.ctop.common.module.service;
 import cn.com.ctop.common.module.entity.OauthConfig;
 import com.baomidou.mybatisplus.extension.service.IService;
 
+import java.util.Map;
+
 /**
  * @Description: 授权配置信息
  * @Author: jeecg-boot
@@ -11,4 +13,7 @@ import com.baomidou.mybatisplus.extension.service.IService;
  */
 public interface IOauthConfigService extends IService<OauthConfig> {
 
+    OauthConfig getConfigByAppId(Long appId);
+
+    Map<Long, String> getConfigMapByMediaId(int mediaId);
 }

+ 21 - 15
module-common/src/main/java/cn/com/ctop/common/module/service/impl/BindAccountAuthServiceImpl.java

@@ -1,11 +1,14 @@
 package cn.com.ctop.common.module.service.impl;
 
 import cn.com.ctop.common.module.entity.BindAccountAuth;
+import cn.com.ctop.common.module.entity.OauthConfig;
 import cn.com.ctop.common.module.mapper.BindAccountAuthMapper;
 import cn.com.ctop.common.module.service.IBindAccountAuthService;
+import cn.com.ctop.common.module.service.IOauthConfigService;
 import cn.com.ctop.common.module.utils.BytedanceInterfaceConstant;
 import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
 import cn.com.ctop.common.module.utils.PropertiesUtils;
+import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -64,23 +67,26 @@ public class BindAccountAuthServiceImpl extends ServiceImpl<BindAccountAuthMappe
     }
 
 
+    @Autowired
+    private IOauthConfigService oauthConfigService;
+
     @Override
-    public String getKuaishouCodeUrl(String state, Integer agentType) throws UnsupportedEncodingException {
+    public String getKuaishouCodeUrl(JSONObject state) throws UnsupportedEncodingException {
         StringBuffer sb = new StringBuffer();
-        if (agentType == 1) {
-            sb.append(PropertiesUtils.getValue("kuaishou_config", "kuaishou_auth_url"))
-                    .append(KuaishouInterfaceConstant.AUTH_PATH)
-                    .append("?app_id=" + PropertiesUtils.getValue("kuaishou_config", "kuaishou_appid"))
-                    .append("&state=" + URLEncoder.encode(URLEncoder.encode(state)))
-                    .append("&scope=%5B%22report_service%22%2C%22ad_query%22%2C%22account_service%22%2C%22ad_manage%22%5D")
-                    .append("&redirect_uri=" + URLEncoder.encode(PropertiesUtils.getValue("kuaishou_config", "kuaishou_callback_url"), "UTF-8"));
-        } else if (agentType == 0) {
-            sb.append(PropertiesUtils.getValue("kuaishou_config", "kuaishou_auth_url"))
-                    .append(KuaishouInterfaceConstant.AUTH_PATH)
-                    .append ("?app_id=" + PropertiesUtils.getValue("kuaishou_config", "kuaishou_third_appid"))
-                    .append("&state=" + URLEncoder.encode(URLEncoder.encode(state)))
-                    .append("&scope=%5B%22report_service%22%2C%22ad_query%22%2C%22account_service%22%2C%22ad_manage%22%5D")
-                    .append("&redirect_uri=" + URLEncoder.encode(PropertiesUtils.getValue("kuaishou_config", "kuaishou_third_callback_url"), "UTF-8"));
+        Long id = state.getLong("id");
+
+        OauthConfig config = oauthConfigService.getById(id);
+        state.put("appId", config.getAppId());
+        state.put("callbackUrl", config.getCallbackUrl());
+        sb.append(PropertiesUtils.getValue("kuaishou_config", "kuaishou_auth_url"))
+                .append(KuaishouInterfaceConstant.AUTH_PATH)
+                .append("?app_id=" + config.getAppId())
+                .append("&state=" + URLEncoder.encode(URLEncoder.encode(state.toJSONString())))
+                .append("&redirect_uri=" + URLEncoder.encode(config.getRedirectUri(), "UTF-8"));
+        if (config.getOauthType() != 1) {
+            sb.append("&scope=%5B%22report_service%22%2C%22ad_query%22%2C%22account_service%22%2C%22ad_manage%22%5D");
+        } else {
+            sb.append("&scope=%5B%22report_service%22%2C%22ad_query%22%2C%22ad_manage%22%5D");
         }
         return sb.toString();
     }

+ 4 - 10
module-common/src/main/java/cn/com/ctop/common/module/service/impl/CtopOauthTokenServiceImpl.java

@@ -121,20 +121,14 @@ public class CtopOauthTokenServiceImpl extends ServiceImpl<CtopOauthTokenMapper,
      * @return
      */
     @Override
-    public void getKuaiShouRefreshToken(Long accountId, String token, String refreshToken, Integer agentType) {
+    public void getKuaiShouRefreshToken(Long accountId, String token, String refreshToken, Long appId, String secret) {
         log.info("快手刷新token入参,accountId:{},token:{},refreshToken:{}", accountId, token, refreshToken);
         String url = PropertiesUtils.getConfig("kuaishou_api_url") + "/rest/openapi/oauth2/authorize/refresh_token";
         Map<String, String> headers = new HashMap<>();
         headers.put("Content-Type", " application/json");
         Map<String, Object> param = new HashMap<>();
-        if (agentType == 1) {
-            param.put("app_id", PropertiesUtils.getConfig("kuaishou_appid"));
-            param.put("secret", PropertiesUtils.getConfig("kuaishou_secret"));
-        } else if (agentType == 0) {
-            param.put("app_id", PropertiesUtils.getConfig("kuaishou_third_appid"));
-            param.put("secret", PropertiesUtils.getConfig("kuaishou_third_secret"));
-        }
-
+        param.put("app_id", appId);
+        param.put("secret", secret);
         param.put("refresh_token", refreshToken);
         try {
             CtopOauthToken oauthToken = ctopOauthTokenMapper.selectByAccountId(accountId);
@@ -142,7 +136,7 @@ public class CtopOauthTokenServiceImpl extends ServiceImpl<CtopOauthTokenMapper,
                 log.error("查询token信息返回结果为空,accountId:{}", accountId);
                 return;
             }
-            XxlJobHelper.log("刷新token,入參:{},token:{}", param,headers);
+            XxlJobHelper.log("刷新token,入參:{},token:{}", param, headers);
             String result = HttpUtils.httpPostRequest(url, param, headers);
             JSONObject resultJson = JSONObject.parseObject(result);
             log.info("快手刷新token返回结果:{}", refreshToken);

+ 33 - 0
module-common/src/main/java/cn/com/ctop/common/module/service/impl/OauthConfigServiceImpl.java

@@ -3,9 +3,17 @@ package cn.com.ctop.common.module.service.impl;
 import cn.com.ctop.common.module.entity.OauthConfig;
 import cn.com.ctop.common.module.mapper.OauthConfigMapper;
 import cn.com.ctop.common.module.service.IOauthConfigService;
+import cn.com.ctop.common.module.utils.Check;
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
 /**
  * 授权配置信息
  *
@@ -15,5 +23,30 @@ import org.springframework.stereotype.Service;
  */
 @Service
 public class OauthConfigServiceImpl extends ServiceImpl<OauthConfigMapper, OauthConfig> implements IOauthConfigService {
+    @Autowired
+    private OauthConfigMapper configMapper;
+
+    @Override
+    public OauthConfig getConfigByAppId(Long appId) {
+        QueryWrapper<OauthConfig> queryWrapper = new QueryWrapper<>();
+        queryWrapper.eq("app_id", appId);
+        OauthConfig config = this.getOne(queryWrapper);
+        return config;
+    }
+
+    @Override
+    public Map<Long, String> getConfigMapByMediaId(int mediaId) {
+
+        Map<Long, String> map = new HashMap<>();
+        List<JSONObject> list = configMapper.getListByMediaId(mediaId);
+        if (!Check.isNull(list)) {
+            for (int i = 0; i < list.size(); i++) {
+                JSONObject jsonObject = list.get(i);
+                map.put(jsonObject.getLong("app_id"), jsonObject.getString("secret"));
+            }
+
+        }
 
+        return map;
+    }
 }

+ 9 - 1
module-common/src/main/java/cn/com/ctop/common/module/service/impl/RefreshTokenServiceImpl.java

@@ -5,6 +5,7 @@ import cn.com.ctop.common.module.entity.OauthAgentToken;
 import cn.com.ctop.common.module.mapper.CtopOauthTokenMapper;
 import cn.com.ctop.common.module.service.ICtopOauthTokenService;
 import cn.com.ctop.common.module.service.IOauthAgentTokenService;
+import cn.com.ctop.common.module.service.IOauthConfigService;
 import cn.com.ctop.common.module.service.IRefreshTokenService;
 import cn.com.ctop.common.module.utils.Check;
 import cn.com.ctop.common.module.utils.CtopAdConstant;
@@ -15,6 +16,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import java.util.List;
+import java.util.Map;
 
 @Slf4j
 @Service
@@ -25,6 +27,8 @@ public class RefreshTokenServiceImpl implements IRefreshTokenService {
     private ICtopOauthTokenService oauthTokenService;
     @Autowired
     private IOauthAgentTokenService agentTokenService;
+    @Autowired
+    private IOauthConfigService configService;
 
     /**
      * 获取所有token
@@ -33,13 +37,17 @@ public class RefreshTokenServiceImpl implements IRefreshTokenService {
      */
     @Override
     public void getKuaiShouRefresh() {
+
+
         List<CtopOauthToken> oauthTokens = oauthTokenMapper.selectKuaiShouTokens(CtopAdConstant.PLATFORM_TYPE_KUAISHOU);
         if (!Check.isNull(oauthTokens)) {
+            Map<Long, String> configMap = configService.getConfigMapByMediaId(CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT);
             for (CtopOauthToken oauthToken : oauthTokens) {
                 XxlJobHelper.log("刷新token,accountId:{}", oauthToken.getAccountId());
                 //快手
                 if (CtopAdConstant.PLATFORM_TYPE_KUAISHOU.equals(oauthToken.getMediaId().trim())) {
-                    oauthTokenService.getKuaiShouRefreshToken(oauthToken.getAccountId(), oauthToken.getAccessToken(), oauthToken.getRefreshToken(), oauthToken.getAgentType());
+                    String secret = configMap.get(oauthToken.getAppId());
+                    oauthTokenService.getKuaiShouRefreshToken(oauthToken.getAccountId(), oauthToken.getAccessToken(), oauthToken.getRefreshToken(), oauthToken.getAppId(), secret);
                 }
             }
         } else {

+ 2 - 2
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/controller/KuaishouBatchCampaignPreviewController.java

@@ -53,7 +53,7 @@ import java.util.Map;
 @Slf4j
 @Api(tags = "快手-广告计划预览信息")
 @RestController
-@RequestMapping("/kuaishouBatchCampaignPreview")
+@RequestMapping("/kuaishouBatch/campaignPreview")
 public class KuaishouBatchCampaignPreviewController {
     @Autowired
     private IKuaishouBatchCampaignPreviewService kuaishouBatchCampaignPreviewService;
@@ -152,7 +152,7 @@ public class KuaishouBatchCampaignPreviewController {
      */
     @AutoLog(value = "快手-广告计划预览信息-编辑")
     @ApiOperation(value = "快手-广告计划预览信息-编辑", notes = "快手-广告计划预览信息-编辑")
-    @PutMapping(value = "/edit")
+    @PostMapping(value = "/edit")
     public Result<KuaishouBatchCampaignPreview> edit(@RequestBody KuaishouBatchCampaignPreview kuaishouBatchCampaignPreview) {
         Result<KuaishouBatchCampaignPreview> result = new Result<KuaishouBatchCampaignPreview>();
         KuaishouBatchCampaignPreview kuaishouBatchCampaignPreviewEntity = kuaishouBatchCampaignPreviewService.getById(kuaishouBatchCampaignPreview.getId());

+ 23 - 2
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/controller/KuaishouBatchCreativePreviewController.java

@@ -12,6 +12,7 @@ import javax.servlet.http.HttpServletResponse;
 import cn.com.ctop.common.module.annotation.AutoLog;
 import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouBatchCreativePreview;
 import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouBatchCreativePreviewService;
+import com.alibaba.fastjson.JSONObject;
 import org.jeecg.common.api.vo.Result;
 import org.jeecg.common.system.query.QueryGenerator;
 import org.jeecg.common.util.oConvertUtils;
@@ -48,7 +49,7 @@ import io.swagger.annotations.ApiOperation;
 @Slf4j
 @Api(tags = "快手-广告创意预览信息")
 @RestController
-@RequestMapping("/kuai/kuaishouBatchCreativePreview")
+@RequestMapping("/kuaishouBatch/creativePreview")
 public class KuaishouBatchCreativePreviewController {
     @Autowired
     private IKuaishouBatchCreativePreviewService kuaishouBatchCreativePreviewService;
@@ -98,6 +99,26 @@ public class KuaishouBatchCreativePreviewController {
         }
         return result;
     }
+    /**
+     * 添加
+     *
+     * @param kuaishouBatchCreativePreview
+     * @return
+     */
+    @AutoLog(value = "根据预览信息创建广告计划、组、创意")
+    @ApiOperation(value = "根据预览信息创建广告计划、组、创意", notes = "根据预览信息创建广告计划、组、创意")
+    @PostMapping(value = "/createAdcampaignAndGroups")
+    public Result<KuaishouBatchCreativePreview> createAdcampaignAndGroups(@RequestBody JSONObject data) {
+        Result<KuaishouBatchCreativePreview> result = new Result<>();
+        try {
+            kuaishouBatchCreativePreviewService.createAdcampaignAndGroups(data);
+            result.success("操作成功!");
+        } catch (Exception e) {
+            log.error(e.getMessage(), e);
+            result.error500("操作失败");
+        }
+        return result;
+    }
 
     /**
      * 编辑
@@ -107,7 +128,7 @@ public class KuaishouBatchCreativePreviewController {
      */
     @AutoLog(value = "快手-广告创意预览信息-编辑")
     @ApiOperation(value = "快手-广告创意预览信息-编辑", notes = "快手-广告创意预览信息-编辑")
-    @PutMapping(value = "/edit")
+    @PostMapping(value = "/edit")
     public Result<KuaishouBatchCreativePreview> edit(@RequestBody KuaishouBatchCreativePreview kuaishouBatchCreativePreview) {
         Result<KuaishouBatchCreativePreview> result = new Result<KuaishouBatchCreativePreview>();
         KuaishouBatchCreativePreview kuaishouBatchCreativePreviewEntity = kuaishouBatchCreativePreviewService.getById(kuaishouBatchCreativePreview.getId());

+ 2 - 3
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/controller/KuaishouBatchGroupPreviewController.java

@@ -22,7 +22,6 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.DeleteMapping;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.PutMapping;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
@@ -51,7 +50,7 @@ import java.util.Map;
 @Slf4j
 @Api(tags = "快手-广告组预览信息")
 @RestController
-@RequestMapping("/kuai/kuaishouBatchGroupPreview")
+@RequestMapping("/kuaishouBatch/groupPreview")
 public class KuaishouBatchGroupPreviewController {
     @Autowired
     private IKuaishouBatchGroupPreviewService kuaishouBatchGroupPreviewService;
@@ -110,7 +109,7 @@ public class KuaishouBatchGroupPreviewController {
      */
     @AutoLog(value = "快手-广告组预览信息-编辑")
     @ApiOperation(value = "快手-广告组预览信息-编辑", notes = "快手-广告组预览信息-编辑")
-    @PutMapping(value = "/edit")
+    @PostMapping(value = "/edit")
     public Result<KuaishouBatchGroupPreview> edit(@RequestBody KuaishouBatchGroupPreview kuaishouBatchGroupPreview) {
         Result<KuaishouBatchGroupPreview> result = new Result<KuaishouBatchGroupPreview>();
         KuaishouBatchGroupPreview kuaishouBatchGroupPreviewEntity = kuaishouBatchGroupPreviewService.getById(kuaishouBatchGroupPreview.getId());

+ 25 - 0
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/controller/KuaishouTemplateController.java

@@ -143,6 +143,31 @@ public class KuaishouTemplateController {
     }
 
 
+    @PostMapping(value = "/updateTemplate")
+    public Result<JSONObject> updateTemplate(@RequestBody JSONObject requestJson) {
+        Result<JSONObject> result = new Result<>();
+        try {
+
+            Long accountId = requestJson.getLong("accountId");
+            if (Check.isNull(accountId)) {
+                throw new Exception("请选择账户id");
+            }
+            CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
+            if (Check.isNull(oauthToken)) {
+                throw new Exception("未获取到账户信息");
+            }
+            JSONObject returnJson = kuaishouTemplateService.updateTemplate(accountId, oauthToken.getAccessToken(), requestJson);
+            result.setSuccess(true);
+            result.setResult(returnJson);
+        } catch (Exception e) {
+            e.printStackTrace();
+            result.setSuccess(false);
+            result.setMessage(e.getMessage());
+        }
+        return result;
+    }
+
+
     /**
      * 添加
      *

+ 20 - 0
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/entity/KuaishouBatchCampaignPreview.java

@@ -1,5 +1,6 @@
 package cn.com.ctop.kuaishou.modules.batch.entity;
 
+import com.baomidou.mybatisplus.annotation.TableField;
 import com.baomidou.mybatisplus.annotation.TableId;
 import com.baomidou.mybatisplus.annotation.TableName;
 import io.swagger.annotations.ApiModel;
@@ -9,7 +10,9 @@ import lombok.EqualsAndHashCode;
 import lombok.experimental.Accessors;
 import org.jeecgframework.poi.excel.annotation.Excel;
 
+import javax.persistence.Table;
 import java.util.Date;
+import java.util.List;
 
 /**
  * 快手-广告计划预览信息
@@ -94,4 +97,21 @@ public class KuaishouBatchCampaignPreview {
     @Excel(name = "批次标识", width = 15)
     @ApiModelProperty(value = "批次标识")
     private String batchId;
+    /**
+     * 是否创建成功 0 失败,1成功
+     */
+    private int isSuccess;
+
+    /**
+     * 操作说明
+     */
+    private String message;
+    /**
+     * 创建成功后的计划ID
+     */
+    private Long campaignId;
+
+    @TableField(exist = false)
+    private List<KuaishouBatchGroupPreview>  kuaishouBatchGroupPreviews;
+
 }

+ 23 - 0
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/entity/KuaishouBatchCreativePreview.java

@@ -175,4 +175,27 @@ public class KuaishouBatchCreativePreview {
     @Excel(name = "批次标识", width = 15)
     @ApiModelProperty(value = "批次标识")
     private String batchId;
+
+    /**
+     * 是否创建成功 0 失败,1成功
+     */
+    private int isSuccess;
+
+    /**
+     * 操作说明
+     */
+    private String message;
+    /**
+     * 创建成功后的计划ID
+     */
+    private Long campaignId;
+    /**
+     * 创建成功后的组ID
+     */
+    private Long unitId;
+    /**
+     * 创建成功后的创意ID
+     */
+    private Long creativeId;
+
 }

+ 24 - 0
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/entity/KuaishouBatchGroupPreview.java

@@ -1,5 +1,6 @@
 package cn.com.ctop.kuaishou.modules.batch.entity;
 
+import com.baomidou.mybatisplus.annotation.TableField;
 import com.baomidou.mybatisplus.annotation.TableId;
 import com.baomidou.mybatisplus.annotation.TableName;
 import com.fasterxml.jackson.annotation.JsonFormat;
@@ -12,6 +13,7 @@ import org.jeecgframework.poi.excel.annotation.Excel;
 import org.springframework.format.annotation.DateTimeFormat;
 
 import java.util.Date;
+import java.util.List;
 
 /**
  * 快手-广告组预览信息
@@ -209,4 +211,26 @@ public class KuaishouBatchGroupPreview {
     @Excel(name = "批次标识", width = 15)
     @ApiModelProperty(value = "批次标识")
     private String batchId;
+
+    @TableField(exist = false)
+    private List<KuaishouBatchCreativePreview> kuaishouBatchCreativePreviews;
+
+    /**
+     * 是否创建成功 0 失败,1成功
+     */
+    private int isSuccess;
+
+    /**
+     * 操作说明
+     */
+    private String message;
+    /**
+     * 创建成功后的计划ID
+     */
+    private Long campaignId;
+    /**
+     * 创建成功后的组ID
+     */
+    private Long unitId;
+
 }

+ 2 - 0
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/service/IKuaishouBatchCreativePreviewService.java

@@ -1,6 +1,7 @@
 package cn.com.ctop.kuaishou.modules.batch.service;
 
 import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouBatchCreativePreview;
+import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.extension.service.IService;
 
 /**
@@ -11,4 +12,5 @@ import com.baomidou.mybatisplus.extension.service.IService;
  */
 public interface IKuaishouBatchCreativePreviewService extends IService<KuaishouBatchCreativePreview> {
 
+    void createAdcampaignAndGroups(JSONObject data) throws Exception;
 }

+ 3 - 12
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/service/IKuaishouInterfaceService.java

@@ -8,7 +8,6 @@ import cn.com.ctop.kuaishou.modules.material.entity.KuaishouResultToken;
 import cn.com.ctop.kuaishou.modules.report.entity.*;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
-import com.google.gson.JsonArray;
 
 import java.text.ParseException;
 import java.util.Date;
@@ -21,7 +20,7 @@ import java.util.Map;
  */
 public interface IKuaishouInterfaceService {
 
-    KuaishouResultToken getAccessToken(String authCode, Integer agentType);
+    KuaishouResultToken getAccessToken(String authCode, Long appId);
 
 
     /**
@@ -152,7 +151,6 @@ public interface IKuaishouInterfaceService {
     void getCreativeList(CtopOauthToken token, Date startDate, Date endDate);
 
 
-
     /**
      * 根据组id,获取创意列表
      *
@@ -162,7 +160,7 @@ public interface IKuaishouInterfaceService {
      * @param endDate
      * @param timeFilterType
      */
-    JSONArray getCreativeList(CtopOauthToken token, Long unitId, Date startDate, Date endDate,int timeFilterType);
+    JSONArray getCreativeList(CtopOauthToken token, Long unitId, Date startDate, Date endDate, int timeFilterType);
 
 
     /**
@@ -359,7 +357,6 @@ public interface IKuaishouInterfaceService {
     void getCampaignList(CtopOauthToken token, Date startDate, Date endDate);
 
 
-
     /**
      * 获取计划列表,新增一个参数 按创建时间,还是更新时间进行筛选
      *
@@ -381,7 +378,6 @@ public interface IKuaishouInterfaceService {
     void getGroupList(CtopOauthToken token, Date startDate, Date endDate);
 
 
-
     /**
      * 获取指定广告计划下的广告组列表
      *
@@ -391,12 +387,7 @@ public interface IKuaishouInterfaceService {
      * @param endDate
      * @param time_filter_type
      */
-    JSONArray getGroupList(CtopOauthToken token, Long campaignId, Date startDate, Date endDate,int time_filter_type);
-
-
-
-
-
+    JSONArray getGroupList(CtopOauthToken token, Long campaignId, Date startDate, Date endDate, int time_filter_type);
 
 
     /**

+ 0 - 1
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/service/IKuaishouTemplateService.java

@@ -16,6 +16,5 @@ public interface IKuaishouTemplateService extends IService<KuaishouTemplate> {
 
     JSONObject createTemplate(Long accountId, String accessToken, JSONObject requestJson);
 
-
     JSONObject updateTemplate(Long accountId, String accessToken, JSONObject requestJson);
 }

+ 97 - 21
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/service/impl/KuaishouBatchCampaignPreviewServiceImpl.java

@@ -8,6 +8,7 @@ import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouBatchCampaignPreviewMap
 import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouBatchCreativePreviewMapper;
 import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouBatchGroupPreviewMapper;
 import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouBatchCampaignPreviewService;
+import com.alibaba.excel.util.CollectionUtils;
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
@@ -119,20 +120,39 @@ public class KuaishouBatchCampaignPreviewServiceImpl extends ServiceImpl<Kuaisho
         JSONObject appList = data.getJSONObject("appList");
         //应用分配方式 1 按账户,2按广告计划,3按广告组
         Integer appAllocation = appList.getInteger("appAllocation");
+        Integer appId = null;
+        Integer siteId = null;
+        String url = null;
         JSONArray appArr = appList.getJSONArray("appArr");
+        JSONArray urlArr = appList.getJSONArray("urlArr");
+        boolean appNoNull = isNotNull(appArr, null, 1);
+        boolean urlNoNull = isNotNull(urlArr, null, 1);
+
         //监测链接分配方式 1 按账户,2按广告计划,3按广告组
         Integer linkAllocation = appList.getInteger("linkAllocation");
-        JSONArray clickUrlList = appList.getJSONArray("clickUrlList");
-        Integer appId = null;
-        Integer siteId = null;
+        JSONArray clickTrackUrlList = appList.getJSONArray("clickUrlList");
+        JSONArray actionbarClickUrlList = appList.getJSONArray("clickUrlActionList");
+        boolean tracknotNull = isNotNull(clickTrackUrlList, null, 1);
+        boolean barnotNull = isNotNull(actionbarClickUrlList, null, 1);
+        String clickTrackUrl = null;
         String actionbarClickUrl = null;
         //按账户
         if (appAllocation == 1) {
-            appId = appArr.getJSONObject(0).getInteger("appId");
-            siteId = appArr.getJSONObject(0).getInteger("siteId");
+            if (appNoNull) {
+                appId = appArr.getJSONObject(0).getInteger("appId");
+                siteId = appArr.getJSONObject(0).getInteger("siteId");
+            }
+            if (urlNoNull) {
+                url = urlArr.getString(0);
+            }
         }
         if (linkAllocation == 1) {
-            actionbarClickUrl = clickUrlList.getString(0);
+            if (tracknotNull) {
+                clickTrackUrl = clickTrackUrlList.getString(0);
+            }
+            if (barnotNull) {
+                actionbarClickUrl = actionbarClickUrlList.getString(0);
+            }
         }
 
         //素材数据
@@ -160,28 +180,51 @@ public class KuaishouBatchCampaignPreviewServiceImpl extends ServiceImpl<Kuaisho
              */
             for (int i = 0; i < targetIds.size(); i++) {
                 if (appAllocation == 2) {
-                    appId = appArr.getJSONObject(i).getInteger("appId");
-                    siteId = appArr.getJSONObject(i).getInteger("siteId");
+                    if (appNoNull) {
+                        appId = appArr.getJSONObject(i).getInteger("appId");
+                        siteId = appArr.getJSONObject(i).getInteger("siteId");
+                    }
+                    if (urlNoNull) {
+                        url = urlArr.getString(i);
+                    }
                 }
                 if (linkAllocation == 2) {
-                    actionbarClickUrl = clickUrlList.getString(i);
+                    if (tracknotNull) {
+                        clickTrackUrl = clickTrackUrlList.getString(i);
+                    }
+                    if (barnotNull) {
+                        actionbarClickUrl = actionbarClickUrlList.getString(i);
+                    }
                 }
                 campaignPreview.setId(null);
+                campaignPreview.setCampaignName(campaignPreview.getCampaignName() + i);
                 campaignPreviewMapper.insert(campaignPreview);
                 for (int j = 0; j < materialList.size(); j++) {
                     if (appAllocation == 3) {
                         appCount--;
-                        appId = appArr.getJSONObject(appCount).getInteger("appId");
-                        siteId = appArr.getJSONObject(appCount).getInteger("siteId");
+                        if (appNoNull) {
+                            appId = appArr.getJSONObject(appCount).getInteger("appId");
+                            siteId = appArr.getJSONObject(appCount).getInteger("siteId");
+                        }
+                        if (urlNoNull) {
+                            url = urlArr.getString(appCount);
+                        }
                     }
                     if (linkAllocation == 3) {
                         count--;
-                        actionbarClickUrl = clickUrlList.getString(count);
+                        if (tracknotNull) {
+                            clickTrackUrl = clickTrackUrlList.getString(count);
+                        }
+                        if (barnotNull) {
+                            actionbarClickUrl = actionbarClickUrlList.getString(count);
+                        }
                     }
                     groupPreview.setId(null);
                     groupPreview.setAppId(appId);
                     groupPreview.setPlanId(campaignPreview.getId());
                     groupPreview.setTemplateId(targetIds.getLong(i));
+                    groupPreview.setUnitName(groupPreview.getUnitName() + j);
+                    groupPreview.setUrl(url);
                     groupPreviewMapper.insert(groupPreview);
                     JSONObject material = materialList.getJSONObject(j);
                     JSONArray photoArr = material.getJSONArray("photoArr");
@@ -192,13 +235,14 @@ public class KuaishouBatchCampaignPreviewServiceImpl extends ServiceImpl<Kuaisho
                     for (int k = 0; k < photoArr.size(); k++) {
                         creativePreview.setId(null);
                         creativePreview.setSiteId(siteId);
+                        creativePreview.setClickTrackUrl(clickTrackUrl);
                         creativePreview.setActionbarClickUrl(actionbarClickUrl);
                         JSONObject photo = photoArr.getJSONObject(k);
                         JSONObject image = photo.getJSONObject("image");
                         creativePreview.setPlanId(campaignPreview.getId());
                         creativePreview.setGroupId(groupPreview.getId());
                         creativePreview.setPhotoId(photo.getString("photoId"));
-                        creativePreview.setCreativeName(photo.getString("creativeName"));
+                        creativePreview.setCreativeName(photo.getString("creativeName") + k);
                         creativePreview.setImageUrl(image.getString("url"));
                         creativePreview.setImageSignature(image.getString("signature"));
                         if (matchingMethod == 1) {
@@ -220,13 +264,24 @@ public class KuaishouBatchCampaignPreviewServiceImpl extends ServiceImpl<Kuaisho
              */
             for (int i = 0; i < materialList.size(); i++) {
                 if (appAllocation == 2) {
-                    appId = appArr.getJSONObject(i).getInteger("appId");
-                    siteId = appArr.getJSONObject(i).getInteger("siteId");
+                    if (appNoNull) {
+                        appId = appArr.getJSONObject(i).getInteger("appId");
+                        siteId = appArr.getJSONObject(i).getInteger("siteId");
+                    }
+                    if (urlNoNull) {
+                        url = urlArr.getString(i);
+                    }
                 }
                 if (linkAllocation == 2) {
-                    actionbarClickUrl = clickUrlList.getString(i);
+                    if (tracknotNull) {
+                        clickTrackUrl = clickTrackUrlList.getString(i);
+                    }
+                    if (barnotNull) {
+                        actionbarClickUrl = actionbarClickUrlList.getString(i);
+                    }
                 }
                 campaignPreview.setId(null);
+                campaignPreview.setCampaignName(campaignPreview.getCampaignName() + i);
                 campaignPreviewMapper.insert(campaignPreview);
                 JSONObject material = materialList.getJSONObject(i);
                 JSONArray photoArr = material.getJSONArray("photoArr");
@@ -237,28 +292,41 @@ public class KuaishouBatchCampaignPreviewServiceImpl extends ServiceImpl<Kuaisho
                 for (int j = 0; j < targetIds.size(); j++) {
                     if (appAllocation == 3) {
                         appCount--;
-                        appId = appArr.getJSONObject(appCount).getInteger("appId");
-                        siteId = appArr.getJSONObject(appCount).getInteger("siteId");
+                        if (appNoNull) {
+                            appId = appArr.getJSONObject(appCount).getInteger("appId");
+                            siteId = appArr.getJSONObject(appCount).getInteger("siteId");
+                        }
+                        if (urlNoNull) {
+                            url = urlArr.getString(appCount);
+                        }
                     }
                     if (linkAllocation == 3) {
                         count--;
-                        actionbarClickUrl = clickUrlList.getString(count);
+                        if (tracknotNull) {
+                            clickTrackUrl = clickTrackUrlList.getString(count);
+                        }
+                        if (barnotNull) {
+                            actionbarClickUrl = actionbarClickUrlList.getString(count);
+                        }
                     }
                     groupPreview.setId(null);
                     groupPreview.setAppId(appId);
                     groupPreview.setPlanId(campaignPreview.getId());
                     groupPreview.setTemplateId(targetIds.getLong(j));
+                    groupPreview.setUnitName(groupPreview.getUnitName() + j);
+                    groupPreview.setUrl(url);
                     groupPreviewMapper.insert(groupPreview);
                     for (int k = 0; k < photoArr.size(); k++) {
                         creativePreview.setId(null);
                         creativePreview.setSiteId(siteId);
+                        creativePreview.setClickTrackUrl(clickTrackUrl);
                         creativePreview.setActionbarClickUrl(actionbarClickUrl);
                         JSONObject photo = photoArr.getJSONObject(k);
                         JSONObject image = photo.getJSONObject("image");
                         creativePreview.setPlanId(campaignPreview.getId());
                         creativePreview.setGroupId(groupPreview.getId());
                         creativePreview.setPhotoId(photo.getString("photoId"));
-                        creativePreview.setCreativeName(photo.getString("creativeName"));
+                        creativePreview.setCreativeName(photo.getString("creativeName") + k);
                         creativePreview.setImageUrl(image.getString("url"));
                         creativePreview.setImageSignature(image.getString("signature"));
                         if (matchingMethod == 1) {
@@ -276,6 +344,14 @@ public class KuaishouBatchCampaignPreviewServiceImpl extends ServiceImpl<Kuaisho
     }
 
 
+    private boolean isNotNull(JSONArray arr, JSONArray arr2, Integer num) {
+        if (num == 2) {
+            return !CollectionUtils.isEmpty(arr) && !CollectionUtils.isEmpty(arr2);
+        } else {
+            return !CollectionUtils.isEmpty(arr);
+        }
+    }
+
     /**
      * 广告语整理
      *
@@ -332,7 +408,7 @@ public class KuaishouBatchCampaignPreviewServiceImpl extends ServiceImpl<Kuaisho
         KuaishouBatchGroupPreview groupPreview = new KuaishouBatchGroupPreview();
         groupPreview.setAccountId(groupJson.getLong("accountId"));
         groupPreview.setUnitName(groupJson.getString("unitName"));
-        groupPreview.setPutStatus(campaignJson.getInteger("unitStatus"));
+        groupPreview.setPutStatus(campaignJson.getInteger("unitStatus") == 2 ? 2 : null);
         groupPreview.setBidType(groupJson.getInteger("bidType"));
         if (groupJson.getInteger("bidType") == 2) {
             int bid = getRandom(groupJson.getInteger("bidMax"), groupJson.getInteger("bidMin"));

+ 457 - 0
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/service/impl/KuaishouBatchCreativePreviewServiceImpl.java

@@ -1,11 +1,42 @@
 package cn.com.ctop.kuaishou.modules.batch.service.impl;
 
+import cn.com.ctop.common.module.entity.CtopOauthToken;
+import cn.com.ctop.common.module.entity.MaterialCutFrame;
+import cn.com.ctop.common.module.service.ICtopOauthTokenService;
+import cn.com.ctop.common.module.service.IMaterialCutFrameService;
+import cn.com.ctop.common.module.utils.Check;
+import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouImageGet;
+import cn.com.ctop.kuaishou.modules.batch.entity.KuaiShouVideoGet;
+import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouBatchCampaignPreview;
 import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouBatchCreativePreview;
+import cn.com.ctop.kuaishou.modules.batch.entity.KuaishouBatchGroupPreview;
+import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouBatchCampaignPreviewMapper;
 import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouBatchCreativePreviewMapper;
+import cn.com.ctop.kuaishou.modules.batch.mapper.KuaishouBatchGroupPreviewMapper;
+import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouGroupTemplateService;
+import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouImageGetService;
+import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouMaterialUploadService;
+import cn.com.ctop.kuaishou.modules.batch.service.IKuaiShouVideoGetService;
 import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouBatchCreativePreviewService;
+import com.alibaba.fastjson.JSONObject;
+import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
 import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
+import lombok.extern.slf4j.Slf4j;
+import org.jeecg.common.util.DateUtils;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import static java.lang.Integer.valueOf;
+
 /**
  * 快手-广告创意预览信息
  *
@@ -13,7 +44,433 @@ import org.springframework.stereotype.Service;
  * @version V1.0
  * @date 2021-01-26
  */
+@Slf4j
 @Service
 public class KuaishouBatchCreativePreviewServiceImpl extends ServiceImpl<KuaishouBatchCreativePreviewMapper, KuaishouBatchCreativePreview> implements IKuaishouBatchCreativePreviewService {
 
+    @Autowired
+    KuaishouBatchCampaignPreviewMapper campaignPreviewMapper;
+    @Autowired
+    KuaishouBatchGroupPreviewMapper groupPreviewMapper;
+    @Autowired
+    KuaishouBatchCreativePreviewMapper creativePreviewMapper;
+
+    @Autowired
+    private IKuaishouInterfaceService kuaishouInterfaceService;
+    @Autowired
+    private ICtopOauthTokenService tokenService;
+    @Autowired
+    private IKuaiShouGroupTemplateService groupTemplateService;
+    @Autowired
+    private IKuaiShouVideoGetService videoGetService;
+    @Autowired
+    private IMaterialCutFrameService cutFrameService;
+    @Autowired
+    private IKuaiShouMaterialUploadService uploadService;
+    @Autowired
+    private IKuaiShouImageGetService imageGetService;
+
+    static ExecutorService campaignService = Executors.newFixedThreadPool(10);
+    static ExecutorService unitService = Executors.newFixedThreadPool(20);
+    static ExecutorService creativeService = Executors.newFixedThreadPool(20);
+
+    @Override
+    public void createAdcampaignAndGroups(JSONObject data) throws Exception {
+        Long accountId = data.getLong("accountId");
+        JSONObject dataList = data.getJSONObject("dataList");
+        if (!Check.isNull(dataList)) {
+            List<String> compaignList = dataList.getJSONArray("campaigns").toJavaList(String.class);
+            List<String> groupList = dataList.getJSONArray("groups").toJavaList(String.class);
+            List<String> creativeList = dataList.getJSONArray("creatives").toJavaList(String.class);
+            List<KuaishouBatchCampaignPreview> campaignPreviewList = campaignPreviewMapper.selectBatchIds(compaignList);
+            List<KuaishouBatchGroupPreview> kuaishouBatchGroupPreviews = groupPreviewMapper.selectBatchIds(groupList);
+            List<KuaishouBatchCreativePreview> kuaishouBatchCreativePreviews = creativePreviewMapper.selectBatchIds(creativeList);
+            //待建计划
+            List<KuaishouBatchCampaignPreview> campaignList = getCampaignList(campaignPreviewList, kuaishouBatchGroupPreviews, kuaishouBatchCreativePreviews);
+            CtopOauthToken oauthToken = tokenService.getTokenByAccountId(accountId);
+            if (Check.isNull(oauthToken)) {
+                throw new Exception("未获取到账户信息");
+            }
+            campaignList.forEach(campaign -> campaignService.submit(() -> {
+                try {
+                    creativeCampaign(oauthToken, campaign);
+                } catch (Exception e) {
+                    log.error("根据预览数据创建广告计划异常", e);
+                }
+            }));
+        }
+    }
+
+    /**
+     * 创建广告计划
+     *
+     * @param
+     * @return void
+     * @throws
+     * @author ZHAOXA
+     */
+    private List<KuaishouBatchCampaignPreview> getCampaignList(List<KuaishouBatchCampaignPreview> campaignPreviewList, List<KuaishouBatchGroupPreview> kuaishouBatchGroupPreviews, List<KuaishouBatchCreativePreview> kuaishouBatchCreativePreviews) {
+        List<KuaishouBatchGroupPreview> groups = new ArrayList<>();
+        for (KuaishouBatchGroupPreview groupPreview : kuaishouBatchGroupPreviews) {
+            List<KuaishouBatchCreativePreview> creatives = new ArrayList<>();
+            for (KuaishouBatchCreativePreview creativePreview : kuaishouBatchCreativePreviews) {
+                if (groupPreview.getPlanId().equals(creativePreview.getPlanId()) && creativePreview.getGroupId().equals(groupPreview.getId())) {
+                    creatives.add(creativePreview);
+                }
+            }
+            groupPreview.setKuaishouBatchCreativePreviews(creatives);
+            groups.add(groupPreview);
+        }
+        List<KuaishouBatchCampaignPreview> campaigns = new ArrayList<>();
+        for (KuaishouBatchCampaignPreview campaignPreview : campaignPreviewList) {
+            List<KuaishouBatchGroupPreview> groupList = new ArrayList<>();
+            for (KuaishouBatchGroupPreview group : groups) {
+                if (campaignPreview.getId().equals(group.getPlanId())) {
+                    groupList.add(group);
+                }
+            }
+            campaignPreview.setKuaishouBatchGroupPreviews(groupList);
+            campaigns.add(campaignPreview);
+        }
+        return campaigns;
+    }
+
+    /**
+     * 根据预览数据创建广告计划
+     *
+     * @param
+     * @return void
+     * @throws
+     * @author ZHAOXA
+     */
+
+    private void creativeCampaign(CtopOauthToken oauthToken, KuaishouBatchCampaignPreview campaign) throws Exception {
+        KuaishouBatchCampaignPreview updateStatus = new KuaishouBatchCampaignPreview();
+        updateStatus.setId(campaign.getId());
+        JSONObject campaignJson = new JSONObject();
+        campaignJson.put("campaign_name", campaign.getCampaignName());
+        campaignJson.put("type", campaign.getCampaignType());
+        if (!Check.isNull(campaign.getDayBudget())) {
+            campaignJson.put("day_budget", campaign.getDayBudget());
+        }
+        if (!Check.isNull(campaign.getDayBudgetSchedule())) {
+            campaignJson.put("day_budget_schedule", campaign.getDayBudgetSchedule());
+        }
+        Map<String, Object> campaignMap = kuaishouInterfaceService.campaignCreate(oauthToken.getAccessToken(), oauthToken.getAccountId(), campaignJson);
+        Integer code = (Integer) campaignMap.get("code");
+        if (code != 0) {
+            updateStatus.setIsSuccess(0);
+            updateStatus.setMessage((String) campaignMap.get("message"));
+            campaignPreviewMapper.updateById(updateStatus);
+            throw new Exception((String) campaignMap.get("message"));
+        }
+        Long campaignId = (Long) campaignMap.get("campaignId");
+        /**
+         *更新预览数据状态
+         */
+        updateStatus.setIsSuccess(1);
+        updateStatus.setMessage((String) campaignMap.get("message"));
+        updateStatus.setCampaignId(campaignId);
+        campaignPreviewMapper.updateById(updateStatus);
+        //创意广告组
+        List<KuaishouBatchGroupPreview> groupPreviewList = campaign.getKuaishouBatchGroupPreviews();
+        groupPreviewList.forEach(group -> campaignService.submit(() -> {
+            try {
+                createCopyUnits(oauthToken, group, campaignId);
+            } catch (Exception e) {
+                log.error("根据预览数据创建广告组异常", e);
+            }
+        }));
+    }
+
+    /**
+     * 根据预览数据创建广告组
+     * detail
+     *
+     * @param
+     * @return void
+     * @throws
+     * @author ZHAOXA
+     */
+    private void createCopyUnits(CtopOauthToken token, KuaishouBatchGroupPreview groupPreview, Long campaignId) throws Exception {
+        KuaishouBatchGroupPreview updateStatus = new KuaishouBatchGroupPreview();
+        try {
+            updateStatus.setId(groupPreview.getId());
+            updateStatus.setCampaignId(campaignId);
+            JSONObject unitJson = new JSONObject();
+            unitJson.put("campaign_id", campaignId);
+            // 资源位置
+            String sceneId = groupPreview.getSceneId();
+            JSONArray scene_id = JSONObject.parseArray(sceneId);
+            unitJson.put("scene_id", scene_id);
+            // 资源创作方式
+            unitJson.put("unit_type", groupPreview.getUnitType());
+            // 转化目标id
+            if (!Check.isNull(groupPreview.getConvertId())) {
+                unitJson.put("convert_id", groupPreview.getConvertId());
+            }
+            // 优先从系统应用商店下载
+            if (!Check.isNull(groupPreview.getUseAppMarket())) {
+                unitJson.put("use_app_market", groupPreview.getUseAppMarket());
+            }
+            // 应用商店列表
+            if (!Check.isNull(groupPreview.getAppStore())) {
+                unitJson.put("app_store", JSONObject.parseArray(groupPreview.getAppStore()));
+            }
+            //投放开始时间
+            String beginTime = groupPreview.getBeginTime();
+            String nowDate = DateUtils.getNowDate("yyyy-MM-dd");
+            boolean beginTimeBoolean = DateUtils.compare(beginTime, nowDate);
+            if (beginTimeBoolean) {
+                unitJson.put("begin_time", nowDate);
+            } else {
+                unitJson.put("begin_time", beginTime);
+            }
+            // 投放结束时间
+            String endTime = groupPreview.getEndTime();
+            if (!Check.isNull(endTime)) {
+                unitJson.put("end_time", endTime);
+            }
+            // 投放时间段
+            String scheduleTime = groupPreview.getScheduleTime();
+            if (!Check.isNull(scheduleTime)) {
+                unitJson.put("schedule_time", scheduleTime);
+            }
+            // 广告组单日预算
+            Integer dayBudget = groupPreview.getDayBudget();
+            if (!Check.isNull(dayBudget)) {
+                unitJson.put("day_budget", dayBudget);
+            }
+            // url类型
+            if (!Check.isNull(groupPreview.getUrlType())) {
+                unitJson.put("url_type", groupPreview.getUrlType());
+            }
+            // url
+            if (!Check.isNull(groupPreview.getUrl())) {
+                unitJson.put("url", groupPreview.getUrl());
+            }
+            // appId
+            if (!Check.isNull(groupPreview.getAppId())) {
+                unitJson.put("app_id", groupPreview.getAppId());
+            }
+            // 创意展现方式
+            if (!Check.isNull(groupPreview.getShowMode())) {
+                unitJson.put("show_mode", groupPreview.getShowMode());
+            }
+            //投放方式
+            Integer speed = groupPreview.getSpeed();
+            if (!Check.isNull(speed)) {
+                unitJson.put("speed", speed);
+            }
+            Integer firstSceneId = valueOf(scene_id.get(0).toString());
+            Long templateId = groupPreview.getTemplateId();
+            if (!Check.isNull(templateId)) {
+                if (firstSceneId != 5) {
+                    unitJson.put("template_id", templateId);
+                } else {
+                    JSONObject unionJson = groupTemplateService.getUnionJson(templateId);
+                    Integer code = unionJson.getInteger("code");
+                    if (code == 0) {
+                        JSONObject target = unionJson.getJSONObject("target");
+                        unitJson.put("target", target);
+                    }
+                }
+            }
+            // 出价
+            Integer bid = groupPreview.getBid();
+            if (!Check.isNull(bid)) {
+                unitJson.put("bid", bid);
+            }
+            // 出价类型
+            Integer bidType = groupPreview.getBidType();
+            if (!Check.isNull(bidType)) {
+                unitJson.put("bid_type", bidType);
+            }
+            // 深度转化出价
+            Integer cpaBid = groupPreview.getCpaBid();
+            if (!Check.isNull(cpaBid)) {
+                unitJson.put("cpa_bid", cpaBid);
+            }
+            // 深度转化目标出价
+            Integer deepConversionBid = groupPreview.getDeepConversionBid();
+            if (!Check.isNull(deepConversionBid)) {
+                unitJson.put("deep_conversion_bid", deepConversionBid);
+            }
+            // 深度转化目标
+            Integer deepConversionType = groupPreview.getDeepConversionType();
+            if (!Check.isNull(deepConversionType)) {
+                unitJson.put("deep_conversion_type", deepConversionType);
+            }
+            // 优化目标
+            Integer ocpxActionType = groupPreview.getOcpxActionType();
+            if (!Check.isNull(ocpxActionType)) {
+                unitJson.put("ocpx_action_type", ocpxActionType);
+            }
+            // 广告组的投放状态
+            Integer putStatus = groupPreview.getPutStatus();
+            if (!Check.isNull(putStatus)) {
+                unitJson.put("put_status", putStatus);
+            }
+            //快手广告组名
+            String unitName = groupPreview.getUnitName();
+            unitJson.put("unit_name", unitName);
+            Map<String, Object> returnUnitMap = kuaishouInterfaceService.adUnitCreate(token.getAccessToken(), token.getAccountId(), unitJson, 1);
+            if (!Check.isNullMap(returnUnitMap)) {
+                Integer code = (Integer) returnUnitMap.get("code");
+                if (code == 0) {
+                    Long unitId = (Long) returnUnitMap.get("unitId");
+                    updateStatus.setIsSuccess(1);
+                    updateStatus.setMessage((String) returnUnitMap.get("message"));
+                    updateStatus.setUnitId(unitId);
+                    createCopyCreatives(token, groupPreview.getKuaishouBatchCreativePreviews(), unitId, campaignId);
+                } else {
+                    updateStatus.setIsSuccess(0);
+                    updateStatus.setMessage((String) returnUnitMap.get("message"));
+                }
+            } else {
+                updateStatus.setIsSuccess(0);
+                updateStatus.setMessage((String) "返回map数据为空!");
+            }
+        } catch (Exception e) {
+            updateStatus.setIsSuccess(0);
+            updateStatus.setMessage("创建组过程中调用快手接口异常");
+            log.error("调用快手接口异常", e);
+        }
+        groupPreviewMapper.updateById(updateStatus);
+    }
+
+    /**
+     * 执行多线程创建创意
+     *
+     * @param
+     * @return void
+     * @throws
+     * @author ZHAOXA
+     */
+    private void createCopyCreatives(CtopOauthToken token, List<KuaishouBatchCreativePreview> creativePreviewList, Long unitId, Long campaignId) {
+        creativePreviewList.forEach(creative -> campaignService.submit(() -> {
+            try {
+                createCreative(token, campaignId, unitId, creative);
+            } catch (Exception e) {
+                log.error("根据预览数据创建广告创意异常", e);
+            }
+        }));
+    }
+
+    /**
+     * 根据预览数据创建广告创意
+     *
+     * @param oauthToken
+     * @param unit_id
+     * @param creative_list
+     */
+    private void createCreative(CtopOauthToken oauthToken, Long campaignId, Long unitId, KuaishouBatchCreativePreview creativePreview) throws Exception {
+        KuaishouBatchCreativePreview updateStatus = new KuaishouBatchCreativePreview();
+        updateStatus.setId(creativePreview.getId());
+        updateStatus.setCampaignId(campaignId);
+        updateStatus.setUnitId(unitId);
+        try {
+            JSONObject createJson = new JSONObject();
+            createJson.put("advertiser_id", oauthToken.getAccountId());
+            createJson.put("unit_id", unitId);
+            createJson.put("creative_name", creativePreview.getCreativeName()); // 创意名称
+            if (!Check.isNull(creativePreview.getPhotoId())) {
+                createJson.put("photo_id", creativePreview.getPhotoId());  // 视频ID
+            }
+            KuaiShouVideoGet video = videoGetService.getVideoByPhotoId(Long.valueOf(creativePreview.getPhotoId()));
+            if (!Check.isNull(video)) {
+                createJson.put("creative_material_type", video.getMaterialType());  // 素材类型
+            }
+            if (!Check.isNull(creativePreview.getActionBarText())) {
+                createJson.put("action_bar_text", creativePreview.getActionBarText());  // 行动号召按钮文案
+            }
+            if (!Check.isNull(creativePreview.getDescription())) {
+                createJson.put("description", creativePreview.getDescription());  // 广告语
+            }
+            if (!Check.isNull(creativePreview.getStickerTitle())) {
+                createJson.put("sticker_title", creativePreview.getStickerTitle());  // 封面广告语标题
+            }
+            if (!Check.isNull(creativePreview.getOverlayType())) {
+                createJson.put("overlay_type", creativePreview.getOverlayType());  // 贴纸样式类型
+            }
+                /*if (!Check.isNull(creativePreview.getCreativeTag())) {
+                    createJson.put("expose_tag", JSONObject.parseArray(creativePreview.getCreativeTag()));  // 广告标签
+                }
+                if (!Check.isNull(creativePreview.getJSONArray("new_expose_tag"))) {
+                    createJson.put("new_expose_tag", creativePreview.getJSONArray("new_expose_tag"));  // 广告标签2期
+                }*/
+            if (!Check.isNull(creativePreview.getSiteId())) {
+                createJson.put("site_id", creativePreview.getSiteId());  // 安卓下载中间页ID
+            }
+            if (!Check.isNull(creativePreview.getClickTrackUrl())) {
+                createJson.put("click_track_url", creativePreview.getClickTrackUrl());  // 第三方点击检测链接
+            }
+            if (!Check.isNull(creativePreview.getImpressionUrl())) {
+                createJson.put("impression_url", creativePreview.getImpressionUrl());  // 第三方开始播放监测链接
+            }
+            if (!Check.isNull(creativePreview.getAdPhotoPlayedT3sUrl())) {
+                createJson.put("ad_photo_played_t3s_url", creativePreview.getAdPhotoPlayedT3sUrl());  // 第三方有效播放监测链接
+            }
+            if (!Check.isNull(creativePreview.getActionbarClickUrl())) {
+                createJson.put("actionbar_click_url", creativePreview.getActionbarClickUrl());  // 第三方点击按钮监测链接
+            }
+            if (!Check.isNull(creativePreview.getCreativeCategory())) {
+                createJson.put("creative_category", creativePreview.getCreativeCategory());  // 创意分类
+            }
+            if (!Check.isNull(creativePreview.getCreativeTag())) {
+                createJson.put("creative_tag", JSONObject.parseArray(creativePreview.getCreativeTag()));  // 创意标签
+            }
+            String image_md5 = creativePreview.getImageSignature();
+            String imageToken = null;
+            if (!Check.isNull(image_md5)) {
+                imageToken = getImageToken(image_md5, oauthToken.getAccountId(), oauthToken.getAccessToken());
+            }
+            if (!Check.isNull(imageToken)) {
+                createJson.put("image_token", imageToken); // 自定义创意封面token
+            }
+            Map<String, Object> creativeMap = kuaishouInterfaceService.creativeCreate(oauthToken.getAccessToken(), oauthToken.getAccountId(), createJson, 1);
+            JSONObject returnJson = new JSONObject();
+            Integer code = (Integer) creativeMap.get("code");
+            if (code == 0) {
+                Long creativeId = (Long) creativeMap.get("creativeId");
+                updateStatus.setIsSuccess(1);
+                updateStatus.setMessage((String) creativeMap.get("message"));
+                updateStatus.setCreativeId(creativeId);
+            } else {
+                updateStatus.setIsSuccess(0);
+                updateStatus.setMessage((String) creativeMap.get("message"));
+            }
+        } catch (Exception e) {
+            log.error("创建广告创意过程中调用快手接口异常", e);
+            updateStatus.setIsSuccess(0);
+            updateStatus.setMessage("创建广告创意过程中调用快手接口异常");
+        }
+        creativePreviewMapper.updateById(updateStatus);
+    }
+
+    /**
+     * 根据封面MD5 获取imageToken
+     *
+     * @param md5
+     * @param accountId
+     * @param accessToken
+     * @return
+     */
+    private String getImageToken(String md5, Long accountId, String accessToken) {
+        String imageToken = null;
+        QueryWrapper<KuaiShouImageGet> queryWrapper = new QueryWrapper<>();
+        queryWrapper.eq("account_id", accountId);
+        queryWrapper.eq("signature", md5);
+        queryWrapper.last("limit 1");
+        KuaiShouImageGet imageGet = imageGetService.getOne(queryWrapper);
+        if (!Check.isNull(imageGet)) {
+            imageToken = imageGet.getImageToken();
+        } else {
+            MaterialCutFrame cutFrame = cutFrameService.selectByMd5(md5);
+            if (!Check.isNull(cutFrame)) {
+                imageToken = uploadService.kuauiShouImageUpload(cutFrame.getUrl(), md5, accountId, accessToken);
+            }
+        }
+        return imageToken;
+    }
 }

+ 10 - 10
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/service/impl/KuaishouInterfaceServiceImpl.java

@@ -2,9 +2,11 @@ package cn.com.ctop.kuaishou.modules.batch.service.impl;
 
 import cn.com.ctop.common.module.entity.CtopOauthToken;
 import cn.com.ctop.common.module.entity.MaterialCutFrame;
+import cn.com.ctop.common.module.entity.OauthConfig;
 import cn.com.ctop.common.module.entity.UserAllocation;
 import cn.com.ctop.common.module.enums.MaterialEnum;
 import cn.com.ctop.common.module.service.IMaterialCutFrameService;
+import cn.com.ctop.common.module.service.IOauthConfigService;
 import cn.com.ctop.common.module.service.IUserAllocationService;
 import cn.com.ctop.common.module.utils.*;
 import cn.com.ctop.kuaishou.modules.batch.entity.*;
@@ -1870,20 +1872,18 @@ public class KuaishouInterfaceServiceImpl implements IKuaishouInterfaceService {
      * @param authCode
      * @return
      */
+    @Autowired
+    private IOauthConfigService configService;
+
     @Override
-    public KuaishouResultToken getAccessToken(String authCode, Integer agentType) {
+    public KuaishouResultToken getAccessToken(String authCode, Long appId) {
         String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.AUTH_TOKEN;
         JSONObject requestJson = new JSONObject();
         requestJson.put("auth_code", authCode);
 
-        if (agentType == 1) { // 本代理商开户
-            requestJson.put("app_id", PropertiesUtils.getConfig("kuaishou_appid"));
-            requestJson.put("secret", PropertiesUtils.getConfig("kuaishou_secret"));
-        } else if (agentType == 0) {
-            requestJson.put("app_id", PropertiesUtils.getConfig("kuaishou_third_appid"));
-            requestJson.put("secret", PropertiesUtils.getConfig("kuaishou_third_secret"));
-        }
-
+        OauthConfig config = configService.getConfigByAppId(appId);
+        requestJson.put("app_id", config.getAppId());
+        requestJson.put("secret", config.getSecret());
         Map<String, String> headers = new HashMap<>();
         headers.put("Content-Type", " application/json");
         KuaishouResultToken kuaiShouResult = null;
@@ -2975,7 +2975,7 @@ public class KuaishouInterfaceServiceImpl implements IKuaishouInterfaceService {
                     @Override
                     public void run() {
                         List<MaterialCutFrame> cutFrames = cutFrameService.getListByVideoSignature(md5);
-                        if(null==cutFrames||cutFrames.isEmpty()){
+                        if (null == cutFrames || cutFrames.isEmpty()) {
                             videoGetService.getKeyFrame(token, accountId, md5, String.valueOf(photo_id));
                         }
                     }

+ 7 - 5
module-kuaishou/src/main/java/cn/com/ctop/kuaishou/modules/batch/service/impl/KuaishouTemplateServiceImpl.java

@@ -46,6 +46,9 @@ public class KuaishouTemplateServiceImpl extends ServiceImpl<KuaishouTemplateMap
         JSONObject resultJson = JSONObject.parseObject(result);
         if (!Check.isNull(resultJson)) {
             Integer code = resultJson.getInteger("code");
+         /*   Map<String, Object> deleteMap = new HashMap<>();
+            deleteMap.put("account_id", accountId);
+            this.removeByMap(deleteMap);*/
             if (code == 0) {
                 JSONObject dataJson = resultJson.getJSONObject("data");
                 if (Check.isNull(dataJson)) {
@@ -344,14 +347,16 @@ public class KuaishouTemplateServiceImpl extends ServiceImpl<KuaishouTemplateMap
             if (Check.isNull(requestJson.getString("templateName"))) {
                 throw new Exception("定向模板名称为必传项");
             }
+            if (Check.isNull(requestJson.getLong("templateId"))) {
+                throw new Exception("定向模板id为必传项");
+            }
 
             JSONObject param = new JSONObject();
             param.put("template_id", requestJson.getLong("templateId"));
             param.put("advertiser_id", accountId);
-            if(!Check.isNull(requestJson.getString("templateName"))){
+            if (!Check.isNull(requestJson.getString("templateName"))) {
                 param.put("template_name", requestJson.getString("templateName"));
             }
-
             JSONObject targetJson = new JSONObject();
             if (!Check.isNull(requestJson.getJSONArray("region"))) {
                 targetJson.put("region", requestJson.getJSONArray("region"));
@@ -449,15 +454,12 @@ public class KuaishouTemplateServiceImpl extends ServiceImpl<KuaishouTemplateMap
             if (!Check.isNull(targetJson)) {
                 param.put("target", targetJson);
             }
-
             Map<String, String> headers = new HashMap<String, String>();
             headers.put("Access-Token", accessToken);
             headers.put("Content-Type", " application/json");
-            System.err.println("入参:" + param.toJSONString());
             String url = PropertiesUtils.getConfig("kuaishou_api_url") + KuaishouInterfaceConstant.TEMPLATE_UPDATE;
             String result = HttpUtils.kuaiShouhttpPostRequest(url, param.toJSONString(), headers);
             JSONObject resultJson = JSONObject.parseObject(result);
-            System.err.println("返回:" + resultJson.toJSONString());
             if (!Check.isNull(resultJson)) {
                 Integer code = resultJson.getInteger("code");
                 if (code == 0) {