FollowBizService.java 14.7 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
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.follow.FollowRecord;
import cn.fw.valhalla.domain.db.follow.FollowTask;
import cn.fw.valhalla.domain.dto.FollowAttachmentDTO;
import cn.fw.valhalla.domain.enums.ApproveStateEnum;
import cn.fw.valhalla.domain.enums.ApproveTypeEnum;
import cn.fw.valhalla.domain.enums.FollowTypeEnum;
import cn.fw.valhalla.domain.enums.TaskStateEnum;
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.ApproveRecordService;
import cn.fw.valhalla.service.data.FollowRecordService;
import cn.fw.valhalla.service.data.FollowTaskService;
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<FollowTypeEnum, FollowStrategy> 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;

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

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

    @Autowired
    public FollowBizService(final List<FollowStrategy> followStrategyList,
                            final FlowApproveRpc flowApproveRpc,
                            final ApproveRecordService approveRecordService,
                            final FollowTaskService followTaskService,
                            final FollowRecordService followRecordService,
                            final UserService userService,
                            final DistributedLocker distributedLocker) {
        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;
    }

    /**
     * 查询待办列表
     *
     * @param queryVO
     * @param currentUser
     * @return
     */
    public AppPage<FollowTodoListVO> 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<FollowTodoListVO> list = strategy.getList(startIndex, pageSize, currentUser.getUserId());
        AppPage<FollowTodoListVO> 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<FollowRecordVO> todoRecord(Long taskId, FollowTypeEnum type) {
        FollowStrategy strategy = followMap.get(type);
        Assert.notNull(strategy, "strategy cannot be null");
        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 completeRecord2(FollowRecord record) {
        FollowStrategy strategy = followMap.get(record.getType());
        Assert.notNull(strategy, "strategy cannot be null");
        strategy.completeRecord2(record);
    }

    /**
     * 查询待办详情
     *
     * @param id
     * @param type
     * @return
     */
    public FollowDetailVO approveDetail(Long id, FollowTypeEnum type) {
        FollowStrategy strategy = followMap.get(type);
        Assert.notNull(strategy, "strategy cannot be null");
        FollowDetailVO detail = strategy.getDetail(id);
        ApproveRecord approveRecord = approveRecordService.getOne(Wrappers.<ApproveRecord>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<Boolean, RLock> 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<String, String> 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<String> 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.getFollowType());
        Assert.notNull(strategy, "strategy cannot be null");
        strategy.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;
        }
        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");

        return strategy.origin2task(originalData);
    }

    /**
     * 创建跟进待办
     *
     * @param task
     */
    public Long createTaskRecord(FollowTask task) {
        FollowStrategy strategy = followMap.get(task.getType());
        Assert.notNull(strategy, "strategy cannot be null");

        return strategy.createFirstRecord(task);
    }

    /**
     * 逾期处理
     *
     * @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
     */
    @Transactional(rollbackFor = Exception.class)
    public void stopTask(Long customerId) {
        List<FollowTypeEnum> typeList = Arrays.asList(FollowTypeEnum.FM, FollowTypeEnum.RM);
        List<FollowTask> list = followTaskService.list(Wrappers.<FollowTask>lambdaQuery()
                .eq(FollowTask::getCustomerId, customerId)
                .eq(FollowTask::getFinished, Boolean.FALSE)
                .eq(FollowTask::getState, TaskStateEnum.ONGOING)
                .in(FollowTask::getType, typeList)
        );
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        for (FollowTask task : list) {
            FollowStrategy strategy = followMap.get(task.getType());
            if (Objects.nonNull(strategy)) {
                strategy.stopFollowTask(task);
            }
        }
    }

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


    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.<ApproveRecord>lambdaQuery()
                .eq(ApproveRecord::getDataId, taskId)
                .eq(ApproveRecord::getType, ApproveTypeEnum.FOLLOW_DEFEAT)
                .eq(ApproveRecord::getState, ApproveStateEnum.WAIT)
        ) > 0;
    }
}