package cn.fw.valhalla.service.bus.follow; import cn.fw.common.cache.locker.DistributedLocker; import cn.fw.common.page.AppPage; import cn.fw.common.web.auth.LoginAuthBean; import cn.fw.valhalla.common.utils.DateUtil; import cn.fw.valhalla.domain.db.ApproveRecord; import cn.fw.valhalla.domain.db.OriginalData; import cn.fw.valhalla.domain.db.SecretReportHistory; import cn.fw.valhalla.domain.db.follow.FollowRecord; import cn.fw.valhalla.domain.db.follow.FollowRecordLog; import cn.fw.valhalla.domain.db.follow.FollowTask; import cn.fw.valhalla.domain.db.pool.CustomerCluePool; import cn.fw.valhalla.domain.dto.CallReportDTO; import cn.fw.valhalla.domain.dto.FollowAttachmentDTO; import cn.fw.valhalla.domain.enums.*; import cn.fw.valhalla.domain.query.FollowQueryVO; import cn.fw.valhalla.domain.vo.follow.FollowDetailVO; import cn.fw.valhalla.domain.vo.follow.FollowRecordVO; import cn.fw.valhalla.domain.vo.follow.FollowTodoListVO; import cn.fw.valhalla.domain.vo.setting.SettingVO; import cn.fw.valhalla.rpc.erp.UserService; import cn.fw.valhalla.rpc.erp.dto.UserInfoDTO; import cn.fw.valhalla.rpc.flow.FlowApproveRpc; import cn.fw.valhalla.rpc.flow.dto.FlowDto; 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.apache.commons.lang3.tuple.Pair; import org.redisson.api.RLock; 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.concurrent.TimeUnit; import java.util.stream.Collectors; import static cn.fw.common.businessvalidator.Validator.BV; /** * @author : kurisu * @className : FollowBizService * @description : 跟进业务服务 * @date: 2020-08-14 17:27 */ @Slf4j @Service public class FollowBizService { /** * 跟进处理器map */ private final Map followMap; private final FlowApproveRpc flowApproveRpc; private final ApproveRecordService approveRecordService; private final FollowTaskService followTaskService; private final FollowRecordService followRecordService; private final UserService userService; private final DistributedLocker distributedLocker; private final CustomerCluePoolService customerCluePoolService; private final SecretReportHistoryService secretReportHistoryService; private final FollowRecordLogService followRecordLogService; @Value("${follow.flowNo}") @Getter private String flowNo; @Value("${spring.cache.custom.global-prefix}:defeat") @Getter private String keyPrefix; @Autowired public FollowBizService(final List followStrategyList, final FlowApproveRpc flowApproveRpc, final ApproveRecordService approveRecordService, final FollowTaskService followTaskService, final FollowRecordService followRecordService, final UserService userService, final DistributedLocker distributedLocker, final CustomerCluePoolService customerCluePoolService, final SecretReportHistoryService secretReportHistoryService, final FollowRecordLogService followRecordLogService) { this.followMap = followStrategyList.stream().collect(Collectors.toMap(FollowStrategy::getFollowType, v -> v)); this.flowApproveRpc = flowApproveRpc; this.approveRecordService = approveRecordService; this.followTaskService = followTaskService; this.followRecordService = followRecordService; this.userService = userService; this.distributedLocker = distributedLocker; this.customerCluePoolService = customerCluePoolService; this.secretReportHistoryService = secretReportHistoryService; this.followRecordLogService = followRecordLogService; } /** * 查询待办列表 * * @param queryVO * @param currentUser * @return */ public AppPage todoList(FollowQueryVO queryVO, LoginAuthBean currentUser) { Integer pageSize = queryVO.getPageSize(); Integer current = queryVO.getCurrent(); Integer startIndex = (current - 1) * pageSize; FollowStrategy strategy = followMap.get(queryVO.getType()); Assert.notNull(strategy, "strategy cannot be null"); List list = strategy.getList(startIndex, pageSize, currentUser.getUserId()); AppPage appPage = AppPage.empty(queryVO); appPage.setData(list); return appPage; } /** * 查询待办详情 * * @param id * @param type * @return */ public FollowDetailVO todoDetail(Long id, FollowTypeEnum type) { FollowStrategy strategy = followMap.get(type); Assert.notNull(strategy, "strategy cannot be null"); return strategy.getDetail(id); } /** * 查询跟进历史 * * @param taskId * @param type * @return */ public List todoRecord(Long taskId, Integer type) { FollowTypeEnum typeEnum = FollowTypeEnum.ofValue(type); if (Objects.isNull(typeEnum)) { FollowTask task = followTaskService.getById(taskId); BV.notNull(task, () -> "跟进任务不存在"); typeEnum = task.getType(); } FollowStrategy strategy = followMap.get(typeEnum); BV.notNull(strategy, () -> "跟进类型不正确"); return strategy.getRecordList(taskId); } /** * 查询跟进池详情 * * @param taskId * @return */ public FollowDetailVO followPoolDetail(Long taskId) { FollowTask task = followTaskService.getById(taskId); BV.notNull(task, () -> "跟进线索不存在,请刷新列表"); FollowStrategy strategy = followMap.get(task.getType()); Assert.notNull(strategy, "strategy cannot be null"); return strategy.followPoolDetail(task); } /** * 完成跟进 * * @param id * @param currentUser */ @Transactional(rollbackFor = Exception.class) public void completeRecord(Long id, FollowTypeEnum type, LoginAuthBean currentUser) { FollowStrategy strategy = followMap.get(type); Assert.notNull(strategy, "strategy cannot be null"); strategy.completeRecord(id, currentUser); } /** * 完成跟进 * * @param record */ @Transactional(rollbackFor = Exception.class) public void completeRecordAndEnd(FollowRecord record) { FollowStrategy strategy = followMap.get(record.getType()); Assert.notNull(strategy, "strategy cannot be null"); strategy.completeRecordAndEnd(record); } /** * 首保流失客户二次分配后更新跟进任务 * * @param customerId * @param type */ @Transactional(rollbackFor = Exception.class) public void updateTask(Long customerId, FollowTypeEnum type) { FollowStrategy strategy = followMap.get(type); Assert.notNull(strategy, "strategy cannot be null"); strategy.updateTask(customerId); } /** * 开始任务 * * @param task */ @Transactional(rollbackFor = Exception.class) public void startTask(FollowTask task) { FollowStrategy strategy = followMap.get(task.getType()); Assert.notNull(strategy, "strategy cannot be null"); strategy.startTask(task, true); } /** * 查询待办详情 * * @param id * @param type * @return */ public FollowDetailVO approveDetail(Long id, Integer type) { FollowTypeEnum typeEnum = FollowTypeEnum.ofValue(type); if (Objects.isNull(typeEnum)) { FollowRecord record = followRecordService.getById(id); BV.notNull(record, () -> "跟进记录不存在"); typeEnum = record.getType(); } FollowStrategy strategy = followMap.get(typeEnum); BV.notNull(strategy, () -> "跟进类型不正确"); FollowDetailVO detail = strategy.getDetail(id); detail.setType(typeEnum.getValue()); ApproveRecord approveRecord = approveRecordService.getOne(Wrappers.lambdaQuery() .eq(ApproveRecord::getDataId, detail.getTaskId()) .last("limit 1") ); if (Objects.nonNull(approveRecord)) { UserInfoDTO user = userService.user(approveRecord.getUserId()); if (Objects.nonNull(user)) { detail.setAdviserId(user.getId()); detail.setAdviserName(user.getUserName()); } detail.setReason(approveRecord.getReason()); } return detail; } /** * 主动战败 * * @param currentUser * @param reason * @param recordId */ @Transactional(rollbackFor = Exception.class) public void defeat(LoginAuthBean currentUser, String reason, Long recordId) { final String lockKey = getLockKey(recordId); Pair pair = distributedLocker.tryLock(lockKey, TimeUnit.SECONDS, 0, 15); BV.isTrue(Boolean.TRUE.equals(pair.getKey()), () -> "请勿重复提交"); try { FollowRecord record = followRecordService.getById(recordId); BV.notNull(record, () -> "跟进记录不存在"); FollowTask task = followTaskService.getById(record.getTaskId()); BV.notNull(task, () -> "跟进信息不存在"); boolean repetition = isRepetition(record.getTaskId().toString()); BV.isFalse(repetition, () -> "正在审批处理中,请勿重复申请"); FlowDto flowDto = FlowDto.create(currentUser.getGroupId(), getFlowNo(), currentUser.getUserId(), currentUser.getUserName(), task.getFollowShop()); HashMap param = new HashMap<>(2); param.put("recordId", recordId.toString()); param.put("type", task.getType().getValue().toString()); flowDto.setParam(param); String name = ""; String plate = ""; FollowStrategy strategy = followMap.get(task.getType()); Assert.notNull(strategy, "strategy cannot be null"); FollowDetailVO vo = strategy.followPoolDetail(task); if (Objects.nonNull(vo)) { name = vo.getName(); plate = vo.getPlateNo(); } List list = Arrays.asList( "申请人: " + currentUser.getUserName(), "客户: " + name, "车辆: " + plate, "跟进类型: " + task.getType().getName(), "战败原因: " + reason ); flowDto.setBriefContentList(list); String orderNo = flowApproveRpc.initiate(flowDto); ApproveRecord approveRecord = new ApproveRecord(); approveRecord.setDataId(task.getId()); approveRecord.setUserId(currentUser.getUserId()); approveRecord.setOrderNo(orderNo); approveRecord.setReason(reason); approveRecord.setState(ApproveStateEnum.WAIT); approveRecord.setType(ApproveTypeEnum.FOLLOW_DEFEAT); approveRecord.setPassed(Boolean.FALSE); approveRecord.setCreateTime(DateUtil.localDateTime2Date(LocalDateTime.now())); approveRecord.setUpdateTime(DateUtil.localDateTime2Date(LocalDateTime.now())); approveRecordService.save(approveRecord); } catch (Exception e) { distributedLocker.unlock(lockKey); throw e; } } /** * 上传跟进附件 * * @param dto */ @Transactional(rollbackFor = Exception.class) public void uploadAtt(FollowAttachmentDTO dto, LoginAuthBean currentUser) { FollowStrategy strategy = followMap.get(dto.getFollowTypeEnum()); Assert.notNull(strategy, "strategy cannot be null"); strategy.uploadAtt(dto, currentUser.getUserId()); } /** * 更新跟进任务 * * @param setting * @param type * @param groupId */ public void synFollowTask(List 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; } FollowStrategy strategy = followMap.get(typeEnum); Assert.notNull(strategy, "strategy cannot be null"); strategy.cancelFollowTask(event.getCustomerId(), event.getGenerateTime(), event.getGroupId()); } /** * 元数据生成任务 * * @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.toString(), exception); return false; } } /** * 创建跟进待办 * * @param cluePool */ public void startClue(CustomerCluePool cluePool) { FollowStrategy strategy = followMap.get(cluePool.getClueType()); Assert.notNull(strategy, "strategy cannot be null"); strategy.startClue(cluePool); } /** * 创建跟进待办 * * @param task */ @Transactional(rollbackFor = Exception.class) public void endTask(FollowTask 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 record */ public void overdueProcessing(FollowRecord record) { FollowStrategy strategy = followMap.get(record.getType()); Assert.notNull(strategy, "strategy cannot be null"); strategy.overdueProcessing(record); } /** * 终止任务 * * @param customerId * @param groupId */ @Transactional(rollbackFor = Exception.class) public void stopTask(Long customerId, Long groupId) { List typeList = Arrays.asList(FollowTypeEnum.FM, FollowTypeEnum.RM); List cluePoolList = customerCluePoolService.list(Wrappers.lambdaQuery() .eq(CustomerCluePool::getClueStatus, ClueStatusEnum.ONGOING) .in(CustomerCluePool::getClueType, typeList) .eq(CustomerCluePool::getRefererId, customerId) .eq(CustomerCluePool::getGroupId, groupId) ); if (!CollectionUtils.isEmpty(cluePoolList)) { for (CustomerCluePool clue : cluePoolList) { FollowStrategy strategy = followMap.get(clue.getClueType()); if (Objects.nonNull(strategy)) { strategy.forceStopClue(clue); } } } List cluePoolWaitList = customerCluePoolService.list(Wrappers.lambdaQuery() .eq(CustomerCluePool::getClueStatus, ClueStatusEnum.WAITING) .in(CustomerCluePool::getClueType, typeList) .eq(CustomerCluePool::getRefererId, customerId) .eq(CustomerCluePool::getGroupId, groupId) ); if (CollectionUtils.isEmpty(cluePoolWaitList)) { return; } List ids = cluePoolWaitList.stream().map(CustomerCluePool::getId).filter(Objects::nonNull).collect(Collectors.toList()); if (!CollectionUtils.isEmpty(ids)) { customerCluePoolService.removeByIds(ids); } } @Transactional(rollbackFor = Exception.class) public void onForbidden(Long customerId, Long groupId) { List typeList = Arrays.asList(FollowTypeEnum.FM, FollowTypeEnum.RM, FollowTypeEnum.IR); List cluePoolList = customerCluePoolService.list(Wrappers.lambdaQuery() .eq(CustomerCluePool::getClueStatus, ClueStatusEnum.ONGOING) .in(CustomerCluePool::getClueType, typeList) .eq(CustomerCluePool::getRefererId, customerId) .eq(CustomerCluePool::getGroupId, groupId) ); if (!CollectionUtils.isEmpty(cluePoolList)) { for (CustomerCluePool clue : cluePoolList) { FollowStrategy strategy = followMap.get(clue.getClueType()); if (Objects.nonNull(strategy)) { strategy.onForbiddenStopClue(clue); } } } List cluePoolWaitList = customerCluePoolService.list(Wrappers.lambdaQuery() .eq(CustomerCluePool::getClueStatus, ClueStatusEnum.WAITING) .in(CustomerCluePool::getClueType, typeList) .eq(CustomerCluePool::getRefererId, customerId) .eq(CustomerCluePool::getGroupId, groupId) ); if (!CollectionUtils.isEmpty(cluePoolWaitList)) { customerCluePoolService.removeByIds(cluePoolWaitList); } } /** * 终止任务 * * @param task */ @Transactional(rollbackFor = Exception.class) public void stopTask(FollowTask task) { CustomerCluePool cluePool = customerCluePoolService.getById(task.getClueId()); FollowStrategy strategy = followMap.get(task.getType()); if (Objects.nonNull(strategy)) { strategy.forceStopClue(cluePool); } } public void readCallReport(CallReportDTO dto, boolean accidentCar, Long... idArr) { if (Objects.isNull(dto) || idArr == null || idArr.length <= 0) { return; } final Long groupId = dto.getGroupId(); final Long staffId = dto.getStaffId(); final Long talkTime = dto.getTalkTime(); if (Objects.isNull(talkTime) || talkTime <= 0) { return; } if (accidentCar) { CustomerCluePool cluePool = customerCluePoolService.getOne(Wrappers.lambdaQuery() .eq(CustomerCluePool::getRefererId, idArr[0]) .eq(CustomerCluePool::getGroupId, groupId) .eq(CustomerCluePool::getClueType, FollowTypeEnum.AC) .eq(CustomerCluePool::getClueStatus, ClueStatusEnum.ONGOING) .orderByDesc(CustomerCluePool::getId) .last(" limit 1") ); if (Objects.nonNull(cluePool)) { completeRecord(dto, cluePool.getId(), staffId, dto.getCallId()); } } else { List list = customerCluePoolService.list(Wrappers.lambdaQuery() .eq(CustomerCluePool::getGroupId, groupId) .eq(CustomerCluePool::getClueStatus, ClueStatusEnum.ONGOING) .in(CustomerCluePool::getRefererId, Arrays.asList(idArr)) ); if (!CollectionUtils.isEmpty(list)) { list.forEach(cluePool -> completeRecord(dto, cluePool.getId(), staffId, dto.getCallId())); } } } 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 String getLockKey(Long recordId) { BV.notNull(recordId, "recordId cannot be null"); return String.format("%s:lock:%s", getKeyPrefix(), recordId); } /** * 审批防重 * * @param taskId * @return */ private boolean isRepetition(String taskId) { return approveRecordService.count(Wrappers.lambdaQuery() .eq(ApproveRecord::getDataId, taskId) .eq(ApproveRecord::getType, ApproveTypeEnum.FOLLOW_DEFEAT) .eq(ApproveRecord::getState, ApproveStateEnum.WAIT) ) > 0; } private void completeRecord(CallReportDTO reportDTO, final Long clueId, final Long staffId, final String callId) { FollowTask followTask = followTaskService.queryOngoingTaskByClueId(clueId); if (Objects.isNull(followTask)) { return; } FollowTypeEnum followType = followTask.getType(); List list = followRecordService.list(Wrappers.lambdaQuery() .eq(FollowRecord::getTaskId, followTask.getId()) .eq(FollowRecord::getUserId, staffId) .eq(FollowRecord::getType, followType) .eq(FollowRecord::getAddTodo, Boolean.TRUE) .eq(FollowRecord::getOutTime, Boolean.FALSE) .isNull(FollowRecord::getFollowTime) ); if (CollectionUtils.isEmpty(list)) { return; } FollowStrategy strategy = followMap.get(followType); Assert.notNull(strategy, "strategy cannot be null"); List reportHistoryList = new ArrayList<>(); for (FollowRecord record : list) { FollowAttachmentDTO dto = new FollowAttachmentDTO(); dto.setAttachments(callId); dto.setTaskId(record.getTaskId()); dto.setFollowType(followType.getValue()); dto.setRecordId(record.getId()); dto.setFeedbackType(FollowTypeEnum.AC.equals(followType) ? FeedbackTypeEnum.OTHER.getValue() : null); dto.setAttType(AttTypeEnum.SMART_PHONE.getValue()); strategy.uploadAtt(dto, staffId); reportHistoryList.add(createHistory(reportDTO, record, followType)); } secretReportHistoryService.saveBatch(reportHistoryList); } private SecretReportHistory createHistory(CallReportDTO reportDTO, FollowRecord record, FollowTypeEnum followTypeEnum) { SecretReportHistory history = new SecretReportHistory(); history.setTaskId(record.getTaskId()); history.setTaskType(followTypeEnum); 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.lambdaQuery() .eq(FollowRecordLog::getTaskId, record.getTaskId()) .eq(FollowRecordLog::getAttType, AttTypeEnum.SMART_PHONE) ); history.setFirstCall(count <= 0); return history; } }