瀏覽代碼

Merge branch 'dev-xym-add-send-request' into test

xueyiming 2 月之前
父節點
當前提交
cebd29f785
共有 19 個文件被更改,包括 486 次插入59 次删除
  1. 40 9
      api-module/src/main/java/com/tzld/piaoquan/api/controller/TencentWeComController.java
  2. 7 0
      api-module/src/main/java/com/tzld/piaoquan/api/controller/WeComUserController.java
  3. 2 2
      api-module/src/main/java/com/tzld/piaoquan/api/dao/generator/MybatisGeneratorMain.java
  4. 17 8
      api-module/src/main/java/com/tzld/piaoquan/api/service/contentplatform/impl/ContentPlatformAccountServiceImpl.java
  5. 3 1
      api-module/src/main/resources/mybatis-generator-config.xml
  6. 4 0
      common-module/src/main/java/com/tzld/piaoquan/growth/common/common/constant/WeComConstant.java
  7. 11 0
      common-module/src/main/java/com/tzld/piaoquan/growth/common/model/po/UserWithTag.java
  8. 60 1
      common-module/src/main/java/com/tzld/piaoquan/growth/common/model/po/UserWithTagExample.java
  9. 13 0
      common-module/src/main/java/com/tzld/piaoquan/growth/common/model/vo/SendRequestParam.java
  10. 16 0
      common-module/src/main/java/com/tzld/piaoquan/growth/common/model/vo/UserTagParam.java
  11. 10 1
      common-module/src/main/java/com/tzld/piaoquan/growth/common/service/Impl/MessageAttachmentServiceImpl.java
  12. 10 1
      common-module/src/main/java/com/tzld/piaoquan/growth/common/service/Impl/MessageServiceImpl.java
  13. 61 0
      common-module/src/main/java/com/tzld/piaoquan/growth/common/service/Impl/WeComServiceImpl.java
  14. 156 4
      common-module/src/main/java/com/tzld/piaoquan/growth/common/service/Impl/WeComUserServiceImpl.java
  15. 13 0
      common-module/src/main/java/com/tzld/piaoquan/growth/common/service/WeComService.java
  16. 11 0
      common-module/src/main/java/com/tzld/piaoquan/growth/common/service/WeComUserService.java
  17. 20 5
      common-module/src/main/resources/mapper/UserWithTagMapper.xml
  18. 11 1
      offline-module/src/main/java/com/tzld/piaoquan/offline/job/WeComStaffDataJob.java
  19. 21 26
      offline-module/src/main/java/com/tzld/piaoquan/offline/job/WeComUserDataJob.java

+ 40 - 9
api-module/src/main/java/com/tzld/piaoquan/api/controller/TencentWeComController.java

@@ -1,26 +1,29 @@
 package com.tzld.piaoquan.api.controller;
 
 import com.alibaba.fastjson.JSONObject;
+import com.tzld.piaoquan.growth.common.model.vo.SendRequestParam;
 import com.tzld.piaoquan.api.service.WeComAutoReply;
 import com.tzld.piaoquan.growth.common.common.constant.WeComServerConstant;
+import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
 import com.tzld.piaoquan.growth.common.service.WeComUserService;
 import com.tzld.piaoquan.growth.common.utils.wecom.WXBizMsgCrypt;
 import com.tzld.piaoquan.growth.common.utils.wecom.WxUtil;
 import lombok.extern.slf4j.Slf4j;
+import lombok.val;
 import org.apache.commons.lang3.StringUtils;
+import org.apache.ibatis.annotations.Param;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.multipart.MultipartFile;
 
 import javax.servlet.ServletInputStream;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import java.io.BufferedReader;
-import java.io.InputStreamReader;
-import java.io.PrintWriter;
+import java.io.*;
+import java.nio.file.Files;
+import java.nio.file.Paths;
 import java.util.Map;
+import java.util.UUID;
 
 import static com.tzld.piaoquan.growth.common.common.enums.CorpEnum.HNWQ;
 import static com.tzld.piaoquan.growth.common.common.enums.CorpEnum.YLQ;
@@ -37,6 +40,9 @@ public class TencentWeComController {
     @Autowired
     private WeComAutoReply weComAutoReply;
 
+    @Autowired
+    private HttpPoolClient httpPoolClient;
+
     @GetMapping("/verify")
     public void verifyGet(HttpServletRequest request, HttpServletResponse response) {
         try {
@@ -201,7 +207,7 @@ public class TencentWeComController {
                     String userId = (String) suiteMap.get("UserID");
                     String externalUserId = (String) suiteMap.get("ExternalUserID");
                     String welcomeCode = (String) suiteMap.get("WelcomeCode");
-                    log.info("addStaffWithUser userId={} externalUserId={}", userId, externalUserId);
+                    log.info("YLQ addStaffWithUser userId={} externalUserId={}", userId, externalUserId);
                     weComUserService.addStaffWithUser(externalUserId, userId, YLQ.getId());
                     weComAutoReply.AutoReplyMessage(welcomeCode, externalUserId, userId, YLQ.getId());
                 }
@@ -209,7 +215,7 @@ public class TencentWeComController {
                 if (StringUtils.isNotEmpty(changeType) && changeType.equals("del_follow_user")) {
                     String userId = (String) suiteMap.get("UserID");
                     String externalUserId = (String) suiteMap.get("ExternalUserID");
-                    log.info("delStaffWithUser userId={} externalUserId={}", userId, externalUserId);
+                    log.info("YLQ delStaffWithUser userId={} externalUserId={}", userId, externalUserId);
                     weComUserService.delStaffWithUser(externalUserId, userId, YLQ.getId(), System.currentTimeMillis());
                 }
             }
@@ -219,4 +225,29 @@ public class TencentWeComController {
         String success = "success";
         return success;
     }
+
+
+    @PostMapping("/send/post")
+    public String sendPost(@RequestBody SendRequestParam sendRequestParam) throws IOException {
+        log.info("sendPost sendRequestParam={}", sendRequestParam);
+        return httpPoolClient.post(sendRequestParam.getUrl(), sendRequestParam.getParam());
+    }
+
+    @PostMapping("/send/post/file")
+    public String sendPostFile(@RequestParam String url, @RequestParam("media") MultipartFile multipartFile) throws IOException {
+        String filePath = UUID.randomUUID() + ".jpg";
+        File file = new File(filePath);
+        // 将MultipartFile的内容传输到File中
+        multipartFile.transferTo(file);
+        log.info("sendPostFile url={}", url);
+        String post = httpPoolClient.post(url, file);
+        Files.delete(Paths.get(filePath));
+        return post;
+    }
+
+    @GetMapping("/send/get")
+    public String sendGet(@RequestParam String url) throws IOException {
+        log.info("sendGet url={}", url);
+        return httpPoolClient.get(url);
+    }
 }

+ 7 - 0
api-module/src/main/java/com/tzld/piaoquan/api/controller/WeComUserController.java

@@ -3,6 +3,7 @@ package com.tzld.piaoquan.api.controller;
 import com.tzld.piaoquan.api.model.vo.WeComUserNameAvatarParam;
 import com.tzld.piaoquan.growth.common.common.base.CommonResponse;
 import com.tzld.piaoquan.growth.common.model.bo.GroupSendWeComUserParam;
+import com.tzld.piaoquan.growth.common.model.vo.UserTagParam;
 import com.tzld.piaoquan.growth.common.model.vo.WeComUserVo;
 import com.tzld.piaoquan.growth.common.service.WeComUserService;
 import com.tzld.piaoquan.growth.common.utils.page.Page;
@@ -37,4 +38,10 @@ public class WeComUserController {
         log.info("param={}", param);
         return CommonResponse.success(service.getGroupSendWeComUser(param));
     }
+
+    @PostMapping("/add/tag")
+    public CommonResponse<Void> addUserTag(@RequestBody UserTagParam userTagParam) {
+        log.info("addUserTag param={}", userTagParam);
+        return service.addUserTag(userTagParam);
+    }
 }

+ 2 - 2
api-module/src/main/java/com/tzld/piaoquan/api/dao/generator/MybatisGeneratorMain.java

@@ -20,9 +20,9 @@ public class MybatisGeneratorMain {
             throws SQLException, IOException, InterruptedException, InvalidConfigurationException, XMLParserException {
         List<String> warnings = new ArrayList<>();
 
-//        File configFile = new File(MybatisGeneratorMain.class.getResource("/mybatis-generator-config.xml").getFile());
+        File configFile = new File(MybatisGeneratorMain.class.getResource("/mybatis-generator-config.xml").getFile());
 //        File configFile = new File(MybatisGeneratorMain.class.getResource("/mybatis-api-generator-config.xml").getFile());
-        File configFile = new File(MybatisGeneratorMain.class.getResource("/mybatis-api-contentPlatform-generator-config.xml").getFile());
+//        File configFile = new File(MybatisGeneratorMain.class.getResource("/mybatis-api-contentPlatform-generator-config.xml").getFile());
         ConfigurationParser cp = new ConfigurationParser(warnings);
         Configuration config = cp.parseConfiguration(configFile);
         DefaultShellCallback callback = new DefaultShellCallback(true);

+ 17 - 8
api-module/src/main/java/com/tzld/piaoquan/api/service/contentplatform/impl/ContentPlatformAccountServiceImpl.java

@@ -100,15 +100,17 @@ public class ContentPlatformAccountServiceImpl implements ContentPlatformAccount
 
     private void saveTokenToRedis(AccountLoginVO loginInfo, String oldToken, String token) {
         String tokenPrefix = "login.{token}";
-        // 清除老token
-        if (StringUtils.hasText(oldToken)) {
-            String info = redisUtils.getString(tokenPrefix.replace("{token}", oldToken));
-            if (StringUtils.hasText(info)) {
-                redisUtils.del(tokenPrefix.replace("{token}", oldToken));
-            }
-        }
+//        // 清除老token
+//        if (StringUtils.hasText(oldToken)) {
+//            String info = redisUtils.getString(tokenPrefix.replace("{token}", oldToken));
+//            if (StringUtils.hasText(info)) {
+//                redisUtils.del(tokenPrefix.replace("{token}", oldToken));
+//            }
+//        }
         String redisKey = tokenPrefix.replace("{token}", token);
         redisUtils.setValueWithExpire(redisKey, JSON.toJSONString(loginInfo), 7 * 24 * 60 * 60L);
+        String tokenListKey = "login.account.token.list." + loginInfo.getTelNum();
+        redisUtils.listLeftPush(tokenListKey, token);
     }
 
     @Override
@@ -168,7 +170,14 @@ public class ContentPlatformAccountServiceImpl implements ContentPlatformAccount
         account.setUpdateTimestamp(System.currentTimeMillis());
         accountMapper.updateByPrimaryKeySelective(account);
         // 清除token
-        redisUtils.del("login." + account.getToken());
+        String tokenListKey = "login.account.token.list." + account.getTelNum();
+        while(true) {
+            String token = redisUtils.listRightPop(tokenListKey);
+            if (!StringUtils.hasText(token)) {
+                return;
+            }
+            redisUtils.del("login." + token);
+        }
     }
 
     @Override

+ 3 - 1
api-module/src/main/resources/mybatis-generator-config.xml

@@ -55,9 +55,11 @@
 <!--        <table tableName="we_com_guarantees_video" domainObjectName="GuaranteesVideo" alias=""/>-->
 <!--        <table tableName="we_com_staff" domainObjectName="Staff" alias=""/>-->
 <!--        <table tableName="we_com_message_attachment" domainObjectName="MessageAttachment" alias=""/>-->
-        <table tableName="we_com_special_pre_send_message" domainObjectName="PreSpecialSendMessage" alias=""/>
+<!--        <table tableName="we_com_special_pre_send_message" domainObjectName="PreSpecialSendMessage" alias=""/>-->
 <!--        <table tableName="we_com_send_msg_result" domainObjectName="SendMsgResult" alias=""/>-->
 <!--        <table tableName="we_com_corp" domainObjectName="Corp" alias=""/>-->
+        <table tableName="we_com_user_with_tag" domainObjectName="UserWithTag" alias=""/>
+
 
     </context>
 

+ 4 - 0
common-module/src/main/java/com/tzld/piaoquan/growth/common/common/constant/WeComConstant.java

@@ -37,4 +37,8 @@ public interface WeComConstant {
 
     //发送新客户欢迎语
     String POST_WE_COM_SEND_WELCOME_MSG = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/send_welcome_msg";
+
+
+    //用户增加新标签
+    String POST_WE_COM_ADD_USER_TAG = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/mark_tag";
 }

+ 11 - 0
common-module/src/main/java/com/tzld/piaoquan/growth/common/model/po/UserWithTag.java

@@ -9,6 +9,8 @@ public class UserWithTag {
 
     private Long tagId;
 
+    private Integer status;
+
     private Integer isDelete;
 
     private Date createTime;
@@ -39,6 +41,14 @@ public class UserWithTag {
         this.tagId = tagId;
     }
 
+    public Integer getStatus() {
+        return status;
+    }
+
+    public void setStatus(Integer status) {
+        this.status = status;
+    }
+
     public Integer getIsDelete() {
         return isDelete;
     }
@@ -72,6 +82,7 @@ public class UserWithTag {
         sb.append(", id=").append(id);
         sb.append(", userId=").append(userId);
         sb.append(", tagId=").append(tagId);
+        sb.append(", status=").append(status);
         sb.append(", isDelete=").append(isDelete);
         sb.append(", createTime=").append(createTime);
         sb.append(", updateTime=").append(updateTime);

+ 60 - 1
common-module/src/main/java/com/tzld/piaoquan/growth/common/model/po/UserWithTagExample.java

@@ -1,7 +1,6 @@
 package com.tzld.piaoquan.growth.common.model.po;
 
 import com.tzld.piaoquan.growth.common.utils.page.Page;
-
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
@@ -297,6 +296,66 @@ public class UserWithTagExample {
             return (Criteria) this;
         }
 
+        public Criteria andStatusIsNull() {
+            addCriterion("`status` is null");
+            return (Criteria) this;
+        }
+
+        public Criteria andStatusIsNotNull() {
+            addCriterion("`status` is not null");
+            return (Criteria) this;
+        }
+
+        public Criteria andStatusEqualTo(Integer value) {
+            addCriterion("`status` =", value, "status");
+            return (Criteria) this;
+        }
+
+        public Criteria andStatusNotEqualTo(Integer value) {
+            addCriterion("`status` <>", value, "status");
+            return (Criteria) this;
+        }
+
+        public Criteria andStatusGreaterThan(Integer value) {
+            addCriterion("`status` >", value, "status");
+            return (Criteria) this;
+        }
+
+        public Criteria andStatusGreaterThanOrEqualTo(Integer value) {
+            addCriterion("`status` >=", value, "status");
+            return (Criteria) this;
+        }
+
+        public Criteria andStatusLessThan(Integer value) {
+            addCriterion("`status` <", value, "status");
+            return (Criteria) this;
+        }
+
+        public Criteria andStatusLessThanOrEqualTo(Integer value) {
+            addCriterion("`status` <=", value, "status");
+            return (Criteria) this;
+        }
+
+        public Criteria andStatusIn(List<Integer> values) {
+            addCriterion("`status` in", values, "status");
+            return (Criteria) this;
+        }
+
+        public Criteria andStatusNotIn(List<Integer> values) {
+            addCriterion("`status` not in", values, "status");
+            return (Criteria) this;
+        }
+
+        public Criteria andStatusBetween(Integer value1, Integer value2) {
+            addCriterion("`status` between", value1, value2, "status");
+            return (Criteria) this;
+        }
+
+        public Criteria andStatusNotBetween(Integer value1, Integer value2) {
+            addCriterion("`status` not between", value1, value2, "status");
+            return (Criteria) this;
+        }
+
         public Criteria andIsDeleteIsNull() {
             addCriterion("is_delete is null");
             return (Criteria) this;

+ 13 - 0
common-module/src/main/java/com/tzld/piaoquan/growth/common/model/vo/SendRequestParam.java

@@ -0,0 +1,13 @@
+package com.tzld.piaoquan.growth.common.model.vo;
+
+import lombok.Data;
+import lombok.ToString;
+
+@Data
+@ToString
+public class SendRequestParam {
+
+    private String url;
+
+    private String param;
+}

+ 16 - 0
common-module/src/main/java/com/tzld/piaoquan/growth/common/model/vo/UserTagParam.java

@@ -0,0 +1,16 @@
+package com.tzld.piaoquan.growth.common.model.vo;
+
+import lombok.Data;
+import lombok.ToString;
+
+@Data
+@ToString
+public class UserTagParam {
+
+    private String tagGroupName;
+
+    private String tagName;
+
+    private String unionId;
+
+}

+ 10 - 1
common-module/src/main/java/com/tzld/piaoquan/growth/common/service/Impl/MessageAttachmentServiceImpl.java

@@ -14,6 +14,7 @@ import com.tzld.piaoquan.growth.common.model.po.*;
 import com.tzld.piaoquan.growth.common.model.vo.GuaranteedParam;
 import com.tzld.piaoquan.growth.common.service.WeComAccessTokenService;
 import com.tzld.piaoquan.growth.common.service.MessageAttachmentService;
+import com.tzld.piaoquan.growth.common.service.WeComService;
 import com.tzld.piaoquan.growth.common.utils.DateUtil;
 import com.tzld.piaoquan.growth.common.utils.LarkRobotUtil;
 import lombok.extern.slf4j.Slf4j;
@@ -62,6 +63,9 @@ public class MessageAttachmentServiceImpl implements MessageAttachmentService {
     @Autowired
     private GuaranteesVideoMapper guaranteesVideoMapper;
 
+    @Autowired
+    private WeComService weComService;
+
     @Override
     public List<Long> addMessageAttachment(List<MessageAttachment> messageAttachmentList, Long createTime) {
         List<Long> messageAttachmentIds = new ArrayList<>();
@@ -342,7 +346,12 @@ public class MessageAttachmentServiceImpl implements MessageAttachmentService {
             File file = new File(filePath);
             String weComAccessToken = weComAccessTokenService.getWeComAccessToken(corpId);
             String url = String.format(POST_WE_COM_MEDIA_UPLOAD + "?access_token=%s&type=%s", weComAccessToken, "image");
-            String res = httpPoolClient.post(url, file);
+            String res;
+            if (corpId == 1L) {
+                res = httpPoolClient.post(url, file);
+            } else {
+                res = weComService.sendPostFile(url, file);
+            }
             JSONObject jsonObject = JSONObject.parseObject(res);
             if (jsonObject != null && jsonObject.getInteger("errcode") == 0) {
                 mediaId = jsonObject.getString("media_id");

+ 10 - 1
common-module/src/main/java/com/tzld/piaoquan/growth/common/service/Impl/MessageServiceImpl.java

@@ -10,6 +10,7 @@ import com.tzld.piaoquan.growth.common.model.po.PreSpecialSendMessage;
 import com.tzld.piaoquan.growth.common.model.po.PreSpecialSendMessageExample;
 import com.tzld.piaoquan.growth.common.service.WeComAccessTokenService;
 import com.tzld.piaoquan.growth.common.service.MessageService;
+import com.tzld.piaoquan.growth.common.service.WeComService;
 import com.tzld.piaoquan.growth.common.utils.DateUtil;
 import com.tzld.piaoquan.growth.common.utils.LarkRobotUtil;
 import lombok.extern.slf4j.Slf4j;
@@ -40,6 +41,9 @@ public class MessageServiceImpl implements MessageService {
     @Autowired
     private PreSpecialSendMessageMapper preSpecialSendMessageMapper;
 
+    @Autowired
+    private WeComService weComService;
+
 
     @Override
     public boolean pushWeComMessage(JSONObject jsonObject, Long corpId) {
@@ -47,7 +51,12 @@ public class MessageServiceImpl implements MessageService {
             String accessToken = weComAccessTokenService.getWeComAccessToken(corpId);
             String url = POST_WE_COM_ADD_MSG_TEMPLATE
                     + "?access_token=" + accessToken;
-            String s = httpPoolClient.post(url, jsonObject.toJSONString());
+            String s;
+            if (corpId == 1L) {
+                s = httpPoolClient.post(url, jsonObject.toJSONString());
+            } else {
+                s = weComService.sendPost(url, jsonObject.toJSONString());
+            }
             JSONObject res = JSONObject.parseObject(s);
             log.info("pushWeComMessage res={}", res);
             Integer code = res.getInteger("errcode");

+ 61 - 0
common-module/src/main/java/com/tzld/piaoquan/growth/common/service/Impl/WeComServiceImpl.java

@@ -0,0 +1,61 @@
+package com.tzld.piaoquan.growth.common.service.Impl;
+
+import com.alibaba.fastjson.JSON;
+import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
+import com.tzld.piaoquan.growth.common.model.vo.SendRequestParam;
+import com.tzld.piaoquan.growth.common.service.WeComService;
+import com.tzld.piaoquan.growth.common.service.WeComUserService;
+import com.tzld.piaoquan.growth.common.utils.LarkRobotUtil;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Service;
+
+import java.io.File;
+import java.io.IOException;
+
+@Service
+public class WeComServiceImpl implements WeComService {
+
+    @Autowired
+    private HttpPoolClient httpPoolClient;
+
+    @Value("${sendRequestIp:}")
+    private String sendRequestIp;
+
+
+    @Override
+    public String sendPost(String url, String param) throws IOException {
+        if (StringUtils.isEmpty(sendRequestIp)) {
+            LarkRobotUtil.sendMessage("转发ip获取失败");
+            return null;
+        }
+        String sendUrl = "http://" + sendRequestIp + "/wecom/server/send/post";
+        SendRequestParam sendRequestParam = new SendRequestParam();
+        sendRequestParam.setUrl(url);
+        sendRequestParam.setParam(param);
+        return httpPoolClient.post(sendUrl, JSON.toJSONString(sendRequestParam));
+    }
+
+    @Override
+    public String sendGet(String url) throws IOException {
+        if (StringUtils.isEmpty(sendRequestIp)) {
+            LarkRobotUtil.sendMessage("转发ip获取失败");
+            return null;
+        }
+        String sendUrl = "http://" + sendRequestIp + "/wecom/server/send/get";
+        sendUrl += "?url=" + url;
+        return httpPoolClient.get(sendUrl);
+    }
+
+    @Override
+    public String sendPostFile(String url, File file) throws IOException {
+        if (StringUtils.isEmpty(sendRequestIp)) {
+            LarkRobotUtil.sendMessage("转发ip获取失败");
+            return null;
+        }
+        String sendUrl = "http://" + sendRequestIp + "/wecom/server/send/post/file";
+        sendUrl += "?url=" + url;
+        return httpPoolClient.post(sendUrl, file);
+    }
+}

+ 156 - 4
common-module/src/main/java/com/tzld/piaoquan/growth/common/service/Impl/WeComUserServiceImpl.java

@@ -2,16 +2,15 @@ package com.tzld.piaoquan.growth.common.service.Impl;
 
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
+import com.tzld.piaoquan.growth.common.common.base.CommonResponse;
 import com.tzld.piaoquan.growth.common.common.enums.PreSpecialStatusEnum;
 import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
-import com.tzld.piaoquan.growth.common.dao.mapper.StaffMapper;
-import com.tzld.piaoquan.growth.common.dao.mapper.StaffWithUserMapper;
-import com.tzld.piaoquan.growth.common.dao.mapper.UserWithTagMapper;
-import com.tzld.piaoquan.growth.common.dao.mapper.WeComUserMapper;
+import com.tzld.piaoquan.growth.common.dao.mapper.*;
 import com.tzld.piaoquan.growth.common.dao.mapper.ext.WeComUserMapperExt;
 import com.tzld.piaoquan.growth.common.model.bo.GroupSendWeComUserParam;
 import com.tzld.piaoquan.growth.common.model.bo.WeComUserBo;
 import com.tzld.piaoquan.growth.common.model.po.*;
+import com.tzld.piaoquan.growth.common.model.vo.UserTagParam;
 import com.tzld.piaoquan.growth.common.model.vo.WeComUserVo;
 import com.tzld.piaoquan.growth.common.service.WeComAccessTokenService;
 import com.tzld.piaoquan.growth.common.service.WeComUserService;
@@ -32,6 +31,7 @@ import java.util.*;
 import java.util.stream.Collectors;
 
 import static com.tzld.piaoquan.growth.common.common.constant.WeComConstant.GET_WE_COM_EXTERNAL_CONTACT_GET;
+import static com.tzld.piaoquan.growth.common.common.constant.WeComConstant.POST_WE_COM_ADD_USER_TAG;
 
 @Slf4j
 @Service
@@ -57,6 +57,9 @@ public class WeComUserServiceImpl implements WeComUserService {
     @Autowired
     private UserWithTagMapper userWithTagMapper;
 
+    @Autowired
+    private TagMapper tagMapper;
+
     @Value("${needFilterTagIdConfig:[]}")
     private String needFilterTagIdConfig;
 
@@ -359,4 +362,153 @@ public class WeComUserServiceImpl implements WeComUserService {
         }
         return allStaffs;
     }
+
+    @Override
+    public CommonResponse<Void> addUserTag(UserTagParam userTagParam) {
+        if (userTagParam == null
+                || StringUtils.isEmpty(userTagParam.getUnionId())
+                || StringUtils.isEmpty(userTagParam.getTagGroupName())
+                || StringUtils.isEmpty(userTagParam.getTagName())) {
+            return CommonResponse.create(500, "参数错误");
+        }
+        TagExample example = new TagExample();
+        example.createCriteria().andTagGroupNameEqualTo(userTagParam.getTagGroupName())
+                .andTagNameEqualTo(userTagParam.getTagName())
+                .andIsDeleteEqualTo(0);
+        List<Tag> tags = tagMapper.selectByExample(example);
+        if (CollectionUtils.isEmpty(tags)) {
+            return CommonResponse.create(500, "标签不存在");
+        }
+        Tag tag = tags.get(0);
+        WeComUserExample userExample = new WeComUserExample();
+        userExample.createCriteria().andUnionIdEqualTo(userTagParam.getUnionId());
+        List<WeComUser> weComUsers = weComUserMapper.selectByExample(userExample);
+        if (CollectionUtils.isEmpty(weComUsers)) {
+            return CommonResponse.create(500, "用户不存在");
+        }
+        WeComUser weComUser = weComUsers.get(0);
+        UserWithTag userWithTag = new UserWithTag();
+        userWithTag.setTagId(tag.getId());
+        userWithTag.setUserId(weComUser.getId());
+        boolean b = addUserWithTag(userWithTag);
+        if (b) {
+            boolean b1 = addWeComTag(tag, weComUser);
+            if (!b1) {
+                UserWithTag record = new UserWithTag();
+                record.setStatus(2);
+                UserWithTagExample userWithTagExample = new UserWithTagExample();
+                userWithTagExample.createCriteria().andUserIdEqualTo(userWithTag.getUserId()).andTagIdEqualTo(userWithTag.getTagId());
+                userWithTagMapper.updateByExampleSelective(record, userWithTagExample);
+                LarkRobotUtil.sendMessage("企微添加标签失败 tagId=" + tag.getId() + "   userId=" + weComUser.getId());
+            }
+        } else {
+            return CommonResponse.create(500, "添加失败");
+        }
+        return CommonResponse.success();
+    }
+
+    private boolean addWeComTag(Tag tag, WeComUser weComUser) {
+        if (tag == null || weComUser == null) {
+            return false;
+        }
+        try {
+            String accessToken = weComAccessTokenService.getWeComAccessToken(weComUser.getCorpId());
+            JSONArray jsonArray = new JSONArray();
+            jsonArray.add(tag.getTagId());
+            StaffWithUserExample staffWithUserExample = new StaffWithUserExample();
+            staffWithUserExample.createCriteria().andUserIdEqualTo(weComUser.getId()).andIsDeleteEqualTo(0);
+            List<StaffWithUser> staffWithUsers = staffWithUserMapper.selectByExample(staffWithUserExample);
+            if (!CollectionUtils.isEmpty(staffWithUsers)) {
+                JSONObject jsonObject = new JSONObject();
+                jsonObject.put("userid", "ShengHuoLeQu");
+                jsonObject.put("external_userid", weComUser.getExternalUserId());
+                jsonObject.put("add_tag", jsonArray);
+                String url = POST_WE_COM_ADD_USER_TAG + "?access_token=" + accessToken;
+                String post = httpPoolClient.post(url, jsonObject.toJSONString());
+                JSONObject jsonObject1 = JSONObject.parseObject(post);
+                if (jsonObject1.getInteger("errcode") == 0) {
+                    return true;
+                }
+            }
+        } catch (Exception e) {
+            log.error("addWeComTag error", e);
+        }
+        return false;
+    }
+
+    public boolean addUserWithTag(UserWithTag userWithTag) {
+        try {
+            UserWithTagExample userWithTagExample = new UserWithTagExample();
+            userWithTagExample.createCriteria().andUserIdEqualTo(userWithTag.getUserId())
+                    .andTagIdEqualTo(userWithTag.getTagId());
+            List<UserWithTag> userWithTags = userWithTagMapper.selectByExample(userWithTagExample);
+            if (CollectionUtils.isEmpty(userWithTags)) {
+                userWithTagMapper.insertSelective(userWithTag);
+            } else {
+                UserWithTag userWithTag1 = userWithTags.get(0);
+                if (userWithTag1.getIsDelete() == 1) {
+                    userWithTag1.setIsDelete(0);
+                    userWithTagMapper.updateByPrimaryKeySelective(userWithTag1);
+                }
+            }
+            return true;
+        } catch (Exception e) {
+            log.error("addUserWithTag error", e);
+        }
+        return false;
+    }
+
+    public boolean delAllUserTag(Long userId) {
+        try {
+            UserWithTagExample userWithTagExample = new UserWithTagExample();
+            userWithTagExample.createCriteria().andUserIdEqualTo(userId).andStatusEqualTo(1);
+            UserWithTag record = new UserWithTag();
+            record.setIsDelete(1);
+            userWithTagMapper.updateByExampleSelective(record, userWithTagExample);
+            return true;
+        } catch (Exception e) {
+            log.error("addUserWithTag error", e);
+        }
+        return false;
+    }
+
+    public void updateUserWithTag(Long userId, List<String> tagIdList) {
+        try {
+            TagExample example = new TagExample();
+            example.createCriteria().andTagIdIn(tagIdList).andIsDeleteEqualTo(0);
+            List<Tag> tags = tagMapper.selectByExample(example);
+            List<Long> tagIds = tags.stream().map(Tag::getId).collect(Collectors.toList());
+            UserWithTagExample userWithTagExample = new UserWithTagExample();
+            userWithTagExample.createCriteria().andUserIdEqualTo(userId).andIsDeleteEqualTo(0);
+            List<UserWithTag> userWithTags = userWithTagMapper.selectByExample(userWithTagExample);
+            List<Long> userTagIds = userWithTags.stream().map(UserWithTag::getTagId).collect(Collectors.toList());
+            userTagIds.removeAll(tagIds);
+            if (!CollectionUtils.isEmpty(userTagIds)) {
+                List<UserWithTag> collect = userWithTags.stream()
+                        .filter(f -> userTagIds.contains(f.getTagId())).collect(Collectors.toList());
+                for (UserWithTag userWithTag : collect) {
+                    if (userWithTag.getStatus() == 2) {
+                        WeComUser weComUser = weComUserMapper.selectByPrimaryKey(userWithTag.getUserId());
+                        Tag tag = tagMapper.selectByPrimaryKey(userWithTag.getTagId());
+                        addWeComTag(tag, weComUser);
+                    } else {
+                        userWithTag.setIsDelete(1);
+                        userWithTagMapper.updateByPrimaryKeySelective(userWithTag);
+                    }
+                }
+            }
+            List<Long> hasUserTagIds = userWithTags.stream().map(UserWithTag::getTagId).collect(Collectors.toList());
+            tagIds.removeAll(hasUserTagIds);
+            if (!CollectionUtils.isEmpty(tagIds)) {
+                for (Long tagId : tagIds) {
+                    UserWithTag userWithTag = new UserWithTag();
+                    userWithTag.setTagId(tagId);
+                    userWithTag.setUserId(userId);
+                    addUserWithTag(userWithTag);
+                }
+            }
+        } catch (Exception e) {
+            log.error("updateUserWithTag error", e);
+        }
+    }
 }

+ 13 - 0
common-module/src/main/java/com/tzld/piaoquan/growth/common/service/WeComService.java

@@ -0,0 +1,13 @@
+package com.tzld.piaoquan.growth.common.service;
+
+import java.io.File;
+import java.io.IOException;
+
+public interface WeComService {
+
+    String sendPost(String url, String param) throws IOException;
+
+    String sendGet(String url) throws IOException;
+
+    String sendPostFile(String url, File file) throws IOException;
+}

+ 11 - 0
common-module/src/main/java/com/tzld/piaoquan/growth/common/service/WeComUserService.java

@@ -1,9 +1,12 @@
 package com.tzld.piaoquan.growth.common.service;
 
 import com.alibaba.fastjson.JSONObject;
+import com.tzld.piaoquan.growth.common.common.base.CommonResponse;
 import com.tzld.piaoquan.growth.common.model.bo.GroupSendWeComUserParam;
 import com.tzld.piaoquan.growth.common.model.po.Staff;
+import com.tzld.piaoquan.growth.common.model.po.UserWithTag;
 import com.tzld.piaoquan.growth.common.model.po.WeComUser;
+import com.tzld.piaoquan.growth.common.model.vo.UserTagParam;
 import com.tzld.piaoquan.growth.common.model.vo.WeComUserVo;
 import com.tzld.piaoquan.growth.common.utils.page.Page;
 
@@ -32,4 +35,12 @@ public interface WeComUserService {
     List<Long> getFilterTagId();
 
     List<Staff> getStaffByUserId(Long userId);
+
+    CommonResponse<Void> addUserTag(UserTagParam userTagParam);
+
+    boolean addUserWithTag(UserWithTag userWithTag);
+
+    boolean delAllUserTag(Long userId);
+
+    void updateUserWithTag(Long userId, List<String> tagIdList);
 }

+ 20 - 5
common-module/src/main/resources/mapper/UserWithTagMapper.xml

@@ -5,6 +5,7 @@
     <id column="id" jdbcType="BIGINT" property="id" />
     <result column="user_id" jdbcType="BIGINT" property="userId" />
     <result column="tag_id" jdbcType="BIGINT" property="tagId" />
+    <result column="status" jdbcType="INTEGER" property="status" />
     <result column="is_delete" jdbcType="INTEGER" property="isDelete" />
     <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
     <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
@@ -68,7 +69,7 @@
     </where>
   </sql>
   <sql id="Base_Column_List">
-    id, user_id, tag_id, is_delete, create_time, update_time
+    id, user_id, tag_id, `status`, is_delete, create_time, update_time
   </sql>
   <select id="selectByExample" parameterType="com.tzld.piaoquan.growth.common.model.po.UserWithTagExample" resultMap="BaseResultMap">
     select
@@ -105,11 +106,11 @@
   </delete>
   <insert id="insert" parameterType="com.tzld.piaoquan.growth.common.model.po.UserWithTag">
     insert into we_com_user_with_tag (id, user_id, tag_id, 
-      is_delete, create_time, update_time
-      )
+      `status`, is_delete, create_time, 
+      update_time)
     values (#{id,jdbcType=BIGINT}, #{userId,jdbcType=BIGINT}, #{tagId,jdbcType=BIGINT}, 
-      #{isDelete,jdbcType=INTEGER}, #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP}
-      )
+      #{status,jdbcType=INTEGER}, #{isDelete,jdbcType=INTEGER}, #{createTime,jdbcType=TIMESTAMP}, 
+      #{updateTime,jdbcType=TIMESTAMP})
   </insert>
   <insert id="insertSelective" parameterType="com.tzld.piaoquan.growth.common.model.po.UserWithTag">
     insert into we_com_user_with_tag
@@ -123,6 +124,9 @@
       <if test="tagId != null">
         tag_id,
       </if>
+      <if test="status != null">
+        `status`,
+      </if>
       <if test="isDelete != null">
         is_delete,
       </if>
@@ -143,6 +147,9 @@
       <if test="tagId != null">
         #{tagId,jdbcType=BIGINT},
       </if>
+      <if test="status != null">
+        #{status,jdbcType=INTEGER},
+      </if>
       <if test="isDelete != null">
         #{isDelete,jdbcType=INTEGER},
       </if>
@@ -172,6 +179,9 @@
       <if test="record.tagId != null">
         tag_id = #{record.tagId,jdbcType=BIGINT},
       </if>
+      <if test="record.status != null">
+        `status` = #{record.status,jdbcType=INTEGER},
+      </if>
       <if test="record.isDelete != null">
         is_delete = #{record.isDelete,jdbcType=INTEGER},
       </if>
@@ -191,6 +201,7 @@
     set id = #{record.id,jdbcType=BIGINT},
       user_id = #{record.userId,jdbcType=BIGINT},
       tag_id = #{record.tagId,jdbcType=BIGINT},
+      `status` = #{record.status,jdbcType=INTEGER},
       is_delete = #{record.isDelete,jdbcType=INTEGER},
       create_time = #{record.createTime,jdbcType=TIMESTAMP},
       update_time = #{record.updateTime,jdbcType=TIMESTAMP}
@@ -207,6 +218,9 @@
       <if test="tagId != null">
         tag_id = #{tagId,jdbcType=BIGINT},
       </if>
+      <if test="status != null">
+        `status` = #{status,jdbcType=INTEGER},
+      </if>
       <if test="isDelete != null">
         is_delete = #{isDelete,jdbcType=INTEGER},
       </if>
@@ -223,6 +237,7 @@
     update we_com_user_with_tag
     set user_id = #{userId,jdbcType=BIGINT},
       tag_id = #{tagId,jdbcType=BIGINT},
+      `status` = #{status,jdbcType=INTEGER},
       is_delete = #{isDelete,jdbcType=INTEGER},
       create_time = #{createTime,jdbcType=TIMESTAMP},
       update_time = #{updateTime,jdbcType=TIMESTAMP}

+ 11 - 1
offline-module/src/main/java/com/tzld/piaoquan/offline/job/WeComStaffDataJob.java

@@ -10,6 +10,7 @@ import com.tzld.piaoquan.growth.common.model.po.CorpExample;
 import com.tzld.piaoquan.growth.common.model.po.Staff;
 import com.tzld.piaoquan.growth.common.model.po.StaffExample;
 import com.tzld.piaoquan.growth.common.service.WeComAccessTokenService;
+import com.tzld.piaoquan.growth.common.service.WeComService;
 import com.tzld.piaoquan.growth.common.utils.LarkRobotUtil;
 import com.xxl.job.core.biz.model.ReturnT;
 import com.xxl.job.core.handler.annotation.XxlJob;
@@ -41,6 +42,9 @@ public class WeComStaffDataJob {
     @Autowired
     private CorpMapper corpMapper;
 
+    @Autowired
+    private WeComService weComService;
+
     @XxlJob("insertStaffJob")
     public ReturnT<String> insertStaff(String param) {
         try {
@@ -84,7 +88,13 @@ public class WeComStaffDataJob {
     private List<String> getCarrierIdList(Long corpId) throws IOException {
         String weComAccessToken = weComAccessTokenService.getWeComAccessToken(corpId);
         String url = String.format(GET_WE_COM_FOLLOW_USER_LIST + "?access_token=%s", weComAccessToken);
-        String res = httpPoolClient.get(url);
+        String res;
+        if (corpId == 1L) {
+            res = httpPoolClient.get(url);
+        } else {
+            res = weComService.sendGet(url);
+        }
+        log.info("getCarrierIdList corp = {}, res={}", corpId, res);
         JSONObject jsonObject = JSONObject.parseObject(res);
         Integer errcode = jsonObject.getInteger("errcode");
         if (errcode == 0) {

+ 21 - 26
offline-module/src/main/java/com/tzld/piaoquan/offline/job/WeComUserDataJob.java

@@ -65,6 +65,7 @@ public class WeComUserDataJob {
     @Autowired
     private WeComStaffService weComStaffService;
 
+
     @XxlJob("updateStaffWithUserJob")
     public ReturnT<String> updateStaffWithUser(String param) {
         XxlJobParam xxlJobParam = new XxlJobParam();
@@ -256,7 +257,7 @@ public class WeComUserDataJob {
             date = param;
         }
         for (Staff staff : staffList) {
-            Map<String, Integer> userCountRes = getUserList(staff, 1L, date);
+            Map<String, Integer> userCountRes = getUserList(staff, date);
             if (userCountRes == null || userCountRes.get("count") == 0) {
                 continue;
             }
@@ -282,14 +283,14 @@ public class WeComUserDataJob {
     }
 
 
-    private Map<String, Integer> getUserList(Staff staff, Long corpId, String date) {
+    private Map<String, Integer> getUserList(Staff staff, String date) {
         Map<String, Integer> result = new HashMap<>();
         int count = 0;
         int newCount = 0;
         try {
             String cursor = "";
             do {
-                String res = getUserDetailList(staff.getCarrierId(), cursor, corpId);
+                String res = getUserDetailList(staff.getCarrierId(), cursor, staff.getCorpId());
                 log.info("getUserList res={} cursor={}", res, cursor);
                 JSONObject jsonObject = JSONObject.parseObject(res);
                 Integer errCode = jsonObject.getInteger("errcode");
@@ -309,22 +310,25 @@ public class WeComUserDataJob {
                     }
                     count++;
                     Long userId = weComUserMapper.selectIdByExternalUserId(externalUserId);
-                    userId = addAndUpdateUser(externalContact, corpId, externalUserId, createAt, staff.getId(), userId);
+                    userId = addAndUpdateUser(externalContact, staff.getCorpId(), externalUserId, createAt, staff.getId(), userId);
                     JSONArray tagIds = followInfo.getJSONArray("tag_id");
                     if (!CollectionUtils.isEmpty(tagIds)) {
                         List<String> tagIdList = tagIds.toJavaList(String.class);
-                        for (String tagId : tagIdList) {
-                            TagExample example = new TagExample();
-                            example.createCriteria().andTagIdEqualTo(tagId);
-                            List<Tag> tags = tagMapper.selectByExample(example);
-                            if (!CollectionUtils.isEmpty(tags)) {
-                                Tag tag = tags.get(0);
-                                UserWithTag userWithTag = new UserWithTag();
-                                userWithTag.setUserId(userId);
-                                userWithTag.setTagId(tag.getId());
-                                addUserWithTag(userWithTag);
-                            }
-                        }
+                        weComUserService.updateUserWithTag(userId, tagIdList);
+//                        for (String tagId : tagIdList) {
+//                            TagExample example = new TagExample();
+//                            example.createCriteria().andTagIdEqualTo(tagId);
+//                            List<Tag> tags = tagMapper.selectByExample(example);
+//                            if (!CollectionUtils.isEmpty(tags)) {
+//                                Tag tag = tags.get(0);
+//                                UserWithTag userWithTag = new UserWithTag();
+//                                userWithTag.setUserId(userId);
+//                                userWithTag.setTagId(tag.getId());
+//                                weComUserService.addUserWithTag(userWithTag);
+//                            }
+//                        }
+                    } else {
+                        weComUserService.delAllUserTag(userId);
                     }
                 }
                 String nextCursor = jsonObject.getString("next_cursor");
@@ -403,7 +407,7 @@ public class WeComUserDataJob {
                                         UserWithTag userWithTag = new UserWithTag();
                                         userWithTag.setUserId(userId);
                                         userWithTag.setTagId(tag.getId());
-                                        addUserWithTag(userWithTag);
+                                        weComUserService.addUserWithTag(userWithTag);
                                     }
                                 }
                             }
@@ -465,15 +469,6 @@ public class WeComUserDataJob {
         }
     }
 
-    private void addUserWithTag(UserWithTag userWithTag) {
-        UserWithTagExample userWithTagExample = new UserWithTagExample();
-        userWithTagExample.createCriteria().andUserIdEqualTo(userWithTag.getUserId()).andTagIdEqualTo(userWithTag.getTagId());
-        long l = userWithTagMapper.countByExample(userWithTagExample);
-        if (l == 0) {
-            userWithTagMapper.insertSelective(userWithTag);
-        }
-    }
-
     private Long addAndUpdateUser(JSONObject externalContact, Long corpId, String externalUserId, Long createAt, Long staffId, Long userId) {
         String name = externalContact.getString("name");
         String unionId = externalContact.getString("unionid");