FollowBizService.java 14.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
package cn.fw.valhalla.service.bus.follow;

import cn.fw.common.web.annotation.DisLock;
import cn.fw.common.web.auth.LoginAuthBean;
import cn.fw.valhalla.common.utils.DateUtil;
import cn.fw.valhalla.domain.db.OriginalData;
import cn.fw.valhalla.domain.db.SecretReportHistory;
import cn.fw.valhalla.domain.db.customer.Customer;
import cn.fw.valhalla.domain.db.follow.ClueTask;
import cn.fw.valhalla.domain.db.follow.FollowClue;
import cn.fw.valhalla.domain.db.follow.FollowRecord;
import cn.fw.valhalla.domain.db.follow.FollowRecordLog;
import cn.fw.valhalla.domain.db.pool.PublicCluePool;
import cn.fw.valhalla.domain.dto.CallReportDTO;
import cn.fw.valhalla.domain.dto.FollowAttachmentDTO;
import cn.fw.valhalla.domain.enums.AttTypeEnum;
import cn.fw.valhalla.domain.enums.ClueStatusEnum;
import cn.fw.valhalla.domain.enums.FollowTypeEnum;
import cn.fw.valhalla.domain.enums.PublicClueStateEnum;
import cn.fw.valhalla.domain.vo.setting.SettingVO;
import cn.fw.valhalla.rpc.shirasawa.ShirasawaRpcService;
import cn.fw.valhalla.sdk.enums.DataTypeEnum;
import cn.fw.valhalla.service.bus.follow.strategy.FollowStrategy;
import cn.fw.valhalla.service.data.*;
import cn.fw.valhalla.service.event.TaskCancelEvent;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : kurisu
 * @className : FollowBizService
 * @description : 跟进业务服务
 * @date: 2020-08-14 17:27
 */
@Slf4j
@Service
public class FollowBizService {
    /**
     * 跟进处理器map
     */
    private final Map<FollowTypeEnum, FollowStrategy> followMap;
    private final PublicCluePoolService publicCluePoolService;
    private final FollowRecordService followRecordService;
    private final PCFollowBizService pcFollowBizService;
    private final SecretReportHistoryService secretReportHistoryService;
    private final FollowRecordLogService followRecordLogService;
    private final CustomerService customerService;
    private final FollowClueService followClueService;
    private final ShirasawaRpcService shirasawaRpcService;

    @Value("${follow.flowNo}")
    @Getter
    private String flowNo;

    @Value("${spring.cache.custom.global-prefix}:follow:defeat")
    @Getter
    private String keyPrefix;

    @Value("${spring.cache.custom.global-prefix}:follow:rpc:complete")
    @Getter
    private String completeKeyPrefix;

    @Autowired
    public FollowBizService(final List<FollowStrategy> followStrategyList,
                            final PublicCluePoolService publicCluePoolService,
                            final FollowRecordService followRecordService,
                            final PCFollowBizService pcFollowBizService,
                            final SecretReportHistoryService secretReportHistoryService,
                            final FollowRecordLogService followRecordLogService,
                            final CustomerService customerService,
                            final FollowClueService followClueService,
                            final ShirasawaRpcService shirasawaRpcService) {
        this.followMap = followStrategyList.stream().collect(Collectors.toMap(FollowStrategy::getFollowType, v -> v));
        this.publicCluePoolService = publicCluePoolService;
        this.followRecordService = followRecordService;
        this.pcFollowBizService = pcFollowBizService;
        this.secretReportHistoryService = secretReportHistoryService;
        this.followRecordLogService = followRecordLogService;
        this.customerService = customerService;
        this.followClueService = followClueService;
        this.shirasawaRpcService = shirasawaRpcService;
    }


    /**
     * 完成跟进
     *
     * @param recordId
     * @param userId
     */
    @DisLock(prefix = "#this.getCompleteKeyPrefix()", key = "#recordId + ':user-id:' + #userId", message = "请勿重复提交")
    public void completeRecord(final Long recordId, final Long userId) {
        shirasawaRpcService.completeRecordTodo(recordId, userId);
    }

    /**
     * 公共客户线索池上传跟进附件
     *
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    public void uploadAtt(FollowAttachmentDTO dto, LoginAuthBean currentUser) {
        pcFollowBizService.uploadAtt(dto, currentUser.getUserId());
    }

    /**
     * 更新跟进任务
     *
     * @param setting
     * @param type
     * @param groupId
     */
    public void synFollowTask(List<SettingVO> setting, FollowTypeEnum type, Long groupId) {
        FollowStrategy strategy = followMap.get(type);
        Assert.notNull(strategy, "strategy cannot be null");
        strategy.settingChanged(setting, groupId);
    }

    /**
     * 当业务数据取消的时候
     *
     * @param event
     */
    public void onDataCancel(TaskCancelEvent event) {
        FollowTypeEnum typeEnum = conv(event.getDataTypeEnum());
        if (Objects.isNull(typeEnum) || FollowTypeEnum.AC.equals(typeEnum)) {
            return;
        }
        Long customerId = event.getCustomerId();
        Long groupId = event.getGroupId();
        Customer customer = customerService.queryById(customerId);
        if (Objects.isNull(customer)) {
            return;
        }
        FollowClue followClue = followClueService.getOne(Wrappers.<FollowClue>lambdaQuery()
                        .eq(FollowClue::getVin, customer.getFrameNo())
                        .eq(FollowClue::getGroupId, groupId)
                        .eq(FollowClue::getClueType, typeEnum)
                        .eq(FollowClue::getClueState, ClueStatusEnum.WAITING)
                , Boolean.FALSE);
        if (Objects.isNull(followClue)) {
            return;
        }
        followClueService.removeById(followClue.getId());
    }

    /**
     * 元数据生成任务
     *
     * @param originalData
     * @param typeEnum
     */
    public boolean origin2task(OriginalData originalData, DataTypeEnum typeEnum) {
        if (Objects.isNull(originalData)) {
            return true;
        }
        FollowTypeEnum type = conv(typeEnum);
        FollowStrategy strategy = followMap.get(type);
        Assert.notNull(strategy, "strategy cannot be null");
        try {
            return strategy.origin2task(originalData);
        } catch (Exception exception) {
            log.error("处理元数据失败 data: [{}]", originalData, exception);
            return false;
        }
    }

    /**
     * 开始线索
     *
     * @param cluePool
     */
    public void startClue(FollowClue cluePool) {
        try {
            FollowStrategy strategy = followMap.get(cluePool.getClueType());
            Assert.notNull(strategy, "strategy cannot be null");

            strategy.startClue(cluePool);
        } catch (Exception e) {
            log.error("开始线索失败 data: [{}]", cluePool, e);
        }
    }

    /**
     * 定时任务结束任务
     *
     * @param task
     */
    public void endTask(ClueTask task) {
        FollowStrategy strategy = followMap.get(task.getType());
        Assert.notNull(strategy, "strategy cannot be null");
        try {
            strategy.closeTask(task);
        } catch (Exception ex) {
            log.error("定时任务结束任务失败 taskId: [{}]", task.getId(), ex);
        }
    }

    /**
     * 角色变动结束任务
     *
     * @param task
     */
    public void roleChangeEndTask(ClueTask task) {
        FollowStrategy strategy = followMap.get(task.getType());
        Assert.notNull(strategy, "strategy cannot be null");
        strategy.onRoleChangeCloseTask(task);
    }

    /**
     * 任务结束同步状态到跟进系统
     *
     * @param task
     */
    public void syncEndTask(ClueTask task) {
        FollowStrategy strategy = followMap.get(task.getType());
        Assert.notNull(strategy, "strategy cannot be null");
        try {
            strategy.syncEndTask(task);
        } catch (Exception ex) {
            log.error("任务结束同步状态到跟进系统失败 taskId: [{}]", task.getId(), ex);
        }
    }

    /**
     * 推送下一次跟进待办
     *
     * @param clue
     */
    public void createNextFollowTodo(FollowClue clue) {
        FollowStrategy strategy = followMap.get(clue.getClueType());
        Assert.notNull(strategy, "strategy cannot be null");
        try {
            strategy.createNextFollowTodo(clue);
        } catch (Exception ex) {
            log.error("推送下一次跟进待办失败 ckueId: [{}]", clue.getId(), ex);
        }
    }

    /**
     * 跟进完成
     *
     * @param task
     * @param preRecordId
     * @param originTime
     * @param overdue     逾期
     */
    public void afterFollowComplete(ClueTask task, Long preRecordId, Date originTime, boolean overdue) {
        FollowStrategy strategy = followMap.get(task.getType());
        Assert.notNull(strategy, "strategy cannot be null");
        strategy.onFollowComplete(task, preRecordId, DateUtil.date2LocalDate(originTime), overdue);
    }

    /**
     * 档案进入公共池任务战败
     *
     * @param vin
     * @param groupId
     */
    @Transactional(rollbackFor = Exception.class)
    public void stopTask(String vin, Long groupId) {
        List<FollowTypeEnum> typeList = Arrays.asList(FollowTypeEnum.FM, FollowTypeEnum.RM);

        List<FollowClue> cluePoolList = followClueService.list(Wrappers.<FollowClue>lambdaQuery()
                .eq(FollowClue::getClueState, ClueStatusEnum.ONGOING)
                .in(FollowClue::getClueType, typeList)
                .eq(FollowClue::getVin, vin)
                .eq(FollowClue::getGroupId, groupId)
        );
        if (!CollectionUtils.isEmpty(cluePoolList)) {
            for (FollowClue clue : cluePoolList) {
                FollowStrategy strategy = followMap.get(clue.getClueType());
                if (Objects.nonNull(strategy)) {
                    strategy.forceStopClue(clue);
                }
            }
        }
    }

    /**
     * 终止任务
     *
     * @param task
     */
    @Transactional(rollbackFor = Exception.class)
    public void stopTask(ClueTask task) {
        FollowStrategy strategy = followMap.get(task.getType());
        if (Objects.nonNull(strategy)) {
            strategy.forceStopTask(task);
        }
    }

    /**
     * 监听智能电话通话记录
     *
     * @param dto
     * @param idArr
     */
    public void readCallReport(CallReportDTO dto, Long... idArr) {
        if (Objects.isNull(dto) || idArr == null || idArr.length <= 0) {
            return;
        }
        final Long talkTime = dto.getTalkTime();
        if (Objects.isNull(talkTime) || talkTime <= 0) {
            return;
        }
        completePublicRecord(dto, idArr);
    }


    /**
     * 手动开始任务
     */
    public void manualStartClue() {
        List<FollowClue> list = followClueService.list(Wrappers.<FollowClue>lambdaQuery()
                .eq(FollowClue::getClueState, ClueStatusEnum.WAITING)
                .le(FollowClue::getStartTime, DateUtil.localDateTime2Date(LocalDateTime.now()))
                .last("limit 0, 2000")
        );
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (FollowClue cluePool : list) {
            startClue(cluePool);
        }
    }


    private FollowTypeEnum conv(DataTypeEnum type) {
        switch (type) {
            case AS:
                return FollowTypeEnum.AC;
            case OD:
            case FM:
                return FollowTypeEnum.FM;
            case BI:
                return FollowTypeEnum.IR;
            case FS:
                return FollowTypeEnum.RM;
            default:
                return null;
        }
    }

    private void completePublicRecord(CallReportDTO reportDTO, Long... custIds) {
        try {
            List<PublicCluePool> cluePools = publicCluePoolService.list(Wrappers.<PublicCluePool>lambdaQuery()
                    .in(PublicCluePool::getCustomerId, Arrays.asList(custIds))
                    .eq(PublicCluePool::getState, PublicClueStateEnum.ONGOING)
                    .eq(PublicCluePool::getAdviserId, reportDTO.getStaffId())
            );
            if (CollectionUtils.isEmpty(cluePools)) {
                return;
            }

            List<Long> clueIds = cluePools.stream().map(PublicCluePool::getId).collect(Collectors.toList());

            List<FollowRecord> list = followRecordService.list(Wrappers.<FollowRecord>lambdaQuery()
                    .in(FollowRecord::getTaskId, clueIds)
                    .eq(FollowRecord::getType, FollowTypeEnum.OT)
                    .eq(FollowRecord::getAddTodo, Boolean.TRUE)
                    .eq(FollowRecord::getOutTime, Boolean.FALSE)
            );
            if (CollectionUtils.isEmpty(list)) {
                return;
            }
            List<SecretReportHistory> reportHistoryList = new ArrayList<>();

            for (FollowRecord record : list) {
                FollowAttachmentDTO dto = new FollowAttachmentDTO();
                dto.setAttachments(reportDTO.getCallId());
                dto.setTaskId(record.getTaskId());
                dto.setFollowType(FollowTypeEnum.OT.getValue());
                dto.setRecordId(record.getId());
                dto.setAttType(AttTypeEnum.SMART_PHONE.getValue());
                reportHistoryList.add(createHistory(reportDTO, record));
                pcFollowBizService.uploadAtt(dto, reportDTO.getStaffId());
            }
            secretReportHistoryService.saveBatch(reportHistoryList);
        } catch (Exception ex) {
            log.error("通话记录同步到跟进公共线索池客户记录失败:", ex);
        }
    }


    private SecretReportHistory createHistory(CallReportDTO reportDTO, FollowRecord record) {
        SecretReportHistory history = new SecretReportHistory();
        history.setTaskId(record.getTaskId());
        history.setTaskType(FollowTypeEnum.OT);
        history.setFollowRecordId(record.getId());
        history.setCallId(reportDTO.getCallId());
        history.setStaffId(reportDTO.getStaffId());
        history.setStaffName(reportDTO.getStaffName());
        history.setCustomerId(record.getCustomerId());
        history.setCallType(reportDTO.getDialType());
        history.setCallTime(reportDTO.getCallTime());
        history.setCallDuration(reportDTO.getTalkTime());
        history.setShopId(record.getShopId());
        history.setGroupId(record.getGroupId());
        int count = followRecordLogService.count(Wrappers.<FollowRecordLog>lambdaQuery()
                .eq(FollowRecordLog::getTaskId, record.getTaskId())
                .eq(FollowRecordLog::getAttType, AttTypeEnum.SMART_PHONE)
        );
        history.setFirstCall(count <= 0);
        return history;
    }
}