Blame view

fw-morax-service/src/main/java/cn/fw/morax/service/biz/kpi/KpiPoolCommonService.java 16 KB
742b79d4   姜超   feature(calculato...
1
2
  package cn.fw.morax.service.biz.kpi;
  
4811c3f9   张志伟   :zap:
3
4
  import cn.fw.common.cache.CacheExtender;
  import cn.fw.common.cache.locker.DistributedLocker;
4811c3f9   张志伟   :zap:
5
  import cn.fw.morax.common.utils.MessageFormatUtil;
742b79d4   姜超   feature(calculato...
6
  import cn.fw.morax.common.utils.PublicUtil;
ff72c844   张志伟   :zap:
7
  import cn.fw.morax.domain.db.UserResignExamine;
742b79d4   姜超   feature(calculato...
8
9
  import cn.fw.morax.domain.db.kpi.KpiGroupUser;
  import cn.fw.morax.domain.db.kpi.KpiPool;
4811c3f9   张志伟   :zap:
10
  import cn.fw.morax.domain.db.kpi.KpiStarRule;
742b79d4   姜超   feature(calculato...
11
12
  import cn.fw.morax.domain.db.salary.SalaryGroupUser;
  import cn.fw.morax.domain.db.salary.SalaryPool;
b365d22a   姜超   feature(*): 申述日期修...
13
  import cn.fw.morax.domain.db.salary.SalaryClosure;
ff72c844   张志伟   :zap:
14
  import cn.fw.morax.domain.enums.ResignExamineStatusEnum;
742b79d4   姜超   feature(calculato...
15
  import cn.fw.morax.domain.enums.StarLevelEnum;
b365d22a   姜超   feature(*): 申述日期修...
16
  import cn.fw.morax.service.biz.salary.SalarySettingCommonService;
4811c3f9   张志伟   :zap:
17
  import cn.fw.morax.service.data.UserResignExamineService;
742b79d4   姜超   feature(calculato...
18
  import cn.fw.morax.service.data.kpi.KpiPoolService;
4811c3f9   张志伟   :zap:
19
20
  import cn.fw.morax.service.data.kpi.KpiStarRuleService;
  import cn.fw.morax.service.data.salary.SalaryGeneralSettinService;
742b79d4   姜超   feature(calculato...
21
22
  import com.alibaba.fastjson.JSON;
  import com.baomidou.mybatisplus.core.toolkit.Wrappers;
ff72c844   张志伟   :zap:
23
  import lombok.Getter;
4811c3f9   张志伟   :zap:
24
  import lombok.RequiredArgsConstructor;
742b79d4   姜超   feature(calculato...
25
  import lombok.extern.slf4j.Slf4j;
4811c3f9   张志伟   :zap:
26
  import org.redisson.api.RLock;
ff72c844   张志伟   :zap:
27
  import org.springframework.beans.factory.annotation.Value;
742b79d4   姜超   feature(calculato...
28
29
  import org.springframework.stereotype.Service;
  import org.springframework.transaction.annotation.Transactional;
4811c3f9   张志伟   :zap:
30
  import org.springframework.util.CollectionUtils;
742b79d4   姜超   feature(calculato...
31
32
  
  import java.math.BigDecimal;
707b76c5   姜超   feature(*): 申述日期修...
33
  import java.time.LocalDate;
b365d22a   姜超   feature(*): 申述日期修...
34
  import java.time.LocalDateTime;
742b79d4   姜超   feature(calculato...
35
  import java.time.YearMonth;
4811c3f9   张志伟   :zap:
36
  import java.util.List;
742b79d4   姜超   feature(calculato...
37
  import java.util.Objects;
4811c3f9   张志伟   :zap:
38
39
  import java.util.Optional;
  import java.util.concurrent.locks.Lock;
ff72c844   张志伟   :zap:
40
  import java.util.stream.Collectors;
4811c3f9   张志伟   :zap:
41
42
  
  import static cn.fw.common.businessvalidator.Validator.BV;
742b79d4   姜超   feature(calculato...
43
  
742b79d4   姜超   feature(calculato...
44
45
46
47
48
49
50
51
52
  /**
   * @author : kurisu
   * @version : 1.0
   * @className : KpiPoolCommonService
   * @description : 绩效池公用方法
   * @date : 2022-09-27 11:40
   */
  @Slf4j
  @Service
4811c3f9   张志伟   :zap:
53
  @RequiredArgsConstructor
742b79d4   姜超   feature(calculato...
54
55
  public class KpiPoolCommonService {
  
ff72c844   张志伟   :zap:
56
      public static final CacheKeyFunction<YearMonth, Long, String> KPI_GROUP_AVERAGE_RATIO_CACHE_NAME = (month, groupId) -> String.format("kpi-group:average-ratio:%s:%s", month.toString(), groupId);
4811c3f9   张志伟   :zap:
57
58
59
60
61
62
      private final KpiPoolService kpiPoolService;
      private final DistributedLocker distributedLocker;
      private final SalaryGeneralSettinService salaryGeneralSettinService;
      private final UserResignExamineService userResignExamineService;
      private final KpiStarRuleService kpiStarRuleService;
      private final CacheExtender cacheExtender;
b365d22a   姜超   feature(*): 申述日期修...
63
      private final SalarySettingCommonService salarySettingCommonService;
742b79d4   姜超   feature(calculato...
64
  
ff72c844   张志伟   :zap:
65
66
67
68
      @Value("${spring.cache.custom.global-prefix}:forced:resign")
      @Getter
      private String forcedResignLockKey;
  
742b79d4   姜超   feature(calculato...
69
70
71
72
73
74
      /**
       * 查询绩效池
       *
       * @param user
       * @return
       */
54f68ff0   姜超   feature(*): 计算薪酬修改
75
      public Optional<KpiPool> queryPool(SalaryGroupUser user) {
742b79d4   姜超   feature(calculato...
76
77
78
79
80
81
82
83
84
          KpiPool kpiPool = kpiPoolService.getOne(Wrappers.<KpiPool>lambdaQuery()
                          .eq(KpiPool::getUserId, user.getUserId())
                          .eq(KpiPool::getPostId, user.getPostId())
                          .eq(KpiPool::getShopId, user.getShopId())
                          .eq(KpiPool::getMonthly, YearMonth.from(user.getDataDate()))
                          .eq(KpiPool::getYn, Boolean.TRUE)
                  , Boolean.FALSE);
          if (PublicUtil.isEmpty(kpiPool)) {
              log.error("绩效数据不存在,用户:{}", JSON.toJSONString(user));
54f68ff0   姜超   feature(*): 计算薪酬修改
85
  //            throw new BusinessException("用户[" + user.getUserId() + "]的绩效数据不存在");
742b79d4   姜超   feature(calculato...
86
          }
54f68ff0   姜超   feature(*): 计算薪酬修改
87
          return Optional.ofNullable(kpiPool);
742b79d4   姜超   feature(calculato...
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
      }
  
      /**
       * 查询绩效池
       *
       * @param pool
       * @return
       */
      public KpiPool queryPool(SalaryPool pool) {
          KpiPool kpiPool = kpiPoolService.getOne(Wrappers.<KpiPool>lambdaQuery()
                          .eq(KpiPool::getUserId, pool.getUserId())
                          .eq(KpiPool::getPostId, pool.getPostId())
                          .eq(KpiPool::getShopId, pool.getShopId())
                          .eq(KpiPool::getMonthly, pool.getMonthly())
                          .eq(KpiPool::getYn, Boolean.TRUE)
                  , Boolean.FALSE);
          if (PublicUtil.isEmpty(kpiPool)) {
              log.error("绩效数据不存在,薪酬池:{}", JSON.toJSONString(pool));
8c9ef818   姜超   feature(*): 查询员工星级修改
106
  //            throw new BusinessException("用户[" + pool.getUserId() + "]的绩效数据不存在");
742b79d4   姜超   feature(calculato...
107
108
109
110
111
112
113
114
115
116
117
118
          }
          return kpiPool;
      }
  
      /**
       * 查询绩效池(上报绩效、计算绩效得分用)
       *
       * @param user
       * @return
       */
      public KpiPool inspectionPool(KpiGroupUser user) {
          KpiPool kpiPool = kpiPoolService.getOne(Wrappers.<KpiPool>lambdaQuery()
a92022b7   姜超   feature(*): 绩效不再使...
119
                          .eq(KpiPool::getKpiGroupId, user.getKpiGroupId())
742b79d4   姜超   feature(calculato...
120
121
                          .eq(KpiPool::getUserId, user.getUserId())
                          .eq(KpiPool::getMonthly, YearMonth.from(user.getDataDate()))
b21841e7   jiangchao   fix(bug): 查询绩效池加上...
122
                          .eq(KpiPool::getYn, Boolean.TRUE)
742b79d4   姜超   feature(calculato...
123
124
125
126
127
128
129
130
                  , Boolean.FALSE);
  
          if (Objects.isNull(kpiPool)) {
              kpiPool = kpiPoolService.getOne(Wrappers.<KpiPool>lambdaQuery()
                              .eq(KpiPool::getPostId, user.getPostId())
                              .eq(KpiPool::getShopId, user.getShopId())
                              .eq(KpiPool::getUserId, user.getUserId())
                              .eq(KpiPool::getMonthly, YearMonth.from(user.getDataDate()))
b21841e7   jiangchao   fix(bug): 查询绩效池加上...
131
                              .eq(KpiPool::getYn, Boolean.TRUE)
742b79d4   姜超   feature(calculato...
132
133
134
135
136
137
138
                      , Boolean.FALSE);
  
              if (Objects.isNull(kpiPool)) {
                  kpiPool = createPoolData(user);
              } else {
                  kpiPool = this.modifyPoolData(kpiPool, user);
              }
5c309793   张志伟   feature(*): 实现计算器
139
140
          } else if ((!kpiPool.getShopId().equals(user.getShopId())) ||
                  (!kpiPool.getKpiGroupId().equals(user.getKpiGroupId()))) {
742b79d4   姜超   feature(calculato...
141
142
143
144
145
146
147
              //若门店信息与员工在职门店不匹配,说明员工是调门店,绩效组没变
              //若绩效组id不匹配,说明绩效组编辑生成了新绩效组,对应绩效池中的绩效组id修改
              kpiPool = this.modifyPoolData(kpiPool, user);
          }
          return kpiPool;
      }
  
4811c3f9   张志伟   :zap:
148
149
150
151
152
153
154
155
156
157
158
159
      /**
       * 固定绩效数据
       *
       * @param groupId
       */
      public void regularKpiStar(Long groupId) {
          String key = String.format("%s:%s", ":regular:kpi-start:group:", groupId);
          Lock lock = distributedLocker.lock(key);
          if (!((RLock) lock).isLocked()) {
              return;
          }
          try {
707b76c5   姜超   feature(*): 申述日期修...
160
              LocalDate current = LocalDate.now();
b365d22a   姜超   feature(*): 申述日期修...
161
162
163
164
165
166
167
              List<SalaryClosure> salaryClosures = salarySettingCommonService.queryNoClosureKpis(groupId);
              for (SalaryClosure salaryClosure : salaryClosures) {
                  //当前时间在申述时间之后
                  if (current.compareTo(salaryClosure.getAppealEndTime()) > 0) {
                      regularStarAndExamineUser(groupId, YearMonth.now().minusMonths(1L));
                      salarySettingCommonService.updateClosureKpi(salaryClosure);
                  }
4811c3f9   张志伟   :zap:
168
              }
4811c3f9   张志伟   :zap:
169
170
171
172
173
          } finally {
              lock.unlock();
          }
      }
  
742b79d4   姜超   feature(calculato...
174
      @Transactional(rollbackFor = Exception.class)
ff72c844   张志伟   :zap:
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
      public void forcedResign() {
          Lock lock = distributedLocker.lock(getForcedResignLockKey());
          if (!((RLock) lock).isLocked()) {
              return;
          }
          try {
              List<UserResignExamine> list = userResignExamineService.list(Wrappers.<UserResignExamine>lambdaQuery()
                      .eq(UserResignExamine::getStatus, ResignExamineStatusEnum.WAITING)
              );
              if (CollectionUtils.isEmpty(list)) {
                  return;
              }
              for (UserResignExamine examine : list) {
                  examine.setStatus(ResignExamineStatusEnum.COMPLETE);
                  // todo 对接人事员工离职接口
              }
              userResignExamineService.updateBatchById(list);
          } finally {
              lock.unlock();
          }
      }
  
      @Transactional(rollbackFor = Exception.class)
742b79d4   姜超   feature(calculato...
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
      public KpiPool modifyPoolData(KpiPool pool, KpiGroupUser user) {
          pool.setKpiGroupId(user.getKpiGroupId());
          pool.setShopId(user.getShopId());
          pool.setShopName(user.getShopName());
          pool.setKgc(user.getKgc());
          kpiPoolService.updateById(pool);
          return pool;
      }
  
      @Transactional(rollbackFor = Exception.class)
      public KpiPool createPoolData(KpiGroupUser groupUser) {
          KpiPool pool = new KpiPool();
          pool.setKpiGroupId(groupUser.getKpiGroupId());
          pool.setKgc(groupUser.getKgc());
          pool.setUserId(groupUser.getUserId());
          pool.setUserName(groupUser.getUserName());
          pool.setPostId(groupUser.getPostId());
          pool.setPostName(groupUser.getPostName());
          pool.setShopId(groupUser.getShopId());
          pool.setShopName(groupUser.getShopName());
          pool.setStarLevel(StarLevelEnum.C);
          pool.setActualStar(StarLevelEnum.C);
          pool.setRevoked(Boolean.FALSE);
          pool.setInclusion(!Boolean.TRUE.equals(groupUser.getIgnored()));
          pool.setRegular(Boolean.FALSE);
742b79d4   姜超   feature(calculato...
223
224
225
226
227
          pool.setMonthly(YearMonth.from(groupUser.getDataDate()));
          pool.setGroupId(groupUser.getGroupId());
          pool.setYn(Boolean.TRUE);
          pool.setKpiScore(BigDecimal.ZERO);
          pool.setKpiScoreRatio(BigDecimal.ZERO);
4da58065   姜超   fix(kpipool): 平均得...
228
          pool.setAverageKpiScoreRatio(BigDecimal.ZERO);
742b79d4   姜超   feature(calculato...
229
230
231
232
          kpiPoolService.save(pool);
          return pool;
      }
  
4811c3f9   张志伟   :zap:
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
      /**
       * 固定星级
       *
       * @param groupId
       * @param yearMonth
       */
      @Transactional(rollbackFor = Exception.class)
      public void regularStarAndExamineUser(Long groupId, YearMonth yearMonth) {
          List<KpiPool> list = kpiPoolService.list(Wrappers.<KpiPool>lambdaQuery()
                  .eq(KpiPool::getGroupId, groupId)
                  .eq(KpiPool::getMonthly, yearMonth)
                  .eq(KpiPool::getYn, Boolean.TRUE)
                  .ne(KpiPool::getRegular, Boolean.TRUE)
                  .last(" limit 2000 ")
          );
          if (CollectionUtils.isEmpty(list)) {
              return;
          }
          final KpiStarRule starRule = kpiStarRuleService.getOne(Wrappers.<KpiStarRule>lambdaQuery()
                          .eq(KpiStarRule::getGroupId, groupId)
                          .eq(KpiStarRule::getYn, Boolean.TRUE)
                  , Boolean.FALSE);
          BV.notNull(starRule, () -> MessageFormatUtil.MessageFormatTransfer("集团[{0}]为配置星级规则", groupId));
ff72c844   张志伟   :zap:
256
          String cacheName = KPI_GROUP_AVERAGE_RATIO_CACHE_NAME.apply(yearMonth, groupId);
4811c3f9   张志伟   :zap:
257
258
259
          for (KpiPool kpiPool : list) {
              kpiPool.setRegular(Boolean.TRUE);
              examineUser(kpiPool, starRule);
ff72c844   张志伟   :zap:
260
              cacheExtender.evictCache(cacheName, kpiPool.getKpiGroupId());
4811c3f9   张志伟   :zap:
261
262
263
264
265
          }
          kpiPoolService.updateBatchById(list);
      }
  
      /**
ff72c844   张志伟   :zap:
266
       * 校验用户是否触发离职
4811c3f9   张志伟   :zap:
267
268
269
270
271
272
273
274
275
276
       *
       * @param kpiPool
       * @param starRule
       */
      private void examineUser(KpiPool kpiPool, KpiStarRule starRule) {
          if (!Boolean.TRUE.equals(kpiPool.getInclusion())) {
              return;
          }
          int maxUnqualifiedTimes = Optional.ofNullable(starRule.getMaxUnqualifiedTimes()).orElse(12);
          int forcedTurnoverCycle = Optional.ofNullable(starRule.getForcedTurnoverCycle()).orElse(3);
4811c3f9   张志伟   :zap:
277
          Long userId = kpiPool.getUserId();
4811c3f9   张志伟   :zap:
278
279
280
          List<KpiPool> list = kpiPoolService.list(Wrappers.<KpiPool>lambdaQuery()
                  .eq(KpiPool::getGroupId, kpiPool.getGroupId())
                  .eq(KpiPool::getUserId, userId)
4811c3f9   张志伟   :zap:
281
282
283
                  .eq(KpiPool::getInclusion, Boolean.TRUE)
                  .eq(KpiPool::getYn, Boolean.TRUE)
                  .eq(KpiPool::getRegular, Boolean.TRUE)
ff72c844   张志伟   :zap:
284
285
                  .lt(KpiPool::getMonthly, kpiPool.getMonthly())
                  .orderByDesc(KpiPool::getMonthly)
4811c3f9   张志伟   :zap:
286
287
                  .last(" limit " + (maxUnqualifiedTimes - 1))
          );
ff72c844   张志伟   :zap:
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
          if (CollectionUtils.isEmpty(list)) {
              return;
          }
          list.add(kpiPool);
          revokedKpiTimes(list, starRule);
          forcedTurnover(list, forcedTurnoverCycle);
      }
  
  
      /**
       * 减少D级判断
       *
       * @param list
       * @param starRule
       */
      private void revokedKpiTimes(List<KpiPool> list, KpiStarRule starRule) {
          int continuousMonthly = Optional.ofNullable(starRule.getContinuousMonthly()).orElse(2);
          BigDecimal minScoreRatio = Optional.ofNullable(starRule.getMinScoreRatio()).orElse(BigDecimal.valueOf(0.5));
          if (list.size() == 0 || list.size() < continuousMonthly) {
              return;
          }
          KpiPool current = list.get(list.size() - 1);
          if (Objects.isNull(current)) {
              return;
          }
          BigDecimal averageRatio = kpiGroupAverageRatio(current.getKpiGroupId(), current.getMonthly(), current.getGroupId());
          if (BigDecimal.ZERO.compareTo(averageRatio) >= 0) {
              return;
          }
          BigDecimal kpiScoreRatio = current.getKpiScoreRatio();
          if (averageRatio.compareTo(kpiScoreRatio) >= 0) {
              return;
          }
          boolean revokeAble = Boolean.TRUE;
          for (int i = 1; i <= continuousMonthly; i++) {
              KpiPool pool = list.get(list.size() - i);
              BigDecimal scoreRatio = pool.getKpiScoreRatio();
              revokeAble = revokeAble && minScoreRatio.compareTo(scoreRatio) < 0;
          }
          if (!revokeAble) {
              return;
          }
          for (KpiPool pool : list) {
              if (StarLevelEnum.D.equals(pool.getActualStar()) && !Boolean.TRUE.equals(pool.getRevoked())) {
                  pool.setRevoked(Boolean.TRUE);
                  kpiPoolService.updateById(pool);
                  break;
              }
          }
      }
  
      /**
       * 强制离职判断
       *
       * @param list
       * @param forcedTurnoverCycle
       */
      private void forcedTurnover(List<KpiPool> list, int forcedTurnoverCycle) {
          if (CollectionUtils.isEmpty(list)) {
              return;
          }
          int count = (int) list.stream()
                  .filter(r -> StarLevelEnum.D.equals(r.getActualStar()))
                  .filter(p -> !Boolean.TRUE.equals(p.getRevoked()))
                  .count();
          if (forcedTurnoverCycle > count) {
              return;
          }
          KpiPool pool = list.get(list.size() - 1);
          UserResignExamine examine = new UserResignExamine();
          examine.setUserId(pool.getUserId());
          examine.setUserName(pool.getUserName());
          examine.setShopId(pool.getShopId());
          examine.setMonthly(pool.getMonthly());
  //      examine.setStatus(ResignExamineStatusEnum.IGNORE); fixme 等稳定了使用这行代码
          examine.setStatus(ResignExamineStatusEnum.IGNORE);
          userResignExamineService.save(examine);
4811c3f9   张志伟   :zap:
365
366
367
368
369
370
371
      }
  
      /**
       * calculate kpi group's specified month average score ratio
       *
       * @param kpiGroupId
       * @param yearMonth
ff72c844   张志伟   :zap:
372
       * @param groupId
4811c3f9   张志伟   :zap:
373
374
       * @return average score ratio
       */
ff72c844   张志伟   :zap:
375
376
377
      private BigDecimal kpiGroupAverageRatio(Long kpiGroupId, YearMonth yearMonth, Long groupId) {
          String cacheName = KPI_GROUP_AVERAGE_RATIO_CACHE_NAME.apply(yearMonth, groupId);
          BigDecimal averageRatio = cacheExtender.getCache(cacheName, kpiGroupId, BigDecimal.class);
4811c3f9   张志伟   :zap:
378
379
380
          if (Objects.nonNull(averageRatio)) {
              return averageRatio;
          }
ff72c844   张志伟   :zap:
381
382
383
384
385
386
          List<KpiPool> list = kpiPoolService.list(Wrappers.<KpiPool>lambdaQuery()
                  .eq(KpiPool::getGroupId, groupId)
                  .eq(KpiPool::getKpiGroupId, kpiGroupId)
                  .eq(KpiPool::getInclusion, Boolean.TRUE)
                  .eq(KpiPool::getYn, Boolean.TRUE)
                  .eq(KpiPool::getMonthly, yearMonth)
4811c3f9   张志伟   :zap:
387
          );
ff72c844   张志伟   :zap:
388
389
          if (CollectionUtils.isEmpty(list)) {
              return BigDecimal.ZERO;
4811c3f9   张志伟   :zap:
390
          }
ff72c844   张志伟   :zap:
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
          Double averaging = list.stream().map(KpiPool::getKpiScoreRatio).filter(Objects::nonNull).collect(Collectors.averagingDouble(BigDecimal::doubleValue));
          averageRatio = BigDecimal.valueOf(averaging);
          cacheExtender.putCache(cacheName, kpiGroupId, averageRatio);
          return averageRatio;
      }
  
      @FunctionalInterface
      interface CacheKeyFunction<T, U, R> {
  
          /**
           * Applies this function to the given arguments.
           *
           * @param t the function argument1
           * @param u the function argument2
           * @return the function result
           */
          R apply(T t, U u);
4811c3f9   张志伟   :zap:
408
      }
742b79d4   姜超   feature(calculato...
409
  }