LeaveNeedDoBizService.java
18.6 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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package cn.fw.valhalla.service.bus;
import cn.fw.common.cache.locker.DistributedLocker;
import cn.fw.common.data.mybatis.pagination.PageData;
import cn.fw.common.page.AppPage;
import cn.fw.common.web.auth.LoginAuthBean;
import cn.fw.data.base.domain.common.Message;
import cn.fw.third.push.sdk.api.ImSendMessage;
import cn.fw.third.push.sdk.api.para.im.MsgPara;
import cn.fw.valhalla.common.constant.RoleCode;
import cn.fw.valhalla.common.enums.AllocationTypeEnum;
import cn.fw.valhalla.common.utils.DateUtil;
import cn.fw.valhalla.domain.db.LeaveNeedDo;
import cn.fw.valhalla.domain.db.customer.Customer;
import cn.fw.valhalla.domain.db.follow.FollowRecord;
import cn.fw.valhalla.domain.db.follow.FollowTask;
import cn.fw.valhalla.domain.dto.LeaveAllocationDTO;
import cn.fw.valhalla.domain.enums.FollowTypeEnum;
import cn.fw.valhalla.domain.enums.LeaveReasonEnum;
import cn.fw.valhalla.domain.enums.LeaveTodoTypeEnum;
import cn.fw.valhalla.domain.enums.TaskStateEnum;
import cn.fw.valhalla.domain.query.LeaveQueryVO;
import cn.fw.valhalla.domain.vo.LeaveNeedDoVO;
import cn.fw.valhalla.rpc.erp.TodoRpcService;
import cn.fw.valhalla.rpc.erp.UserService;
import cn.fw.valhalla.rpc.erp.dto.BackLogItemDTO;
import cn.fw.valhalla.rpc.erp.dto.PostUserDTO;
import cn.fw.valhalla.rpc.erp.dto.UserInfoDTO;
import cn.fw.valhalla.rpc.erp.dto.UserRoleDataRangeDTO;
import cn.fw.valhalla.service.data.CustomerService;
import cn.fw.valhalla.service.data.FollowRecordService;
import cn.fw.valhalla.service.data.FollowTaskService;
import cn.fw.valhalla.service.data.LeaveNeedDoService;
import com.alibaba.fastjson.JSONObject;
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.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static cn.fw.common.businessvalidator.Validator.BV;
/**
* @author : kurisu
* @className : LeaveNeedDoBizService
* @description : 人员变动处理
* @date: 2020-10-16 17:04
*/
@Service
@Slf4j
public class LeaveNeedDoBizService {
private final LeaveNeedDoService leaveNeedDoService;
private final CustomerService customerService;
private final UserService userService;
private final FollowTaskService followTaskService;
private final FollowRecordService followRecordService;
private final DistributedLocker distributedLocker;
private final ImSendMessage imSendMessage;
private final TodoRpcService todoRpcService;
/**
* Redis工具
*/
private final StringRedisTemplate redisTemplate;
@Value("${spring.cache.custom.global-prefix}:LeaveNeedDo")
@Getter
private String keyPrefix;
@Value("${follow.todo.leave2do}")
@Getter
private String leave2doCode;
@Autowired
public LeaveNeedDoBizService(final LeaveNeedDoService leaveNeedDoService,
final CustomerService customerService,
final UserService userService,
final FollowTaskService followTaskService,
final FollowRecordService followRecordService,
final DistributedLocker distributedLocker,
final ImSendMessage imSendMessage,
final TodoRpcService todoRpcService,
final StringRedisTemplate redisTemplate) {
this.leaveNeedDoService = leaveNeedDoService;
this.customerService = customerService;
this.userService = userService;
this.followTaskService = followTaskService;
this.followRecordService = followRecordService;
this.distributedLocker = distributedLocker;
this.imSendMessage = imSendMessage;
this.todoRpcService = todoRpcService;
this.redisTemplate = redisTemplate;
}
@Transactional(rollbackFor = Exception.class)
public void add(final Long userId, final Long shopId) {
String lockKey = String.format("%s:add:lock:%s:%s", getKeyPrefix(), shopId, userId);
Pair<Boolean, RLock> pair = distributedLocker.tryLock(lockKey, TimeUnit.SECONDS, 0, 30);
BV.isTrue(Boolean.TRUE.equals(pair.getKey()), () -> "请勿重复提交");
try {
List<PostUserDTO> postUserDTOS = userService.getUserByRole(shopId, RoleCode.BYKFP);
BV.isFalse(CollectionUtils.isEmpty(postUserDTOS), () -> "该门店没有配置保有客分配人员");
LeaveNeedDo db = addable(userId, shopId);
leaveNeedDoService.save(db);
push2Todo(db.getId(), postUserDTOS.get(0).getUserId());
} catch (Exception e) {
distributedLocker.unlock(lockKey);
throw e;
}
}
public AppPage<LeaveNeedDoVO> getList(LoginAuthBean currentUser, LeaveQueryVO queryVO) {
List<UserRoleDataRangeDTO> dataRange = userService.getUserRoleDataRange(currentUser.getUserId(), RoleCode.BYKFP);
List<Long> shopIds = dataRange.stream().map(UserRoleDataRangeDTO::getRangeValue).collect(Collectors.toList());
BV.isFalse(CollectionUtils.isEmpty(shopIds), () -> "无权限操作,请检查角色权限是否正确");
PageData<LeaveNeedDo> pageData = leaveNeedDoService.page(new PageData<>(queryVO), Wrappers.<LeaveNeedDo>lambdaQuery()
.in(LeaveNeedDo::getShopId, shopIds)
.eq(LeaveNeedDo::getDone, Boolean.FALSE)
.eq(Objects.nonNull(queryVO.getType()), LeaveNeedDo::getType, queryVO.getType())
);
AppPage<LeaveNeedDoVO> page = AppPage.empty(queryVO);
List<LeaveNeedDoVO> list = new ArrayList<>();
List<LeaveNeedDo> records = Optional.ofNullable(pageData.getRecords()).orElse(new ArrayList<>());
for (LeaveNeedDo needDo : records) {
int i = customerService.count(Wrappers.<Customer>lambdaQuery()
.eq(Customer::getAdviserId, needDo.getUserId())
.eq(Customer::getYn, Boolean.TRUE)
);
list.add(LeaveNeedDoVO.with(needDo, i));
}
page.setData(list);
return page;
}
@Transactional(rollbackFor = Exception.class)
public void allocation(LoginAuthBean user, LeaveAllocationDTO dto) {
final String key = generateKey(dto.getId());
final String lockKey = getLockKey(dto.getId());
Pair<Boolean, RLock> pair = distributedLocker.tryLock(lockKey, TimeUnit.SECONDS, 0, 30);
BV.isTrue(Boolean.TRUE.equals(pair.getKey()), () -> "请勿重复提交");
try {
//准备分配 常规校验
prepareAllocation(dto);
//变更档案
List<Customer> customerList = doAllocation(dto, key);
//分配跟进任务
dealFollowTask(customerList);
//完成分配发送消息提醒等
finish(user.getUserName(), dto.getId(), key);
} catch (Exception e) {
clearKey(key);
distributedLocker.unlock(lockKey);
throw e;
}
}
private void prepareAllocation(LeaveAllocationDTO dto) {
AllocationTypeEnum typeEnum = AllocationTypeEnum.ofValue(dto.getAllocationType());
BV.notNull(typeEnum, () -> "分配方式不正确,请重试");
dto.setType(typeEnum);
LeaveNeedDo needDo = leaveNeedDoService.queryProcessableById(dto.getId());
BV.notNull(needDo, () -> "该条记录已处理或不存在,请刷新后重试");
dto.setAdviserId(needDo.getUserId());
if (AllocationTypeEnum.ONE.equals(typeEnum)) {
BV.notNull(dto.getUserId(), () -> "指定人员不能为空");
List<UserRoleDataRangeDTO> dataRange = userService.getUserRoleDataRange(dto.getUserId(), RoleCode.FWGW);
List<Long> shopIdList = dataRange.stream().map(UserRoleDataRangeDTO::getRangeValue).collect(Collectors.toList());
BV.isNotEmpty(shopIdList, () -> "指定人员非服务顾问角色,请核对");
Long shopId = shopIdList.get(0);
BV.isTrue(needDo.getShopId().equals(shopId), () -> "指定人员所属门店与档案归属门店不符");
dto.setShopId(shopId);
}
if (AllocationTypeEnum.ALL.equals(dto.getType())) {
dto.setShopId(needDo.getShopId());
}
}
/**
* 处理数据
*
* @param dto
* @return 处理完的档案
*/
private List<Customer> doAllocation(LeaveAllocationDTO dto, String key) {
List<Customer> customerList = customerService.queryByAdviserId(dto.getAdviserId());
if (CollectionUtils.isEmpty(customerList)) {
return null;
}
if (AllocationTypeEnum.ONE.equals(dto.getType())) {
allocation(key, customerList, dto);
}
if (AllocationTypeEnum.ALL.equals(dto.getType())) {
allocation(key, customerList, dto.getShopId());
}
return customerList;
}
/**
* 分配给指定人员
*
* @param list
* @param dto
*/
private void allocation(String key, List<Customer> list, LeaveAllocationDTO dto) {
for (Customer customer : list) {
customer.setShopId(dto.getShopId());
customer.setAdviserId(dto.getUserId());
}
customerService.updateBatchById(list);
setToCache(key, new UserInfo(dto.getUserId(), "", list.size()));
}
/**
* 门店内平均分配
*
* @param list
* @param shopId
*/
private void allocation(String key, List<Customer> list, Long shopId) {
List<PostUserDTO> users = userService.getUserByRole(shopId, RoleCode.FWGW);
BV.isNotEmpty(users, () -> "该门店没有服务顾问,请检查配置是否正确");
LinkedList<UserInfo> queue = new LinkedList<>();
for (PostUserDTO user : users) {
queue.offer(new UserInfo(user.getUserId(), user.getUserName()));
}
for (Customer customer : list) {
UserInfo info = queue.poll();
customer.setShopId(shopId);
customer.setAdviserId(Objects.requireNonNull(info, "服务顾问信息获取异常,请重试").getUserId());
info.setCount(info.getCount() + 1);
queue.offer(info);
}
customerService.updateBatchById(list);
setToCache(key, queue);
}
/**
* 完成分配的后续处理逻辑
*
* @param list
*/
private void dealFollowTask(List<Customer> list) {
List<FollowTypeEnum> enumList = Arrays.asList(FollowTypeEnum.FM, FollowTypeEnum.RM);
if (!CollectionUtils.isEmpty(list)) {
//处理待办等信息
for (Customer customer : list) {
final Long customerId = customer.getId();
final Long shopId = customer.getShopId();
final Long adviserId = customer.getAdviserId();
List<FollowTask> taskList = followTaskService.getListByCustomerId(customerId, enumList);
taskList.forEach(task -> {
task.setFollowUser(adviserId);
task.setFollowShop(shopId);
if (TaskStateEnum.WAITING.equals(task.getState())) {
task.setOriginUser(adviserId);
task.setOriginShop(shopId);
} else {
task.setChanged(Boolean.TRUE);
}
});
List<FollowRecord> recordList = followRecordService.getRecordListByCustomer(customerId, enumList);
recordList.forEach(record -> {
record.setUserId(adviserId);
record.setShopId(shopId);
});
if (taskList.size() > 0) {
followTaskService.updateBatchById(taskList);
}
if (recordList.size() > 0) {
followRecordService.updateBatchById(recordList);
}
}
}
}
private void finish(String userName, Long leaveId, String key) {
leaveNeedDoService.dealById(leaveId);
List<UserInfo> list = getAllFromCache(key);
for (UserInfo info : list) {
try {
String text = String.format("%s通过资源分配给你%s台保有客", userName, info.getCount());
final MsgPara msgPara = MsgPara.getOfflineTxetPara(text, null, "保有客分配",
"保有客分配", null, info.getUserId()).build();
final Message<Integer> msg = imSendMessage.sendMsg(msgPara);
log.info("给[{}]推送im消息结果:[{}]", info, msg.getResult());
} catch (Exception e) {
log.error("给[{}]推送im消息失败:]", info, e);
}
}
clearKey(key);
BackLogItemDTO backLogItemDTO = new BackLogItemDTO(null, getLeave2doCode(), String.valueOf(leaveId), new Date());
todoRpcService.complete(backLogItemDTO);
}
private String getLockKey(final Long leaveId) {
BV.notNull(leaveId, "leaveId cannot be null");
return String.format("%s:lock:%s", getKeyPrefix(), leaveId);
}
private String generateKey(final Long leaveId) {
Assert.notNull(leaveId, "leaveId cannot be null");
return String.format("%s:allocation:%s", getKeyPrefix(), leaveId);
}
public List<UserInfo> getAllFromCache(final String key) {
try {
Boolean hasKey = redisTemplate.hasKey(key);
if (!Boolean.TRUE.equals(hasKey)) {
return new ArrayList<>();
}
BoundListOperations<String, String> ops = redisTemplate.boundListOps(key);
List<String> stringList = ops.range(0, -1);
if (CollectionUtils.isEmpty(stringList)) {
return new ArrayList<>();
}
List<UserInfo> dtos = stringList.stream().map(str -> JSONObject.parseObject(str, UserInfo.class)).collect(Collectors.toList());
redisTemplate.delete(key);
return dtos;
} catch (Exception e) {
log.error("缓存设置信息失败 key[{}]", key, e);
return new ArrayList<>();
}
}
private void setToCache(final String key, final UserInfo userInfo) {
try {
BoundListOperations<String, String> ops = redisTemplate.boundListOps(key);
String jsonString = JSONObject.toJSONString(userInfo);
ops.rightPush(jsonString);
} catch (Exception e) {
log.error("缓存设置信息失败 key[{}]", key, e);
}
}
private void setToCache(final String key, final LinkedList<UserInfo> userInfos) {
try {
if (CollectionUtils.isEmpty(userInfos)) {
return;
}
BoundListOperations<String, String> ops = redisTemplate.boundListOps(key);
String[] users = userInfos.stream().map(JSONObject::toJSONString).toArray(String[]::new);
ops.rightPushAll(users);
} catch (Exception e) {
log.error("缓存设置信息失败 key[{}]", key, e);
}
}
private void clearKey(final String key) {
try {
redisTemplate.delete(key);
} catch (Exception e) {
log.error("清空缓存信息失败 key[{}]", key, e);
}
}
private LeaveNeedDo addable(final Long userId, final Long shopId) {
List<UserRoleDataRangeDTO> dataRange = userService.getUserRoleDataRange(userId, RoleCode.FWGW);
boolean ok = CollectionUtils.isEmpty(dataRange) || !Objects.equals(dataRange.get(0).getRangeValue(), shopId);
BV.isTrue(ok, () -> "请先移除对对应服务站服务顾问角色后操作");
int count = leaveNeedDoService.count(Wrappers.<LeaveNeedDo>lambdaQuery()
.eq(LeaveNeedDo::getUserId, userId)
.eq(LeaveNeedDo::getShopId, shopId)
.eq(LeaveNeedDo::getDone, Boolean.FALSE)
);
BV.isTrue(count == 0, () -> "已存在待分配记录,请勿重复添加");
UserInfoDTO user = userService.user(userId);
BV.notNull(user, () -> "用户不存在");
boolean bool = customerService.count(Wrappers.<Customer>lambdaQuery()
.eq(Customer::getAdviserId, userId)
.eq(Customer::getShopId, shopId)
.eq(Customer::getYn, Boolean.TRUE)
) > 0;
BV.isTrue(bool, () -> "该顾问没有可用档案无需分配保有客");
LeaveNeedDo db = new LeaveNeedDo();
db.setDone(Boolean.FALSE);
db.setEffectiveTime(DateUtil.getMonthEndDay(new Date()));
db.setReason(LeaveReasonEnum.OTHER);
db.setType(LeaveTodoTypeEnum.CUSTOMER);
db.setShopId(shopId);
db.setUserId(userId);
db.setUserName(user.getUserName());
db.setCreateTime(new Date());
db.setUpdateTime(new Date());
return db;
}
private void push2Todo(Long id, Long userId) {
BackLogItemDTO dto = new BackLogItemDTO(userId, getLeave2doCode(), String.valueOf(id), new Date());
todoRpcService.push(dto);
}
static class UserInfo {
private Long userId;
private String userName;
private int count;
public UserInfo() {
}
public UserInfo(Long userId, String userName) {
this.userId = userId;
this.userName = userName;
}
public UserInfo(Long userId, String userName, int count) {
this.userId = userId;
this.userName = userName;
this.count = count;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
return "UserInfo{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", count=" + count +
'}';
}
}
}