KpiGroupBizService.java 19.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 420 421 422
package cn.fw.morax.service.biz.kpi;

import cn.fw.common.data.mybatis.pagination.PageData;
import cn.fw.common.exception.BusinessException;
import cn.fw.common.page.AppPage;
import cn.fw.common.web.annotation.DisLock;
import cn.fw.common.web.auth.LoginAuthBean;
import cn.fw.morax.common.constant.Constant;
import cn.fw.morax.common.pojo.event.ApprovalResultEvent;
import cn.fw.morax.common.pojo.event.KpiGroupChangeEvent;
import cn.fw.morax.common.utils.DateUtil;
import cn.fw.morax.common.utils.EventBusUtil;
import cn.fw.morax.common.utils.PublicUtil;
import cn.fw.morax.domain.db.ApprovalRecord;
import cn.fw.morax.domain.db.kpi.*;
import cn.fw.morax.domain.dto.*;
import cn.fw.morax.domain.dto.query.KpiGroupQueryDTO;
import cn.fw.morax.domain.dto.query.KpiGroupRepeatQueryDTO;
import cn.fw.morax.domain.enums.*;
import cn.fw.morax.domain.vo.kpi.*;
import cn.fw.morax.service.biz.ApprovalBizService;
import cn.fw.morax.service.biz.CommonService;
import cn.fw.morax.service.data.kpi.*;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Maps;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.*;
import java.util.stream.Collectors;

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

@RequiredArgsConstructor
@Service
@Slf4j
public class KpiGroupBizService {

    private final KpiGroupIndicatorLaddersService kpiGroupIndicatorLaddersService;
    private final KpiGroupIndicatorService kpiGroupIndicatorService;
    private final KpiGroupUserBizService kpiGroupUserBizService;
    private final KpiStarLaddersService kpiStarLaddersService;
    private final KpiGroupDataService kpiGroupDataService;
    private final ApprovalBizService approvalBizService;
    private final IndicatorsService indicatorsService;
    private final KpiGroupService kpiGroupService;

    @Value("${spring.cache.custom.global-prefix}:kpi:group:save:")
    @Getter
    private String savePrefix;

    /**
     * 分页查询
     * @param dto
     * @return
     */
    public AppPage<KpiGroupVO> kpiGroupPage(KpiGroupQueryDTO dto) {
        PageData<KpiGroup> pageData = kpiGroupService.page(new PageData<>(dto.getCurrent(), dto.getPageSize()),
                Wrappers.<KpiGroup>lambdaQuery()
                        .eq(KpiGroup::getGroupId, dto.getGroupId())
                        .eq(PublicUtil.isNotEmpty(dto.getPostId()), KpiGroup::getPostId, dto.getPostId())
                        .eq(KpiGroup::getYn, Boolean.TRUE)
                        .last("ORDER BY FIELD(`status`,3,1,2,4)")
        );
        return PublicUtil.toPage(pageData, kpiGroup -> {
            KpiGroupVO kpiGroupVo = PublicUtil.copy(kpiGroup, KpiGroupVO.class);
            kpiGroupVo.setBeginTime(YearMonth.from(kpiGroup.getBeginTime()));
            return kpiGroupVo;
        });
    }

    /**
     * 绩效组详情
     * @param kpiGroupId
     * @return
     */
    public KpiGroupVO kpiGroupDetail(Long kpiGroupId) {
        KpiGroup kpiGroup = kpiGroupService.getById(kpiGroupId);
        BV.notNull(kpiGroup, "绩效配置不存在,请重试");
        KpiGroupVO kpiGroupVo = KpiGroupVO.convertKpiGroup(kpiGroup);
        List<KpiStarLadders> starLadders = kpiStarLaddersService.list(Wrappers.<KpiStarLadders>lambdaQuery()
                .eq(KpiStarLadders::getKpiGroupId, kpiGroupId)
                .eq(KpiStarLadders::getYn, Boolean.TRUE)
        );
        List<KpiStarLaddersVO> starLaddersVos = PublicUtil.copyList(starLadders, KpiStarLaddersVO.class);
        for (KpiStarLaddersVO starLaddersVO : starLaddersVos) {
            starLaddersVO.setUpper(starLaddersVO.getUpper().multiply(Constant.ONE_HUNDRED));
            starLaddersVO.setLower(starLaddersVO.getLower().multiply(Constant.ONE_HUNDRED));
        }
        kpiGroupVo.setStarLadders(starLaddersVos);

        List<KpiGroupIndicator> kpiGroupIndicators = kpiGroupIndicatorService.list(Wrappers.<KpiGroupIndicator>lambdaQuery()
                .eq(KpiGroupIndicator::getKpiGroupId, kpiGroupId)
                .eq(KpiGroupIndicator::getYn, Boolean.TRUE)
        );
        List<KpiGroupIndicatorVO> kpiGroupIndicatorVOS = PublicUtil.copyList(kpiGroupIndicators, KpiGroupIndicatorVO.class);
        for (KpiGroupIndicatorVO indicatorVO : kpiGroupIndicatorVOS) {
            if (KpiTargetTypeEnum.RATIO.equals(indicatorVO.getTargetType())) {
                indicatorVO.setTargetValue(indicatorVO.getTargetValue().multiply(Constant.ONE_HUNDRED));
            }
        }
        List<Long> kpiGroupIndicatorIds = kpiGroupIndicatorVOS.stream().map(KpiGroupIndicatorVO::getId).collect(Collectors.toList());
        if (PublicUtil.isEmpty(kpiGroupIndicatorIds)) {
            kpiGroupVo.setIndicators(kpiGroupIndicatorVOS);
            return kpiGroupVo;
        }
        List<KpiGroupIndicatorLadders> kpiGroupIndicatorLadders = kpiGroupIndicatorLaddersService.list(Wrappers.<KpiGroupIndicatorLadders>lambdaQuery()
                .in(KpiGroupIndicatorLadders::getKpiGroupIndicatorId, kpiGroupIndicatorIds)
                .eq(KpiGroupIndicatorLadders::getYn, Boolean.TRUE)
                .orderByAsc(KpiGroupIndicatorLadders::getId)
        );
        Map<Long, List<KpiGroupIndicatorLadders>> indicatorLaddersMap = kpiGroupIndicatorLadders.stream().collect(Collectors.groupingBy(KpiGroupIndicatorLadders::getKpiGroupIndicatorId));
        for (KpiGroupIndicatorVO indicatorVo : kpiGroupIndicatorVOS) {
            if (indicatorLaddersMap.containsKey(indicatorVo.getId())) {
                List<KpiGroupIndicatorLaddersVO> laddersVos = PublicUtil.copyList(indicatorLaddersMap.get(indicatorVo.getId()), KpiGroupIndicatorLaddersVO.class);
                for (KpiGroupIndicatorLaddersVO laddersVO : laddersVos) {
                    laddersVO.convertToPercent();
                }
                indicatorVo.setIndicatorLadders(laddersVos);
            }
        }
        kpiGroupVo.setIndicators(kpiGroupIndicatorVOS);
        return kpiGroupVo;
    }

    /**
     * 绩效组保存
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    @DisLock(prefix = "#this.getSavePrefix()", key = "#dto.getPostId()", message = "保存中,请勿重复操作")
    public KpiGroupSavePromptVO saveKpi(KpiGroupDTO dto, LoginAuthBean user) {
        //初始化数据
        this.initKpiDate(dto);
        //检查数据
        this.checkKpi(dto);
        this.checkKpiLadders(dto.getIndicators());
        this.checkStarLadders(dto.getStarLadders(), dto.getStarEvaluationType());
        KpiGroupSavePromptVO promptVo = this.checkShopKpiRepeat(dto);
        if (promptVo.getPrompt()) {
            return promptVo;
        }
        //保存相关数据
        KpiGroup kpiGroup = kpiGroupDataService.saveKpiGroup(dto);
        kpiGroupDataService.saveKpiIndicators(dto.getIndicators(), kpiGroup);
        kpiGroupDataService.saveKpiStarLadders(dto.getStarLadders(), kpiGroup);
        Integer staffNum = kpiGroupUserBizService.queryShopPostCurStaffNum(dto.getPostId(), dto.getShopIds());
        approvalBizService.applyApproveKpi(kpiGroup, user, staffNum);
        return new KpiGroupSavePromptVO(false);
    }

    /**
     * 检查绩效组配置状态
     *
     * @param dto
     */
    public void checkKpi(KpiGroupDTO dto) {
        checkNameRepetition(dto.getId(), dto.getName());
        Long postId = dto.getPostId();
        List<Long> shopIds = dto.getShopIds();
        List<KpiGroup> effectKpis = kpiGroupService.getApprovingKpis(postId, shopIds, dto.getId(), dto.getBeginTime());
        if (PublicUtil.isNotEmpty(effectKpis)) {
            KpiGroup kpiGroup = effectKpis.get(0);
            List<String> shopNames = new ArrayList<>(kpiGroup.getShopNames());
            shopNames.retainAll(dto.getShopNames());
            throw new BusinessException("绩效组门店【" + String.join(",", shopNames) + "】存在" +
                    kpiGroup.getStatus().getName() + "配置");
        }

        Set<Long> indicatorIds = new HashSet<>();
        dto.getIndicators().stream().forEach(indicator -> {
            if (indicatorIds.contains(indicator.getIndicatorId())) {
                throw new BusinessException("【" + indicator.getIndicatorName() + "】指标已配置,不能重复配置");
            }
            indicatorIds.add(indicator.getIndicatorId());
        });

        List<Indicators> indicators = indicatorsService.list(Wrappers.<Indicators>lambdaQuery()
                .in(Indicators::getId, indicatorIds)
                .eq(Indicators::getYn, Boolean.TRUE)
        );
        Map<Long, KpiTargetTypeEnum> indicatorTargetMap = indicators.stream().collect(
                Collectors.toMap(Indicators::getId, Indicators::getTargetType, (v1, v2) -> v1));
        dto.getIndicators().stream().forEach(indicator -> {
            if (! indicatorTargetMap.containsKey(indicator.getIndicatorId())) {
                throw new BusinessException("【" + indicator.getIndicatorName() + "】指标不存在或被禁用,请重试");
            }
            if (! KpiTargetTypeEnum.NO.equals(indicatorTargetMap.get(indicator.getIndicatorId()))) {
                if (PublicUtil.isEmpty(indicator.getTargetValue())) {
                    throw new BusinessException("【" + indicator.getIndicatorName() + "】指标目标值未设置,请重试");
                }
            }
        });

        //原来的绩效组配置不能在审批中
        if (PublicUtil.isEmpty(dto.getId())) {
            return;
        }
        KpiGroup kpiGroup = kpiGroupService.getById(dto.getId());
        BV.notNull(kpiGroup, "绩效配置不存在,请重试");
        BV.isFalse((SettingStatusEnum.APPROVING.equals(kpiGroup.getStatus())), "审批中的绩效组配置不能编辑");
        dto.setKgc(kpiGroup.getKgc());
    }

    /**
     * 检查绩效组排名名称是否重复
     *
     * @param id
     * @param name
     */
    public void checkNameRepetition(Long id, String name) {
        int count = kpiGroupService.count(Wrappers.<KpiGroup>lambdaQuery()
                .eq(KpiGroup::getName, name)
                .ne(PublicUtil.isNotEmpty(id), KpiGroup::getId, id)
                .eq(KpiGroup::getYn, Boolean.TRUE)
        );
        BV.isTrue(count <= 0, "绩效组名称重复,请重新输入");
    }

    /**
     * 检查指标修改的权限
     * @param dto
     */
    private void initKpiDate(KpiGroupDTO dto) {
        LocalDate currentTime = LocalDate.now();
        dto.setBeginTime((EffectMonthEnum.CURRENT_MONTH.equals(dto.getBeginTimeType()) ? currentTime : PublicUtil.getNextMonthFirstDay()));
    }

    /**
     * 检查绩效组配置是否重复
     * 同月
     * 之前没有这些门店配置,不提示
     * 有这些门店配置
     *      1)门店和之前相同不提示
     *      2)门店比之前少,之前ABC门店,现A门店,提示BC门店缺失绩效组配置
     *      3)门店比之前多,配置1 ABC门店, 配置2 DE门店,新增ABCD门店,提示E门店缺失绩效配置
     * @param kpiGroupDTO
     */
    private KpiGroupSavePromptVO checkShopKpiRepeat(KpiGroupDTO kpiGroupDTO) {
        //强制提交,退出检查
        if (kpiGroupDTO.getForce()) {
            return new KpiGroupSavePromptVO(false);
        }

        YearMonth yearMonth = YearMonth.now();
        YearMonth beginTime = YearMonth.from(kpiGroupDTO.getBeginTime());
        StringBuilder msgBuilder = new StringBuilder();
        if (yearMonth.equals(beginTime)) {
            KpiGroupRepeatQueryDTO effectRepeatDTO = KpiGroupRepeatQueryDTO.convertDto(kpiGroupDTO, SettingStatusEnum.EFFECTIVE);
            List<KpiGroup> effectKpiGroups = kpiGroupService.queryRepeatKpiGroup(effectRepeatDTO);
            if (PublicUtil.isNotEmpty(effectKpiGroups)) {
                msgBuilder.append("审批通过后").append(yearMonth.getMonth().getValue()).append("月份已生效绩效组配置会被移除,门店【");
                HashSet<String> shopNames = effectKpiGroups.stream().map(KpiGroup::getShopNames).collect(HashSet::new, HashSet::addAll, HashSet::addAll);
                msgBuilder.append(String.join(",", shopNames));
                msgBuilder.append("】。");
            }
        }
        KpiGroupRepeatQueryDTO beEffectRepeatDTO = KpiGroupRepeatQueryDTO.convertDto(kpiGroupDTO, SettingStatusEnum.BE_EFFECTIVE);
        List<KpiGroup> beKpiGroups = kpiGroupService.queryRepeatKpiGroup(beEffectRepeatDTO);
        if (PublicUtil.isNotEmpty(beKpiGroups)) {
            if (msgBuilder.length() == 0) {
                msgBuilder.append("审批通过后");
            }
            Map<LocalDate, List<KpiGroup>> monthKpiMap = beKpiGroups.stream().collect(Collectors.groupingBy(KpiGroup::getBeginTime));
            for (Map.Entry<LocalDate, List<KpiGroup>> monthKpi : monthKpiMap.entrySet()) {
                msgBuilder.append(monthKpi.getKey().getMonth().getValue()).append("月份待生效绩效组配置会被移除,门店【");
                HashSet<String> shopNames = monthKpi.getValue().stream().map(KpiGroup::getShopNames).collect(HashSet::new, HashSet::addAll, HashSet::addAll);
                msgBuilder.append(String.join(",", shopNames));
            }
            msgBuilder.append("】。");
        }
        if (msgBuilder.length() == 0) {
            return new KpiGroupSavePromptVO(false);
        }
        return new KpiGroupSavePromptVO(true, msgBuilder.toString());
    }

    /**
     * 检查阶梯分值
     * @param indicators
     */
    private void checkKpiLadders(List<KpiGroupIndicatorDTO> indicators) {
        Integer baseScore = null;
        List<KpiGroupIndicatorLaddersDTO> indicatorLadders = null;
        for (KpiGroupIndicatorDTO indicatorDto : indicators) {
            if (ScoreWayEnum.NORMAL.equals(indicatorDto.getScoreWay())) {
                continue;
            }
            baseScore = indicatorDto.getBaseScore();
            indicatorLadders = indicatorDto.getIndicatorLadders();
            Collections.sort(indicatorLadders);

            //阶梯值校验  标准分不能超过指标基础分,阶梯值必须连续
            for (KpiGroupIndicatorLaddersDTO laddersDtos : indicatorLadders) {
                //阶梯标准分不能超过绩效分值
                if (laddersDtos.getStandardScore().compareTo(baseScore) > 0) {
                    throw new BusinessException("【" + indicatorDto.getIndicatorName() + "】的阶梯标准分不能超过绩效分值");
                }
            }
            //校验阶梯
            CommonService.checkLadders(indicatorLadders, indicatorDto.getIndicatorName());
        }
    }

    /**
     * 检查星级阶梯分值
     * 1. 赋初始值
     * 2. 校验连续性、上限下限大小、所有星级都已经配置
     * @param laddersDTOS
     */
    private void checkStarLadders(List<KpiStarLaddersDTO> laddersDTOS, StarEvaluationEnum starEvaluationType) {
        Set<StarLevelEnum> levelEnumSet = Arrays.stream(StarLevelEnum.values()).collect(Collectors.toSet());
        Collections.sort(laddersDTOS, new Comparator<KpiStarLaddersDTO>() {
            @Override
            public int compare(KpiStarLaddersDTO o1, KpiStarLaddersDTO o2) {
                if (starEvaluationType.equals(StarEvaluationEnum.SCORING_RATE)) {
                    return o2.getLevel().getValue() - o1.getLevel().getValue();
                } else {
                    return o1.getLevel().getValue() - o2.getLevel().getValue();
                }
            }
        });
        //校验阶梯
        CommonService.checkLadders(laddersDTOS);
        //阶梯值校验  标准分不能超过指标基础分,阶梯值必须连续
        for (KpiStarLaddersDTO dto : laddersDTOS) {
            if (! levelEnumSet.remove(dto.getLevel())) {
                throw new BusinessException("【" + dto.getLevel().getName() + "】级的阶梯配置重复");
            }
        }
        if (levelEnumSet.size() != 0) {
            List<String> levels = levelEnumSet.stream().map(level -> {
                return level.getName() + "级";
            }).collect(Collectors.toList());
            throw new BusinessException("【" + String.join(",", levels) + "】阶梯未配置");
        }
    }

    /**
     * 审批kpiGroup
     * 生效时间 在 当前时间 之前,那么这个审批是无效的
     * 次月生效
     * 1. 将次月生效的重复绩效配置设置为失效,等待月定时器执行
     * 当月生效
     * 1. 将当月生效的重复绩效配置设置为失效,将之前配置设置为无效,将状态设置为生效中
     * @param approvalRecord
     * @param result
     */
    @Transactional(rollbackFor = Exception.class)
    public void approvalKpiGroup(ApprovalRecord approvalRecord, ApprovalResultEvent result) {
        log.info("收到绩效组配置变更审批信息:{}", JSON.toJSONString(approvalRecord));
        KpiGroup kpiGroup = kpiGroupService.getById(approvalRecord.getDataId());
        if (! result.getAgree()) {
            kpiGroupDataService.modifyStatusById(kpiGroup, SettingStatusEnum.INEFFECTIVE);
            return;
        }

        //通知绩效组人员
        KpiGroupChangeEvent kpiGroupChangeEvent = PublicUtil.copy(kpiGroup, KpiGroupChangeEvent.class);
        EventBusUtil.asyncPost(kpiGroupChangeEvent);

        YearMonth yearMonth = YearMonth.now();
        YearMonth beginTime = YearMonth.from(kpiGroup.getBeginTime());
        kpiGroup.getBeginTime();
        if (yearMonth.isAfter(beginTime)) {
            log.info("审批通过时间在绩效组生效时间之后,等待定时器执行");
            return;
        }

        //处理重复绩效组配置数据
        this.processRepeatKpiGroup(kpiGroup);
    }

    /**
     * 处理重复数据
     * 1. 次月之后生效,需要处理次月后重复的待生效数据
     * 2. 当月生效,   需要处理当月后重复的待生效数据,处理当前重复的生效数据
     * @param kpiGroup
     */
    public void processRepeatKpiGroup(KpiGroup kpiGroup){
        YearMonth yearMonth = YearMonth.now();
        YearMonth beginTime = YearMonth.from(kpiGroup.getBeginTime());
        //删除重复的待生效配置数据(时间在此绩效组配置之后、同岗位、同门店)
        KpiGroupRepeatQueryDTO beEffectRepeatDTO = KpiGroupRepeatQueryDTO.convertToBeEffectiveDTO(kpiGroup);
        List<KpiGroup> beKpiGroups = kpiGroupService.queryRepeatKpiGroup(beEffectRepeatDTO);
        kpiGroupDataService.delInEffective(beKpiGroups);

        SettingStatusEnum status = SettingStatusEnum.BE_EFFECTIVE;
        //当月生效,处理当前重复的生效数据
        if (yearMonth.equals(beginTime)) {
            status = SettingStatusEnum.EFFECTIVE;
            KpiGroupRepeatQueryDTO effectRepeatDTO = KpiGroupRepeatQueryDTO.convertToEffectiveDTO(kpiGroup);
            List<KpiGroup> effectKpiGroups = kpiGroupService.queryRepeatKpiGroup(effectRepeatDTO);
            kpiGroupDataService.modifyStatusByKpis(effectKpiGroups, SettingStatusEnum.INEFFECTIVE);
        }

        kpiGroupDataService.modifyStatusById(kpiGroup, status);
    }

    /**
     * 所有集团生效的绩效组配置
     */
    public Map<Long, List<KpiGroup>> postEffectKpis(){
        Date queryDate = DateUtil.localDateTime2Date(LocalDateTime.now().minusDays(1L));
        List<KpiGroup> kpiGroups = kpiGroupService.getAllEffectGroups(queryDate);
        if (PublicUtil.isEmpty(kpiGroups)) {
            log.info("时间:{},没有正在生效中的绩效组配置", new SimpleDateFormat("yyyy-MM-dd").format(queryDate));
            return Maps.newHashMap();
        }
        return kpiGroups.stream().collect(Collectors.groupingBy(KpiGroup::getPostId));
    }

}