WeUserServiceImpl.java 15.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 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 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 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 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 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 341 342 343 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 388 389 390 391 392 393 394 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 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
package com.linkwechat.wecom.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.google.common.collect.Lists;
import com.linkwechat.common.config.RuoYiConfig;
import com.linkwechat.common.constant.WeConstans;
import com.linkwechat.common.core.redis.RedisCache;
import com.linkwechat.common.exception.wecom.WeComException;
import com.linkwechat.common.utils.SecurityUtils;
import com.linkwechat.common.utils.StringUtils;
import com.linkwechat.common.utils.Threads;
import com.linkwechat.common.utils.spring.SpringUtils;
import com.linkwechat.wecom.annotation.SynchRecord;
import com.linkwechat.wecom.client.WeCustomerClient;
import com.linkwechat.wecom.client.WeCustomerGroupClient;
import com.linkwechat.wecom.client.WeUserClient;
import com.linkwechat.wecom.constants.SynchRecordConstants;
import com.linkwechat.wecom.domain.WeAllocateCustomer;
import com.linkwechat.wecom.domain.WeAllocateGroup;
import com.linkwechat.wecom.domain.WeCustomerAddUser;
import com.linkwechat.wecom.domain.WeUser;
import com.linkwechat.wecom.domain.dto.AllocateWeCustomerDto;
import com.linkwechat.wecom.domain.dto.WeUserInfoDto;
import com.linkwechat.wecom.domain.dto.customer.CustomerGroupDetail;
import com.linkwechat.wecom.domain.dto.customer.CustomerGroupList;
import com.linkwechat.wecom.domain.dto.customer.ExternalUserDetail;
import com.linkwechat.wecom.domain.dto.customer.FollowUserList;
import com.linkwechat.wecom.domain.dto.msgaudit.WeMsgAuditDto;
import com.linkwechat.wecom.domain.vo.*;
import com.linkwechat.wecom.mapper.WeUserMapper;
import com.linkwechat.wecom.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 通讯录相关客户Service业务层处理
 *
 * @author ruoyi
 * @date 2020-08-31
 */
@Service
public class WeUserServiceImpl extends ServiceImpl<WeUserMapper, WeUser> implements IWeUserService {
    @Autowired
    private WeUserMapper weUserMapper;

    @Autowired
    private WeUserClient weUserClient;




    @Autowired
    private RuoYiConfig  ruoYiConfig;


    @Autowired
    private WeCustomerClient weCustomerClient;

    @Autowired
    private IWeAllocateCustomerService iWeAllocateCustomerService;

    @Autowired
    private WeCustomerGroupClient weCustomerGroupClient;

    @Autowired
    private IWeAllocateGroupService iWeAllocateGroupService;

    @Autowired
    private IWeGroupService iWeGroupService;

    @Override
    public WeUser getById(Long id) {
        return super.getById(id);
    }



    /**
     * 查询通讯录相关客户列表
     *
     * @param weUser 通讯录相关客户
     * @return 通讯录相关客户
     */
    @Override
    public List<WeUser> getList(WeUser weUser) {


       return this.list(new LambdaQueryWrapper<WeUser>()
                .like(StringUtils.isNotEmpty(weUser.getName()),WeUser::getName,weUser.getName())
                .eq(weUser.getIsActivate() !=null,WeUser::getIsActivate,weUser.getIsActivate())
                .eq(weUser.getIsConfigCustomerContact() != null,WeUser::getIsConfigCustomerContact,weUser.getIsConfigCustomerContact())
                .apply(StringUtils.isNotEmpty(weUser.getDepartment()),"FIND_IN_SET('"+weUser.getDepartment()+"',department)")
                .apply(StringUtils.isNotBlank( weUser.getBeginTime()),
                        "date_format (create_time,'%Y-%m-%d') >= date_format('" + weUser.getBeginTime() + "','%Y-%m-%d')")
                .apply(StringUtils.isNotBlank(weUser.getEndTime()),
                        "date_format (create_time,'%Y-%m-%d') <= date_format('" + weUser.getEndTime() + "','%Y-%m-%d')")
               .orderByDesc(WeUser::getCreateTime)
        );
    }

    /**
     * 新增通讯录相关客户
     *
     * @param weUser 通讯录相关客户
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(WeUser weUser) {
        weUser.setIsActivate(4);
        if (insert2Data(weUser)) {
            weUserClient.createUser(
                    weUser.transformWeUserDto()
            );
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insert2Data(WeUser weUser) {
        List<WeUser> list = new ArrayList<>(16);
        list.add(weUser);
        this.weUserMapper.insertBatch(list);
        return true;
    }

    /**
     * 修改通讯录相关客户
     *
     * @param weUser 通讯录相关客户
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(WeUser weUser) {
        if (update2Data(weUser)) {
            weUserClient.updateUser(weUser.transformWeUserDto());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update2Data(WeUser weUser) {
        return this.updateById(weUser);
    }


    /**
     * 启用或禁用用户
     *
     * @param weUser
     * @return
     */
    @Override
    public void startOrStop(WeUser weUser) {
        this.update(weUser);
    }


    /**
     * 离职未分配员工
     *
     * @param weLeaveUserVo
     * @return
     */
    @Override
    public List<WeLeaveUserVo> leaveNoAllocateUserList(WeLeaveUserVo weLeaveUserVo) {
        return this.weUserMapper.leaveNoAllocateUserList(weLeaveUserVo);
    }


    /**
     * 离职已分配员工
     *
     * @param weLeaveUserVo
     * @return
     */
    @Override
    public List<WeLeaveUserVo> leaveAllocateUserList(WeLeaveUserVo weLeaveUserVo) {
        return this.baseMapper.leaveAllocateUserList(weLeaveUserVo);
    }


    /**
     * 分配离职员工相关数据
     *
     * @param weLeaveUserInfoAllocateVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void allocateLeaveUserAboutData(WeLeaveUserInfoAllocateVo weLeaveUserInfoAllocateVo) {
        try {
            //分配客户
//            SpringUtils.getBean(IWeCustomerService.class).allocateWeCustomer(weLeaveUserInfoAllocateVo);
            //分配群组
            SpringUtils.getBean(IWeGroupService.class).allocateWeGroup(weLeaveUserInfoAllocateVo);
            //更新员工状态为已分配
            this.update2Data(WeUser.builder()
                    .userId(weLeaveUserInfoAllocateVo.getHandoverUserid())
                    .isAllocate(WeConstans.LEAVE_ALLOCATE_STATE)
                    .build());
        } catch (Exception e) {
            throw new WeComException(e.getMessage());
        }

    }


    /**
     * 同步成员
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SynchRecord(synchType = SynchRecordConstants.SYNCH_MAIL_LIST)
    public void synchWeUser() {
        SecurityContext securityContext = SecurityContextHolder.getContext();

        //异步同步一下标签库,解决标签不同步问题
        Threads.SINGLE_THREAD_POOL.execute(new Runnable() {
            @Override
            public void run() {
                SecurityContextHolder.setContext(securityContext);


                //同步部门
                SpringUtils.getBean(IWeDepartmentService.class).synchWeDepartment();
                //获取通讯录成员列表
                List<WeUser> weUsers = weUserClient.list(WeConstans.WE_ROOT_DEPARMENT_ID,
                        WeConstans.DEPARTMENT_SUB_WEUSER).getWeUsers();
                if (CollectionUtil.isNotEmpty(weUsers)) {
                    //不存在的客户设置为离职未分配状态
                   update(WeUser.builder()
                            .isActivate(WeConstans.WE_USER_IS_LEAVE)
                            .isAllocate(WeConstans.LEAVE_NO_ALLOCATE_STATE)
                            .dimissionTime(new Date())
                            .build(),new LambdaQueryWrapper<WeUser>()
                            .notIn(WeUser::getUserId,weUsers.stream().map(WeUser::getUserId).collect(Collectors.toList())));


                    List<List<WeUser>> lists = Lists.partition(weUsers, 500);
                    for(List<WeUser> list : lists){
                        weUserMapper.insertBatch(list);
                    }


                    //获取外部联系人列表
                    FollowUserList followUserList = weCustomerClient.getFollowUserList();
                    if (WeConstans.WE_SUCCESS_CODE.equals(followUserList.getErrcode())
                            && ArrayUtil.isNotEmpty(followUserList.getFollow_user())) {

                        //设置员工是否开启外部联系人功能
                        update(WeUser.builder()
                                .isConfigCustomerContact(new Integer(1))
                                .build(),new LambdaQueryWrapper<WeUser>()
                                .eq(WeUser::getUserId,ListUtil.toList(followUserList.getFollow_user())));


                    }



                }

            }
        });




    }


    /**
     * 删除用户
     *
     * @param userIds
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @Async
    public void deleteUser(String[] userIds) {
        List<WeUser> weUsers=new ArrayList<>();
        CollectionUtil.newArrayList(userIds).forEach(userId-> {

            String[] noSyncWeUser = ruoYiConfig.getNoSyncWeUser();

            if(ArrayUtil.isNotEmpty(noSyncWeUser)){
                if(CollectionUtil.toList(noSyncWeUser).contains(userId)){
                    throw new WeComException("当前员工不可删除");
                }
            }

            weUsers.add(
                    WeUser.builder()
                            .userId(userId)
                            .isActivate(WeConstans.corpUserEnum.ACTIVE_STATE_FIVE.getKey())
                            .dimissionTime(new Date())
                            .build()
            );


        }
       );
        if(this.updateBatchById(weUsers)){
            weUsers.forEach(k-> weUserClient.deleteUserByUserId(k.getUserId()));
            //同步离职成员相关信息分配
            this.synchLeaveUserData();
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUserNoToWeCom(String userId) {
        WeUser weUser = WeUser.builder()
                .userId(userId)
                .isActivate(WeConstans.WE_USER_IS_LEAVE)
                .dimissionTime(new Date())
                .build();
        return this.updateById(weUser);
    }


    /**
     * 获取历史分配记录的成员
     *
     * @param weAllocateCustomersVo
     * @return
     */
    @Override
    public List<WeAllocateCustomersVo> getAllocateCustomers(WeAllocateCustomersVo weAllocateCustomersVo) {
        return this.baseMapper.getAllocateCustomers(weAllocateCustomersVo);
    }


    /**
     * 获取历史分配群
     *
     * @param weAllocateGroupsVo
     * @return
     */
    @Override
    public List<WeAllocateGroupsVo> getAllocateGroups(WeAllocateGroupsVo weAllocateGroupsVo) {
        return this.baseMapper.getAllocateGroups(weAllocateGroupsVo);
    }


    @Override
    public WeUserInfoVo getUserInfo(String code, String agentId) {
        WeUserInfoDto userInfo = weUserClient.getUserInfo(code, agentId);
        return WeUserInfoVo.builder()
                .userId(userInfo.getUserId())
                .deviceId(userInfo.getDeviceId())
                .externalUserId(userInfo.getExternal_userid())
                .openId(userInfo.getOpenId())
                .build();

    }

    @Override
    public List<WeCustomerAddUser> findWeUserByCustomerId(String externalUserid) {
        return this.baseMapper.findWeUserByCutomerId(externalUserid);
    }


    /**
     * 同步离职成员的相关数据(待分配客户,待分配群)。
     */
    @Override
    @Async
    public void synchLeaveUserData() {

        //同步所需要分配的客户
        List<AllocateWeCustomerDto.Info> infos=new ArrayList<>();
        getLeaveUserCustomer(null,infos);
        if(CollectionUtil.isNotEmpty(infos)){
            //过滤掉不存在的外部联系人
            List<WeAllocateCustomer> allocateCustomers=new ArrayList<>();
            infos.stream().forEach(kk->{
                allocateCustomers.add(
                        WeAllocateCustomer.builder()
                                .allocateTime(new Date())
                                .extentType(new Integer(1))
                                .externalUserid(kk.getExternal_userid())
                                .handoverUserid(kk.getHandover_userid())
                                .status(new Integer(2))
                                .failReason("离职继承")
                                .build()
                );

            });
            iWeAllocateCustomerService.batchAddOrUpdate(allocateCustomers);
        }



        //同步所需分配的客户群
        List<CustomerGroupList.GroupChat> groupChats=new ArrayList<>();
        getLeaveUserGroup(null,groupChats);
        if(CollectionUtil.isNotEmpty(groupChats)){
            List<WeAllocateGroup> weAllocateGroups=new ArrayList<>();
            groupChats.stream().forEach(k->{
                CustomerGroupDetail customerGroupDetail = weCustomerGroupClient.groupChatDetail(CustomerGroupDetail.Params.builder()
                        .chat_id(k.getChatId())
                        .need_name(new Integer(0))
                        .build());

                if(WeConstans.WE_SUCCESS_CODE.equals(customerGroupDetail.getErrcode())
                &&ArrayUtil.isNotEmpty(customerGroupDetail.getGroupChat())){
                    weAllocateGroups.add(WeAllocateGroup.builder()
                            .chatId(k.getChatId())
                            .oldOwner(customerGroupDetail.getGroupChat().stream().findFirst().get().getOwner())
                            .status(new Integer(3))
                            .build());
                }


            });
            iWeAllocateGroupService.batchAddOrUpdate(weAllocateGroups);
        }






    }

    private void getLeaveUserCustomer(String nextCursor, List<AllocateWeCustomerDto.Info> list){
        AllocateWeCustomerDto unassignedList = weUserClient.getUnassignedList(AllocateWeCustomerDto.CheckParm.builder()
                        .cursor(nextCursor)
                .build());

        if (WeConstans.WE_SUCCESS_CODE.equals(unassignedList.getErrcode())
                && ArrayUtil.isNotEmpty(unassignedList.getInfo())) {
            list.addAll(unassignedList.getInfo());
            if (StringUtils.isNotEmpty(unassignedList.getNext_cursor())) {
                getLeaveUserCustomer(unassignedList.getNext_cursor(),list);
            }

        }

    }


    private void getLeaveUserGroup(String nextCursor,List<CustomerGroupList.GroupChat> groupChats){
        CustomerGroupList customerGroupList =
                weCustomerGroupClient.groupChatLists(CustomerGroupList.Params.builder()
                        .status_filter(new Integer(1))
                        .cursor(nextCursor)
                                .limit(new Integer(1000))
                        .build());
        if (WeConstans.WE_SUCCESS_CODE.equals(customerGroupList.getErrcode())
                && ArrayUtil.isNotEmpty(customerGroupList.getGroupChatList())) {
            groupChats.addAll(customerGroupList.getGroupChatList());
            if (StringUtils.isNotEmpty(customerGroupList.getNext_cursor())) {
                getLeaveUserGroup(customerGroupList.getNext_cursor(),groupChats);
            }
        }

    }




}