IRFollowStrategy.java 16.5 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
package cn.fw.valhalla.service.bus.follow.strategy.impl;

import cn.fw.common.web.auth.LoginAuthBean;
import cn.fw.valhalla.common.constant.RoleCode;
import cn.fw.valhalla.common.utils.DateUtil;
import cn.fw.valhalla.common.utils.MobileUtil;
import cn.fw.valhalla.domain.db.OriginalData;
import cn.fw.valhalla.domain.db.customer.Customer;
import cn.fw.valhalla.domain.db.follow.FollowNoticeRecord;
import cn.fw.valhalla.domain.db.follow.FollowRecord;
import cn.fw.valhalla.domain.db.follow.FollowTask;
import cn.fw.valhalla.domain.dto.CustomerDetailDto;
import cn.fw.valhalla.domain.dto.FollowAttachmentDTO;
import cn.fw.valhalla.domain.enums.*;
import cn.fw.valhalla.domain.vo.follow.*;
import cn.fw.valhalla.domain.vo.setting.SettingVO;
import cn.fw.valhalla.rpc.angel.dto.InsuranceDTO;
import cn.fw.valhalla.rpc.erp.dto.PostUserDTO;
import cn.fw.valhalla.rpc.erp.dto.UserRoleDataRangeDTO;
import cn.fw.valhalla.rpc.oop.dto.ShopDTO;
import cn.fw.valhalla.service.bus.follow.strategy.AbstractFollowStrategy;
import cn.fw.valhalla.service.event.CancelApproveEvent;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

import static cn.fw.common.businessvalidator.Validator.BV;

/**
 * @author : kurisu
 * @className : IRFollowStrategy
 * @description : 续保策略
 * @date: 2020-08-17 10:48
 */
@Slf4j
@Component
public class IRFollowStrategy extends AbstractFollowStrategy {
    @Override
    public FollowTypeEnum getFollowType() {
        return FollowTypeEnum.IR;
    }

    @Override
    public List<FollowTodoListVO> getList(Integer startIndex, Integer pageSize, Long userId) {
        List<FollowRecord> list = list(startIndex, pageSize, userId, getFollowType());
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<FollowTodoListVO> voList = new ArrayList<>();
        for (FollowRecord followRecord : list) {
            IRTodoListVO vo = new IRTodoListVO();
            vo.setId(followRecord.getId());
            vo.setTaskId(followRecord.getTaskId());
            vo.setCustomerId(followRecord.getCustomerId());
            vo.setDeadline(followRecord.getDeadline());
            CustomerDetailDto customerDetailDto = queryCustomerInfo(followRecord.getCustomerId());
            vo.setName(customerDetailDto.getName());
            vo.setCarImage(customerDetailDto.getCarImage());
            vo.setPlateNo(customerDetailDto.getPlateNo());
            Optional<InsuranceDTO> insuranceDTO = queryInsuInfo(followRecord.getCustomerId());
            insuranceDTO.ifPresent(ins -> {
                vo.setInsComName(ins.getInsurerName());
                vo.setInsExpiration(ins.getExpiryDate());
            });
            voList.add(vo);
        }
        return voList;
    }

    @Override
    public FollowDetailVO getDetail(Long id) {
        FollowRecord followRecord = followRecordService.getById(id);
        BV.notNull(followRecord, "跟进记录不存在");
        IRDetailVO vo = assemble(followRecord.getCustomerId());
        vo.setId(followRecord.getId());
        vo.setTaskId(followRecord.getTaskId());
        vo.setDeadline(followRecord.getDeadline());
        return vo;
    }

    @Override
    public List<FollowRecordVO> getRecordList(Long taskId) {
        return super.getRecordList(taskId);
    }

    @Override
    public void completeRecord(Long id, LoginAuthBean currentUser) {
        super.completeRecord(id, currentUser);
    }

    @Override
    public void uploadAtt(FollowAttachmentDTO dto, Long userId) {
        super.uploadAtt(dto, userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelFollowTask(Long customerId, Date time, Long groupId) {
        List<FollowTask> list = followTaskService.list(Wrappers.<FollowTask>lambdaQuery()
                .eq(FollowTask::getCustomerId, customerId)
                .eq(FollowTask::getGroupId, groupId)
                .eq(FollowTask::getType, getFollowType())
                .and(w -> w.ge(FollowTask::getCreateTime, time).or().ge(FollowTask::getFinishTime, time))
        );

        for (FollowTask followTask : list) {
            if (TaskStateEnum.WAITING.equals(followTask.getState())) {
                followTaskService.removeById(followTask.getId());
                followNoticeRecordService.removeByTaskId(followTask.getId());
            }
            if (TaskStateEnum.ONGOING.equals(followTask.getState())) {
                followTaskService.removeById(followTask.getId());
                followNoticeRecordService.removeByTaskId(followTask.getId());
                cancelFollowTodo(followTask.getId());
            }
            if (TaskStateEnum.END.equals(followTask.getState())) {
                rollback(followTask);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void settingChanged(List<SettingVO> setting, Long groupId) {
        List<FollowTask> list = followTaskService.list(Wrappers.<FollowTask>lambdaQuery()
                .eq(FollowTask::getState, TaskStateEnum.WAITING)
                .eq(FollowTask::getType, getFollowType())
        );
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        updateTask(list, setting);

        SettingVO noticeSetting = setting.stream().filter(r -> SettingTypeEnum.FIRST_NOTICE_TIME.getValue().equals(r.getType())).findFirst().orElse(new SettingVO());
        updateNoticeRecord(list, noticeSetting);
    }

    @Override
    protected void updateTask(List<FollowTask> list, List<SettingVO> setting) {
        for (SettingVO vo : setting) {
            final Integer unit = vo.getUnit();
            final int value = Optional.ofNullable(vo.getDetailValue()).orElse(0);
            SettingUnitEnum unitEnum = SettingUnitEnum.ofValue(unit);

            if (SettingTypeEnum.FIRST_TRIGGER_TIME.getValue().equals(vo.getType())) {
                if (Objects.nonNull(unitEnum) && value > 0) {
                    final int calendarType = getCalendarType(unitEnum);
                    list.forEach(task -> {
                        Date originTime = task.getOriginTime();
                        Timestamp timestamp = DateUtil.getExpired(originTime, -1 * value, calendarType);
                        task.setBeginTime(timestamp);
                    });
                }
            }
            if (SettingTypeEnum.CHANGE_TIME.getValue().equals(vo.getType())) {
                if (Objects.nonNull(unitEnum) && value > 0) {
                    final int calendarType = getCalendarType(unitEnum);
                    list.forEach(task -> {
                        Date originTime = task.getOriginTime();
                        Timestamp timestamp = DateUtil.getExpired(originTime, -1 * value, calendarType);
                        task.setBeginTime(timestamp);
                    });
                }
            }
            if (SettingTypeEnum.FAIL_TIME.getValue().equals(vo.getType())) {
                if (Objects.nonNull(unitEnum) && value > 0) {
                    final int calendarType = getCalendarType(unitEnum);
                    list.forEach(task -> {
                        Date originTime = task.getOriginTime();
                        Timestamp timestamp = DateUtil.getExpired(originTime, value, calendarType);
                        task.setBeginTime(timestamp);
                    });
                }
            }
        }
        followTaskService.updateBatchById(list);
    }

    /**
     * 更新服务号消息记录
     *
     * @param list
     * @param vo
     */
    @Override
    protected void updateNoticeRecord(List<FollowTask> list, SettingVO vo) {
        List<Long> idList = list.stream().map(FollowTask::getId).collect(Collectors.toList());
        List<FollowNoticeRecord> noticeList = followNoticeRecordService.list(Wrappers.<FollowNoticeRecord>lambdaQuery()
                .eq(FollowNoticeRecord::getStatus, SendStatusEnum.NOT_SENT)
                .in(FollowNoticeRecord::getTaskId, idList)
        );
        Integer unit = vo.getUnit();
        int value = Optional.ofNullable(vo.getDetailValue()).orElse(0);
        SettingUnitEnum unitEnum = SettingUnitEnum.ofValue(unit);
        if (Objects.isNull(unitEnum) || value <= 0) {
            return;
        }
        final int calendarType = getCalendarType(unitEnum);
        for (FollowTask task : list) {
            for (FollowNoticeRecord noticeRecord : noticeList) {
                if (task.getId().equals(noticeRecord.getTaskId())) {
                    Date originTime = task.getOriginTime();
                    Timestamp timestamp = DateUtil.getExpired(originTime, -1 * value, calendarType);
                    noticeRecord.setSendTime(timestamp);
                }
            }
        }
        followNoticeRecordService.updateBatchById(noticeList);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean origin2task(OriginalData originalData) {
        Customer customer = customerService.queryById(originalData.getCustomerId());
        if (Objects.isNull(customer)) {
            return true;
        }
        this.completeTask(customer, originalData.getGenerateTime());

        final FollowTask task = createTask(originalData, getFollowType());
        if (Objects.isNull(task)) {
            return true;
        }
        Long shopId = customer.getShopId();
        List<PostUserDTO> userList = userService.getUserByRole(shopId, RoleCode.XBGJ);

        if (CollectionUtils.isEmpty(userList)) {
            log.error("跟进人员获取失败:没有续保跟进员");
            return false;
        }
        task.setOriginUser(userList.get(0).getUserId());
        task.setFollowUser(userList.get(0).getUserId());

        userList.stream().filter(r -> customer.getAdviserId().equals(r.getUserId())).findFirst().ifPresent(user -> {
            task.setOriginUser(user.getUserId());
            task.setFollowUser(user.getUserId());
        });

        ShopDTO shop = oopService.shop(shopId);
        if (Objects.nonNull(shop)) {
            task.setDealerId(shop.getDealerId());
        }
        task.setOriginShop(shopId);
        task.setFollowShop(shopId);
        boolean saved = followTaskService.save(task);
        if (!saved) {
            return true;
        }
        return this.createFirstNotice(task);
    }

    /**
     * 生成任务实体
     *
     * @param originalData
     * @return
     */
    @Override
    protected FollowTask createTask(final OriginalData originalData, FollowTypeEnum followType) {
        final FollowTask followTask = new FollowTask();
        followTask.setCustomerId(originalData.getCustomerId());
        followTask.setType(followType);
        followTask.setState(TaskStateEnum.WAITING);
        Optional<InsuranceDTO> optional = insurerRpcService.getByInsId(originalData.getCustomerId(), originalData.getDetailId());
        if (optional.isPresent()) {
            followTask.setOriginTime(optional.get().getExpiryDate());
        } else {
            followTask.setOriginTime(DateUtil.getExpired(originalData.getGenerateTime(), 1, Calendar.YEAR));
        }
        settingBizService.querySettingByType(followType, SettingTypeEnum.FIRST_TRIGGER_TIME, originalData.getGroupId())
                .ifPresent(r -> followTask.setBeginTime(calDate(r, followTask.getOriginTime(), true)));

        settingBizService.querySettingByType(followType, SettingTypeEnum.CHANGE_TIME, originalData.getGroupId())
                .ifPresent(r -> followTask.setChangeUserTime(calDate(r, followTask.getOriginTime(), true)));

        settingBizService.querySettingByType(followType, SettingTypeEnum.FAIL_TIME, originalData.getGroupId())
                .ifPresent(r -> followTask.setDeadline(calDate(r, followTask.getOriginTime(), false)));
        followTask.setFinished(Boolean.FALSE);
        followTask.setGroupId(originalData.getGroupId());
        followTask.setCreateTime(originalData.getGenerateTime());

        return followTask;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createFirstRecord(FollowTask task) {
        return super.createFirstRecord(task);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void overdueProcessing(FollowRecord record) {
        super.overdueProcessing(record);
    }

    @Override
    public FollowDetailVO followPoolDetail(FollowTask task) {
        IRDetailVO vo = assemble(task.getCustomerId());
        vo.setTaskId(task.getId());
        return vo;
    }

    /**
     * 生成消息推送
     *
     * @param task
     */
    @Override
    protected boolean createFirstNotice(final FollowTask task) {
        if (!task.getDeadline().after(task.getBeginTime()) || !task.getDeadline().after(DateUtil.localDateTime2Date(LocalDateTime.now()))) {
            return true;
        }
        final FollowNoticeRecord record = new FollowNoticeRecord();
        record.setTaskId(task.getId());
        record.setCustomerId(task.getCustomerId());
        record.setStatus(SendStatusEnum.NOT_SENT);
        settingBizService.querySettingByType(task.getType(), SettingTypeEnum.FIRST_NOTICE_TIME, task.getGroupId())
                .ifPresent(r -> record.setSendTime(calDate(r, task.getOriginTime(), true)));
        record.setCreateTime(new Date());
        record.setFollowType(task.getType());
        return followNoticeRecordService.save(record);
    }


    /**
     * 完成之前的跟进
     *
     * @param customer
     * @param completeTime
     */
    private void completeTask(Customer customer, Date completeTime) {
        List<FollowTask> list = followTaskService.list(Wrappers.<FollowTask>lambdaQuery()
                .eq(FollowTask::getType, getFollowType())
                .ne(FollowTask::getState, TaskStateEnum.END)
                .eq(FollowTask::getCustomerId, customer.getId())
        );
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        List<Long> idList = new ArrayList<>();
        List<FollowTask> taskList = new ArrayList<>();
        for (FollowTask task : list) {
            if (TaskStateEnum.WAITING.equals(task.getState())) {
                idList.add(task.getId());
            }

            if (TaskStateEnum.ONGOING.equals(task.getState())) {
                List<UserRoleDataRangeDTO> range = userService.getUserRoleDataRange(task.getFollowUser(), RoleCode.FWGW);
                task.setFinishUser(customer.getAdviserId());
                task.setFinishShop(customer.getShopId());
                if (CollectionUtils.isEmpty(range)) {
                    task.setFinishUser(task.getFollowUser());
                    task.setFinishShop(task.getFollowShop());
                }
                task.setFinished(Boolean.TRUE);
                task.setState(TaskStateEnum.END);
                task.setFinishTime(completeTime);
                completeTodo(task.getId());
                taskList.add(task);
                CancelApproveEvent event = new CancelApproveEvent(task.getId(), ApproveTypeEnum.FOLLOW_DEFEAT);
                eventPublisher.publishEvent(event);
            }
        }
        List<Long> ids = list.stream().map(FollowTask::getId).collect(Collectors.toList());
        followNoticeRecordService.removeByTaskIds(ids);
        if (idList.size() > 0) {
            followTaskService.removeByIds(idList);
        }
        if (taskList.size() > 0) {
            followTaskService.updateBatchById(taskList);
        }
    }

    @Override
    public IRDetailVO assemble(Long customerId) {
        CustomerDetailDto detailDto = queryCustomerInfo(customerId);
        IRDetailVO vo = new IRDetailVO();
        vo.setCustomerId(customerId);
        vo.setAdviserId(detailDto.getAdviserId());
        vo.setAdviserName(detailDto.getAdviserName());
        vo.setVin(detailDto.getFrameNo());
        vo.setName(detailDto.getName());
        vo.setMobile(detailDto.getMobile());
        vo.setRegion(MobileUtil.attribution(detailDto.getMobile()));
        vo.setRealMobile(detailDto.getMobile());
        vo.setPlateNo(detailDto.getPlateNo());
        vo.setCarModel(detailDto.getBrandName() + " " + detailDto.getSeriesName());
        Optional<InsuranceDTO> insuranceDTO = queryInsuInfo(customerId);
        insuranceDTO.ifPresent(ins -> {
            vo.setTclInsComName(ins.getTciInsurerName());
            vo.setTclInsExpiration(ins.getTciExpiryDate());
            vo.setBusInsComName(ins.getInsurerName());
            vo.setBusInsExpiration(ins.getExpiryDate());
        });
        return vo;
    }
}