WePresTagGroupTaskServiceImpl.java 16.5 KB
Newer Older
1 2 3
package com.linkwechat.wecom.service.impl;

import cn.hutool.core.collection.CollectionUtil;
孙喜旺 已提交
4
import com.alibaba.fastjson.JSONObject;
5
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
Y
YaoYuHang 已提交
6
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
7
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
8
import com.linkwechat.common.core.domain.entity.WeCorpAccount;
Y
YaoYuHang 已提交
9 10 11 12 13
import com.linkwechat.common.enums.ChatType;
import com.linkwechat.common.enums.MediaType;
import com.linkwechat.common.enums.TaskSendType;
import com.linkwechat.common.enums.CommunityTaskType;
import com.linkwechat.common.exception.wecom.WeComException;
14
import com.linkwechat.common.utils.SecurityUtils;
Y
YaoYuHang 已提交
15
import com.linkwechat.common.utils.StringUtils;
16
import com.linkwechat.common.utils.bean.BeanUtils;
Y
YaoYuHang 已提交
17 18
import com.linkwechat.wecom.client.WeCustomerMessagePushClient;
import com.linkwechat.wecom.client.WeMessagePushClient;
19
import com.linkwechat.wecom.domain.*;
Y
YaoYuHang 已提交
20 21
import com.linkwechat.wecom.domain.dto.WeMediaDto;
import com.linkwechat.wecom.domain.dto.WeMessagePushDto;
22
import com.linkwechat.wecom.domain.dto.WePresTagGroupTaskDto;
Y
YaoYuHang 已提交
23 24
import com.linkwechat.wecom.domain.dto.message.*;
import com.linkwechat.wecom.domain.vo.WeCommunityTaskEmplVo;
25 26
import com.linkwechat.wecom.domain.vo.WePresTagGroupTaskStatVo;
import com.linkwechat.wecom.domain.vo.WePresTagGroupTaskVo;
Y
YaoYuHang 已提交
27 28
import com.linkwechat.wecom.mapper.*;
import com.linkwechat.wecom.service.*;
29 30
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
Y
YaoYuHang 已提交
31
import org.springframework.beans.factory.annotation.Value;
32
import org.springframework.scheduling.annotation.Async;
33 34 35
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

Y
YaoYuHang 已提交
36 37
import java.net.URLEncoder;
import java.util.ArrayList;
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WePresTagGroupTaskServiceImpl extends ServiceImpl<WePresTagGroupTaskMapper, WePresTagGroupTask> implements IWePresTagGroupTaskService {

    @Autowired
    private WePresTagGroupTaskMapper taskMapper;

    @Autowired
    private WePresTagGroupTaskStatMapper taskStatMapper;

    @Autowired
    private WePresTagGroupTaskScopeMapper taskScopeMapper;

    @Autowired
    private WePresTagGroupTaskTagMapper taskTagMapper;

Y
YaoYuHang 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
    @Autowired
    private WeCustomerMessagePushClient customerMessagePushClient;

    @Autowired
    private WeMessagePushClient messagePushClient;

    @Autowired
    private IWeMaterialService materialService;

    @Autowired
    private WeGroupCodeMapper groupCodeMapper;

    @Autowired
    private IWeCorpAccountService corpAccountService;

    @Autowired
    private WeCustomerMapper customerMapper;

    @Value("${wecome.authorizeUrl}")
    private String authorizeUrl;

    @Value("${wecome.authorizeRedirectUrl}")
    private String authorizeRedirectUrl;

82
    /**
83 84 85 86 87
     * 添加新标签建群任务
     * @param task 建群任务本体信息
     * @param tagIdList 标签列表
     * @param emplIdList 员工列表
     * @return 结果
88 89
     */
    @Override
90
    @Transactional
91
    public int add(WePresTagGroupTask task, List<String> tagIdList, List<String> emplIdList) {
92
        if (taskMapper.insertTask(task) > 0) {
93 94
            // 保存标签对象
            if (CollectionUtil.isNotEmpty(tagIdList)) {
Y
YaoYuHang 已提交
95 96 97 98
                List<WePresTagGroupTaskTag> taskTagList = tagIdList
                        .stream()
                        .map(id -> new WePresTagGroupTaskTag(task.getTaskId(), id))
                        .collect(Collectors.toList());
99 100 101 102 103
                taskTagMapper.batchBindsTaskTags(taskTagList);
            }

            // 保存员工信息
            if (CollectionUtil.isNotEmpty(emplIdList)) {
Y
YaoYuHang 已提交
104 105 106 107
                List<WePresTagGroupTaskScope> wePresTagGroupTaskScopeList = emplIdList
                        .stream()
                        .map(id -> new WePresTagGroupTaskScope(task.getTaskId(), id, false))
                        .collect(Collectors.toList());
108 109
                taskScopeMapper.batchBindsTaskScopes(wePresTagGroupTaskScopeList);
            }
110
            return 1;
111
        }
112
        return 0;
113 114 115
    }

    /**
Y
YaoYuHang 已提交
116 117 118 119 120
     * 根据条件查询任务列表
     *
     * @param taskName  任务名称
     * @param sendType  发送方式
     * @param createBy  创建人
121
     * @param beginTime 起始时间
Y
YaoYuHang 已提交
122
     * @param endTime   结束时间
123 124 125
     * @return 结果
     */
    @Override
Y
YaoYuHang 已提交
126
    public List<WePresTagGroupTaskVo> selectTaskList(String taskName, Integer sendType, String createBy, String beginTime, String endTime) {
127 128
        // 查询任务列表
        List<WePresTagGroupTaskVo> taskVoList = taskMapper.selectTaskList(taskName, sendType, createBy, beginTime, endTime);
Y
YaoYuHang 已提交
129 130
        if (CollectionUtil.isNotEmpty(taskVoList)) {
            taskVoList.forEach(this::setGroupCodeAndScopeAndTag);
131 132 133 134 135 136 137 138 139 140 141 142
        }
        return taskVoList;
    }

    /**
     * 通过id获取老客标签建群任务
     *
     * @param taskId 任务id
     * @return 结果
     */
    @Override
    public WePresTagGroupTaskVo getTaskById(Long taskId) {
Y
YaoYuHang 已提交
143
        WePresTagGroupTaskVo taskVo = taskMapper.selectTaskById(taskId);
144 145 146
        if (StringUtils.isNotNull(taskVo)) {
            setGroupCodeAndScopeAndTag(taskVo);
        }
Y
YaoYuHang 已提交
147
        return taskVo;
148 149 150 151 152 153 154 155 156
    }

    /**
     * 批量删除老客标签建群任务
     *
     * @param idList 任务id列表
     * @return 删除的行数
     */
    @Override
Y
YaoYuHang 已提交
157
    @Transactional(rollbackFor = RuntimeException.class)
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    public int batchRemoveTaskByIds(Long[] idList) {
        List<Long> ids = Arrays.asList(idList);

        // 解除关联的标签
        QueryWrapper<WePresTagGroupTaskTag> taskTagQueryWrapper = new QueryWrapper<>();
        taskTagQueryWrapper.in("task_id", ids);
        taskTagMapper.delete(taskTagQueryWrapper);
        // 解除关联的员工
        QueryWrapper<WePresTagGroupTaskScope> taskScopeQueryWrapper = new QueryWrapper<>();
        taskScopeQueryWrapper.in("task_id", ids);
        taskScopeMapper.delete(taskScopeQueryWrapper);
        // 删除其用户统计
        QueryWrapper<WePresTagGroupTaskStat> statQueryWrapper = new QueryWrapper<>();
        statQueryWrapper.in("task_id", ids);
        taskStatMapper.delete(statQueryWrapper);

        // 删除task
        QueryWrapper<WePresTagGroupTask> taskQueryWrapper = new QueryWrapper<>();
        taskQueryWrapper.in("task_id", ids);
        return taskMapper.delete(taskQueryWrapper);
    }

    /**
     * 更新老客户标签建群任务
     *
     * @param wePresTagGroupTaskDto 更新数据
     * @return 结果
Y
YaoYuHang 已提交
185
     * @taskId 待更新任务id
186 187 188 189 190 191 192 193
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public int updateTask(Long taskId, WePresTagGroupTaskDto wePresTagGroupTaskDto) {
        WePresTagGroupTask wePresTagGroupTask = new WePresTagGroupTask();
        BeanUtils.copyProperties(wePresTagGroupTaskDto, wePresTagGroupTask);
        wePresTagGroupTask.setTaskId(taskId);
        wePresTagGroupTask.setUpdateBy(SecurityUtils.getUsername());
194
        if (taskMapper.updateTask(wePresTagGroupTask) > 0) {
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
            // 更新标签
            // 先删除旧标签
            QueryWrapper<WePresTagGroupTaskTag> taskTagQueryWrapper = new QueryWrapper<>();
            taskTagQueryWrapper.eq("task_id", taskId);
            taskTagMapper.delete(taskTagQueryWrapper);
            // 再添加新标签
            List<String> tagIdList = wePresTagGroupTaskDto.getTagList();
            if (CollectionUtil.isNotEmpty(tagIdList)) {
                List<WePresTagGroupTaskTag> wePresTagGroupTaskTagList = tagIdList.stream().map(id -> new WePresTagGroupTaskTag(taskId, id)).collect(Collectors.toList());
                taskTagMapper.batchBindsTaskTags(wePresTagGroupTaskTagList);
            }

            // 先解除旧的员工绑定信息
            QueryWrapper<WePresTagGroupTaskScope> taskScopeQueryWrapper = new QueryWrapper<>();
            taskScopeQueryWrapper.eq("task_id", taskId);
            taskScopeMapper.delete(taskScopeQueryWrapper);

            // 再重新绑定员工信息
            List<String> userIdList = wePresTagGroupTaskDto.getScopeList();
            if (CollectionUtil.isNotEmpty(userIdList)) {
Y
YaoYuHang 已提交
215
                List<WePresTagGroupTaskScope> wePresTagGroupTaskScopeList = userIdList.stream().map(id -> new WePresTagGroupTaskScope(taskId, id, false)).collect(Collectors.toList());
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
                taskScopeMapper.batchBindsTaskScopes(wePresTagGroupTaskScopeList);
            }
            return 1;
        }
        return 0;
    }

    /**
     * 检测任务名是否已存在
     *
     * @param taskName 任务名
     * @return 结果
     */
    @Override
    public boolean checkTaskNameUnique(String taskName) {
        int count = taskMapper.checkTaskNameUnique(taskName);
        return count <= 0;
    }

    /**
     * 通过老客标签建群id获取其统计信息
     *
Y
YaoYuHang 已提交
238
     * @param taskId 任务id
239 240 241
     * @return 统计信息
     */
    @Override
Y
YaoYuHang 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
    public List<WePresTagGroupTaskStatVo> getStatByTaskId(Long taskId) {
        WePresTagGroupTask task = taskMapper.selectById(taskId);
        // 该任务对应的所有外部联系人id
        List<String> externalIdList = taskStatMapper.getAllExternalIdByTaskId(taskId);
        List<WePresTagGroupTaskStatVo> statVoList = new ArrayList<>();
        if (task.getSendType().equals(TaskSendType.CROP.getType())) {
            // 企业群发。通过企微接口统计
            QueryCustomerMessageStatusResultDataObjectDto requestData = new QueryCustomerMessageStatusResultDataObjectDto();
            requestData.setMsgid(task.getMsgid());
            QueryCustomerMessageStatusResultDto resultDto = customerMessagePushClient.queryCustomerMessageStatus(requestData);

            if (StringUtils.isNotEmpty(resultDto.getDetail_list())) {
                for (DetailMessageStatusResultDto detail : resultDto.getDetail_list()) {
                    WePresTagGroupTaskStatVo statVo = new WePresTagGroupTaskStatVo();
                    WeCustomer customer = customerMapper.selectWeCustomerById(detail.getExternal_userid());
                    statVo.setCustomerName(customer.getName());
                    statVo.setStatus(detail.getStatus());
                    statVo.setInGroup(externalIdList.contains(detail.getExternal_userid()));
                    statVoList.add(statVo);
                }
            }

        } else {
            // 个人群发。通过数据库进行统计
            statVoList = taskStatMapper.selectStatInfoByTaskId(taskId);
        }
        return statVoList;

270 271 272
    }

    /**
Y
YaoYuHang 已提交
273
     * 根据任务id获取对应员工信息列表
274 275 276 277 278
     *
     * @param taskId 任务id
     * @return 结果
     */
    @Override
Y
YaoYuHang 已提交
279
    public List<WeCommunityTaskEmplVo> getScopeListByTaskId(Long taskId) {
280 281 282 283
        return taskScopeMapper.getScopeListByTaskId(taskId);
    }

    /**
Y
YaoYuHang 已提交
284
     * 根据任务id获取对应标签信息列表
285 286 287 288 289 290 291 292
     *
     * @param taskId 任务id
     * @return 结果
     */
    @Override
    public List<WeTag> getTagListByTaskId(Long taskId) {
        return taskTagMapper.getTagListByTaskId(taskId);
    }
Y
YaoYuHang 已提交
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340

    /**
     * 获取员工建群任务信息
     *
     * @param emplId 员工id
     * @param isDone 是否已处理
     * @return 结果
     */
    @Override
    public List<WePresTagGroupTaskVo> getEmplTaskList(String emplId, boolean isDone) {
        List<WePresTagGroupTaskVo> taskVoList = taskMapper.getTaskListByEmplId(emplId, isDone);
        if (StringUtils.isNotEmpty(taskVoList)) {
            taskVoList.forEach(this::setGroupCodeAndScopeAndTag);
        }
        return taskVoList;
    }

    /**
     * 员工发送信息后,变更其任务状态为 "完成"
     *
     * @param taskId 任务id
     * @param emplId 员工id
     * @return 结果
     */
    @Override
    public int updateEmplTaskStatus(Long taskId, String emplId) {
        return taskScopeMapper.updateEmplTaskStatus(taskId, emplId);
    }

    /**
     * 任务群活码、员工和标签
     *
     * @param taskVo 任务vo
     */
    private void setGroupCodeAndScopeAndTag(WePresTagGroupTaskVo taskVo) {
        // 任务群活码信息
        taskVo.fillGroupCodeVo();
        // 员工信息
        taskVo.setScopeList(this.getScopeListByTaskId(taskVo.getTaskId()));
        // 客户标签
        taskVo.setTagList(this.getTagListByTaskId(taskVo.getTaskId()));
    }

    /**
     * 任务派发
     *
     * @param task 建群任务
     */
341 342 343
    @Override
    @Async
    public void sendMessage(WePresTagGroupTask task) {
Y
YaoYuHang 已提交
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
        try {

            Integer sendType = task.getSendType();

            if (sendType.equals(TaskSendType.CROP.getType())) {
                // 企业群发
                this.sendCorpMessage(task);

            } else {
                // 个人群发
                this.sendEmployeeMessage(task);
            }

        } catch (Exception e) {
            throw new WeComException(e.getMessage());
        }
    }

    /**
     * 企业群发
     *
     * @param task 建群任务信息
     */
    private void sendCorpMessage(WePresTagGroupTask task) {
        try {

            // 构建企微api参数 [客户联系 - 消息推送 - 创建企业群发]

            // 群发任务的类型、外部联系人id列表
            List<String> externalIdList = taskTagMapper.getExternalUserIdListByTaskId(task.getTaskId());
            WeCustomerMessagePushDto queryData = new WeCustomerMessagePushDto();
            queryData.setChat_type(ChatType.SINGLE.getName());
            queryData.setExternal_userid(externalIdList);

            // 引导语
            TextMessageDto text = new TextMessageDto();
            text.setContent(task.getWelcomeMsg());
            queryData.setText(text);

            // 群活码图片(上传临时文件获取media_id) TODO 过期问题?
            ImageMessageDto image = new ImageMessageDto();
            WeGroupCode groupCode = groupCodeMapper.selectWeGroupCodeById(task.getGroupCodeId());
            WeMediaDto mediaDto = materialService.uploadTemporaryMaterial(groupCode.getCodeUrl(), MediaType.IMAGE.getMediaType(), "临时文件");
            image.setMedia_id(mediaDto.getMedia_id());
孙喜旺 已提交
388 389 390 391 392 393 394
            //queryData.setImage(image);
            List list = new ArrayList();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msgtype","image");
            jsonObject.put("image",image);
            list.add(jsonObject);
            queryData.setAttachments(list);
Y
YaoYuHang 已提交
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423

            // 调用企业群发接口
            SendMessageResultDto resultDto = customerMessagePushClient.sendCustomerMessageToUser(queryData);

            // 设定该任务的msgid
            UpdateWrapper<WePresTagGroupTask> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("task_id", task.getTaskId());
            updateWrapper.set("msgid", resultDto.getMsgid());
            this.update(updateWrapper);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 个人群发
     *
     * @param task 建群任务信息
     */
    private void sendEmployeeMessage(WePresTagGroupTask task) {
        WeMessagePushDto pushDto = new WeMessagePushDto();
        // 设置toUser参数
        List<WeCommunityTaskEmplVo> employeeList = taskScopeMapper.getScopeListByTaskId(task.getTaskId());
        String toUser = employeeList.stream().map(WeCommunityTaskEmplVo::getUserId).collect(Collectors.joining("|"));
        pushDto.setTouser(toUser);

        // 获取agentId
        WeCorpAccount validWeCorpAccount = corpAccountService.findValidWeCorpAccount();
        String agentId = validWeCorpAccount.getAgentId();
424
        String corpId = validWeCorpAccount.getCorpId();
425 426 427
        if (StringUtils.isEmpty(agentId)) {
            throw new WeComException("当前agentId不可用或不存在");
        }
Y
YaoYuHang 已提交
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
        pushDto.setAgentid(Integer.valueOf(agentId));

        // 设置文本消息
        TextMessageDto text = new TextMessageDto();
        String REDIRECT_URI = URLEncoder.encode(String.format("%s?corpId=%s&agentId=%s&type=%s", authorizeRedirectUrl, corpId, agentId, CommunityTaskType.TAG.getType()));
        String context = String.format(
                "你有一个新任务,<a href='%s?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect'>请点击此链接查看</a>",
                authorizeUrl, corpId, REDIRECT_URI);
        text.setContent(context);
        pushDto.setText(text);

        pushDto.setMsgtype("text");

        // 请求消息推送接口,获取结果 [消息推送 - 发送应用消息]
        messagePushClient.sendMessageToUser(pushDto, agentId);
    }
444
}