DriverServiceImpl.java
22.3 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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
package com.ruoyi.driver.service.impl;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.HttpUtil;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.cache.SchedulingCache;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.global.Result;
import com.ruoyi.common.global.ResultCode;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.equipment.mapper.EquipmentMapper;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.job.DriverJob;
import com.ruoyi.pojo.DriverSignInRecommendation;
import com.ruoyi.domain.EquipmentDriverExpand;
import com.ruoyi.domain.DriverScheduling;
import com.ruoyi.pojo.request.DriverRequestVo;
import com.ruoyi.pojo.request.DriverSignInRequestVo;
import com.ruoyi.pojo.request.FaceUpdateReqVo;
import com.ruoyi.pojo.response.DriverResponseVo;
import com.ruoyi.pojo.response.ResponseSchedulingDto;
import com.ruoyi.service.SchedulingService;
import com.ruoyi.service.ThreadJobService;
import com.ruoyi.utils.ConstDateUtil;
import com.ruoyi.utils.ListUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.tomcat.util.buf.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.driver.mapper.DriverMapper;
import com.ruoyi.driver.domain.Driver;
import com.ruoyi.driver.service.IDriverService;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static com.ruoyi.common.ApiProperties.PERSONNEL_API_KEY;
import static com.ruoyi.common.ConstDriverProperties.*;
import static com.ruoyi.common.ConstSignInConstSignInProperties.*;
import static com.ruoyi.common.redispre.GlobalRedisPreName.DRIVER_SCHEDULING_PRE;
/**
* 驾驶员信息Service业务层处理
*
* @author 古自健
* @date 2023-07-04
*/
@Service
public class DriverServiceImpl implements IDriverService {
private Logger log = LoggerFactory.getLogger(DriverServiceImpl.class);
@Value("${api.url.getSchedulingInfo}")
private String schedulingInfoUrl;
@Value("${api.config.password}")
private String password;
@Value("${api.config.nonce}")
private String nonce;
@Resource
private SchedulingCache schedulingCache;
@Resource
private SchedulingService schedulingService;
@Autowired
private EquipmentMapper equipmentMapper;
@Autowired
private DriverJob driverJob;
@Autowired
private ServerConfig serverConfig;
@Autowired
private DriverMapper driverMapper;
@Autowired
private ThreadJobService threadJobService;
@Autowired
private RedisCache redisCache;
@Value("${api.headImage}")
private String headImagePre;
/**
* 查询驾驶员信息
*
* @param id 驾驶员信息主键
* @return 驾驶员信息
*/
@Override
public Driver selectDriverById(Long id) {
return driverMapper.selectDriverById(id);
}
/**
* 查询驾驶员信息列表
*
* @param driver 驾驶员信息
* @return 驾驶员信息
*/
@Override
public List<Driver> selectDriverList(DriverRequestVo driver) {
List<Driver> drivers = driverMapper.selectDriverList(driver);
List<EquipmentDriverExpand> list = equipmentMapper.querySignListByJobCode(drivers);
for (Driver item : drivers) {
// 查询对应工号的注册设备号 然后用,拼接展示在前端
List<String> collect = list.stream().filter(todo -> item.getJobCode().equals(todo.getJobCode())).map(EquipmentDriverExpand::getDeviceId).collect(Collectors.toList());
item.setSignInEquipment(StringUtils.join(collect));
}
return drivers;
}
private DriverSignInRecommendation checkTime(List<DriverScheduling> dto, Long now) {
Map<Integer, DriverSignInRecommendation> timeMap = new HashMap<>();
for (int i = 0; i < dto.size(); i++) {
timeMap.put(i, new DriverSignInRecommendation(dto.get(i), i));
}
long minDiff = Long.MAX_VALUE;
Integer index = 0;
// 迭代比较每个时间戳与当前时间戳的差值
for (Integer i : timeMap.keySet()) {
long diff = Math.abs(now - timeMap.get(i).getTimestamps());
if (diff < minDiff) {
minDiff = diff;
index = i;
}
}
LocalDateTime nowTime = ConstDateUtil.getLocalDateTimeByLongTime(now);
LocalDateTime signTime = ConstDateUtil.getLocalDateTimeByLongTime(timeMap.get(index).getTimestamps());
long range = ChronoUnit.MINUTES.between(signTime, nowTime);
// 如果当前记录靠近签退,但是未到签退小于合法范围 上一次记录未签到,则返回签到记录
if (dto.size() > 1
&& BC_TYPE_IN.equals(timeMap.get(index).getBcType())
&& range < -60L
&& Objects.isNull(timeMap.get(index).getSignInId())
&& Objects.isNull(timeMap.get(index - 1).getSignInId())) {
// 定位上次操作
index = index - 1;
}
// 如果当前记录是异常的记录且还在目前还在签到范围内
if (!Objects.isNull(timeMap.get(index).getSignInId()) && dto.size() > 1) {
LocalDateTime endTime = ConstDateUtil.getLocalDateTimeByLongTime(timeMap.get(index).getTimestamps());
long nowBetween = ChronoUnit.MINUTES.between(endTime, nowTime);
// 如果当前有效范围内签到记录无效如酒精测试异常则重复当前操作
if ((Math.abs(nowBetween) <= 60) && timeMap.get(index).getExType().equals(SIGN_ALCOHOL_EX_NUM) && timeMap.get(index).getBcType().equals(BC_TYPE_OUT)) {
return timeMap.get(index);
} else {
index = index < timeMap.size() - 1 ? index + 1 : index;
}
}
return timeMap.get(index);
}
/**
* 新增驾驶员信息
*
* @param driver 驾驶员信息
* @return 结果
*/
@Override
public int insertDriver(Driver driver) {
driver.setUpdateTime(new Date());
return driverMapper.insertDriver(driver);
}
/**
* 修改驾驶员信息
*
* @param driver 驾驶员信息
* @return 结果
*/
@Override
public int updateDriver(Driver driver) {
driver.setUpdateTime(new Date());
return driverMapper.updateDriver(driver);
}
/**
* 批量删除驾驶员信息
*
* @param ids 需要删除的驾驶员信息主键
* @return 结果
*/
@Override
public int deleteDriverByIds(Long[] ids) {
return driverMapper.deleteDriverByIds(ids);
}
/**
* 删除驾驶员信息信息
*
* @param id 驾驶员信息主键
* @return 结果
*/
@Override
public int deleteDriverById(Long id) {
return driverMapper.deleteDriverById(id);
}
@Override
public void insertDrivers(List<Driver> driverList) {
driverMapper.saveDrivers(driverList);
}
@Override
public AjaxResult getDriverSchedulingInfo(String schedulingDate, String jobCode) {
String key = DRIVER_SCHEDULING_PRE + schedulingDate;
long now = System.currentTimeMillis();
List<ResponseSchedulingDto> cacheMapValue = schedulingCache.getCacheSchedulingMapValueByHKey(key, jobCode);
// 获取考勤表进行比对,因为排班数据是会变化的
List<DriverScheduling> dto = schedulingService.queryScheduling(jobCode, now);
log.info("获取到排班数据:{}", cacheMapValue);
if (jobCode.equals("700001")){
return AjaxResult.success("");
}
// 优先从缓存中读取
if (!CollectionUtil.isEmpty(cacheMapValue) && !CollectionUtil.isEmpty(dto)) {
return AjaxResult.success(cacheMapValue);
}
// 获取昨天的排班数据
String yesterdayKey = DRIVER_SCHEDULING_PRE + ConstDateUtil.formatDate(ConstDateUtil.getTheSpecifiedNumberOfDaysOfTime(-1));
cacheMapValue = schedulingCache.getCacheSchedulingMapValueByHKey(yesterdayKey, jobCode);
if (!CollectionUtil.isEmpty(cacheMapValue) && !CollectionUtil.isEmpty(dto)) {
LocalDateTime zdsjT = ConstDateUtil.getLocalDateTimeByLongTime(cacheMapValue.get(cacheMapValue.size() - 1).getZdsjT());
LocalDateTime nowTime = ConstDateUtil.getLocalDateTimeByLongTime(now);
long range = ChronoUnit.MINUTES.between(zdsjT, nowTime);
if (range <= 0L) {
return AjaxResult.success(cacheMapValue);
} else if (range <= 120L) {
return AjaxResult.success();
}
}
return AjaxResult.success();
}
@Override
public AjaxResult getDriverSchedulingAll() {
// return AjaxResult.success(redisCache.getHashKeys(DRIVER_SCHEDULING_PRE + ConstDateUtil.formatDate("yyyyMMdd")));
return AjaxResult.success(schedulingCache.getHKeysByKey(DRIVER_SCHEDULING_PRE + ConstDateUtil.formatDate("yyyyMMdd")));
}
@Override
public AjaxResult checkJobCode(Driver driver) {
Integer result = driverMapper.jobCodeIsEmpty(driver.getJobCode());
Map<String, Boolean> resultMap = new HashMap<>();
if (result > 0) {
resultMap.put("result", true);
} else {
resultMap.put("result", false);
}
return AjaxResult.success(resultMap);
}
@Override
public AjaxResult uploadImage(MultipartFile file) throws InvalidExtensionException, IOException {
// 上传并返回新文件名称
// 上传文件路径
String baseUrl = RuoYiConfig.getUploadPath() + headImagePre;
// 校验文件格式
FileUploadUtils.assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
// 后期可以通过请求头拿到对应的工号
String fileName = FilenameUtils.getBaseName(file.getOriginalFilename()) + "." + FileUploadUtils.getExtension(file);
String absPath = FileUploadUtils.getAbsoluteFile(baseUrl, fileName).getAbsolutePath();
fileName = FileUploadUtils.getPathFileName(baseUrl, fileName);
file.transferTo(Paths.get(absPath));
String url = serverConfig.getUrl() + fileName;
AjaxResult ajax = AjaxResult.success();
ajax.put("url", url);
ajax.put("fileName", fileName);
ajax.put("newFileName", FileUtils.getName(fileName));
ajax.put("originalFilename", file.getOriginalFilename());
return ajax;
}
@Override
public void downloadHeadImage(String jobCode, HttpServletResponse response) {
File file = getLocationFile(jobCode);
ServletOutputStream ops = null;
try {
if (file.exists()) {
byte[] bytes = com.alibaba.excel.util.FileUtils.readFileToByteArray(file);
ops = response.getOutputStream();
ops.write(bytes);
ops.flush();
}
} catch (Exception e) {
throw new RuntimeException("download fail cause:" + e.getMessage());
} finally {
try {
if (ops != null) {
ops.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
@Override
public List<DriverResponseVo> getDrivers(DriverRequestVo driver) {
List<Driver> drivers = driverMapper.getDrivers(driver);
Long now = System.currentTimeMillis();
List<DriverResponseVo> vos = new ArrayList<>(drivers.size());
List<DriverScheduling> dto = null;
Boolean schedulingFlag = true;
Boolean alcoholFlag = true;
boolean needCheckAlcoholDevice = doCheckDevice(driver.getDeviceId());
// 更新信息
for (Driver item : drivers) {
dto = schedulingService.queryScheduling(item.getJobCode(), now);
DriverResponseVo vo = handlerRecommendation(item, now, dto, schedulingFlag, alcoholFlag);
// 针对指定用户操作
if ( item.getJobCode().equals("722717") || item.getJobCode().equals("700001")) {
if (!CollectionUtil.isEmpty(dto) && vo.getPlanAction().equals(SIGN_IN_STRING) ){
vos.add(DriverResponseVo.createDriverResponseVo(null, item, SIGN_IN_STRING, needCheckAlcoholDevice, true, "测试", "测试", "测试"));
}else if (!CollectionUtil.isEmpty(dto)){
vos.add(vo);
}else {
vos.add(DriverResponseVo.createDriverResponseVo(null, item, SIGN_IN_STRING, needCheckAlcoholDevice, true, "测试", "测试", "测试"));
}
}else {
// 无排班
if (Objects.isNull(vo)) {
vos.add(DriverResponseVo.createDriverResponseVo(null, item, null, false, false, "", "", ""));
} else {
// 特定设备是无需酒精测试的
vo.setCheckAlcohol(needCheckAlcoholDevice ? vo.getCheckAlcohol() : false);
vos.add(vo);
}
}
}
return vos;
}
private boolean doCheckDevice(String deviceId) {
if (StringUtil.isEmpty(deviceId)){
return true;
}
switch (deviceId){
case "001":
case "002":
case "003":
case "004":
case "005":
case "006":
case "007":
case "008":
case "009":
case "010":
case "011":
case "012":
return true;
}
return false;
}
private DriverResponseVo handlerRecommendation(Driver driver, Long now, List<DriverScheduling> dto, Boolean schedulingFlag, Boolean alcoholFlag) {
DriverResponseVo vo = null;
// 给出计划操作
if (!CollectionUtil.isEmpty(dto)) {
DriverSignInRecommendation recommendation = checkTime(dto, now);
if (BC_TYPE_OUT.equals(recommendation.getBcType())) {
// 售票员无需酒精测试
if (recommendation.getPosts().equals(PERSONNEL_POSTS_DRIVER))
vo = DriverResponseVo.createDriverResponseVo(recommendation.getTimestamps(), driver, SIGN_IN_STRING, alcoholFlag, schedulingFlag, recommendation.getNbbm(), recommendation.getLpName(), recommendation.getLineName());
else
vo = DriverResponseVo.createDriverResponseVo(recommendation.getTimestamps(), driver, SIGN_IN_STRING, !alcoholFlag, schedulingFlag, recommendation.getNbbm(), recommendation.getLpName(), recommendation.getLineName());
} else if (BC_TYPE_IN.equals(recommendation.getBcType())) {
vo = DriverResponseVo.createDriverResponseVo(recommendation.getTimestamps(), driver, SIGN_IN_OUT_STRING, !alcoholFlag, schedulingFlag, recommendation.getNbbm(), recommendation.getLpName(), recommendation.getLineName());
}
}
return vo;
}
@Override
public AjaxResult faceRegistrationFeedback(String deviceId, List<String> jobCodes) {
threadJobService.asyncInsertSignInContactEquipment(deviceId, jobCodes);
return AjaxResult.success("注册成功");
}
@Override
public void updateDriverByComputed() {
Integer count = equipmentMapper.count();
// 更新人脸认证状态
driverMapper.updateDriverByComputed(count);
}
@Override
public Result<?> updateFaceByJob(HttpServletRequest request, FaceUpdateReqVo vo) {
log.info("接收到人事数据:{}", vo);
// 获取校验
String header = request.getHeader("X-TOKEN-AUTHORIZATION");
if (!PERSONNEL_API_KEY.equals(header)) {
return Result.ERROR(ResultCode.CODE_401, "X-TOKEN-AUTHORIZATION value error");
}
Date date = new Date();
// 查询当前人员信息库是否存在对应员工数据
List<String> jobCodes = vo.getFaceDataList().stream().map(FaceUpdateReqVo.FaceData::getJobCode).collect(Collectors.toList());
Map<String, String> existsSet = driverMapper.queryJobCodesIsExists(jobCodes).stream().collect(Collectors.toMap(item -> item, s -> s));
jobCodes = new ArrayList<>(existsSet.values());
List<Driver> updateDrivers = getDriversByJobCode(vo, date, existsSet, true);
List<Driver> insertDrivers = getDriversByJobCode(vo, date, existsSet, false);
List<List<Driver>> lists = ListUtils.splitList(updateDrivers, 400);
log.info("开始人脸数据更新");
// 数据更新 更新人脸注册标识 更新基本数据
for (List<Driver> list : lists) {
driverMapper.updateSignStatusDriversByJobCodes(list);
}
if (insertDrivers.size() > 0) driverMapper.saveDrivers(insertDrivers);
log.info("人脸数据更新完成");
log.info("开始删除注册表中对应工号的数据");
if (jobCodes.size() > 0)
driverMapper.deleteDeviceIdAssociatedJobCode(jobCodes);
log.info("删除注册表中对应工号的数据结束");
return Result.OK();
}
private ArrayList<Driver> getDriversByJobCode(FaceUpdateReqVo vo, Date date, Map<String, String> existsSet, Boolean updateFlag) {
if (updateFlag)
return vo.getFaceDataList().stream().map(item -> {
Driver driver = new Driver();
driver.setPosts(item.getPosts());
driver.setJobCode(item.getJobCode());
driver.setFleetName(item.getFleetName());
driver.setLineName(item.getLineName());
try {
driver.setImage(getNewImageUrl(item.getJobCode(), item.getImageUrl()));
} catch (IOException e) {
log.error(e.getMessage());
throw new RuntimeException(e);
}
driver.setPersonnelName(item.getName());
driver.setUpdateTime(date);
return driver;
}).filter(item -> !Objects.isNull(existsSet.get(item.getJobCode()))).collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(s -> s.getJobCode()))), ArrayList::new));
else
return vo.getFaceDataList().stream().map(item -> {
Driver driver = new Driver();
driver.setPosts(item.getPosts());
driver.setJobCode(item.getJobCode());
driver.setFleetName(item.getFleetName());
driver.setLineName(item.getLineName());
driver.setFaceSignIn(SIGN_FACE_ACTIVE);
try {
driver.setImage(getNewImageUrl(item.getJobCode(), item.getImageUrl()));
} catch (IOException e) {
log.error(e.getMessage());
throw new RuntimeException(e);
}
driver.setPersonnelName(item.getName());
driver.setUpdateTime(date);
return driver;
}).filter(item -> Objects.isNull(existsSet.get(item.getJobCode()))).collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(s -> s.getJobCode()))), ArrayList::new));
}
@Override
public void updateDriverSignInfo(DriverSignInRequestVo vo) {
log.info("开始进行人员数据更新");
Driver driver = new Driver();
driver.setJobCode(vo.getJobCode());
driver.setPersonnelName(vo.getName());
driver.setPosts(vo.getPosts());
String base64 = vo.getImage();
String fileName = vo.getJobCode() + ".png";
String filePath = new File(RuoYiConfig.getUploadPath() + headImagePre + "/" + fileName + File.separator).getAbsolutePath();
try {
fileName = FileUploadUtils.getPathFileName(RuoYiConfig.getUploadPath() + headImagePre, fileName);
} catch (IOException e) {
throw new RuntimeException(e);
}
driver.setImage(fileName);
driver.setUpdateTime(new Date());
driverMapper.updateSignStatusDriversByJobCodes(new ArrayList<>(Arrays.asList(driver)));
driverMapper.deleteDeviceIdAssociatedJobCode(new ArrayList<>(Arrays.asList(driver.getJobCode())));
log.info("进行人员数据更新完毕");
log.info("开始上传人脸图片");
// 异步上传文件
threadJobService.asyncStartUploadBase64Image(filePath, base64);
}
@Override
public void updateDrivers(List<Driver> drivers) {
driverMapper.updateDriverInfoByJobCodes(drivers);
}
@Override
public void deleteNotEmptyJob(List<String> jobList) {
driverMapper.deleteNotEmptyJob(jobList);
}
/**
* 获取新的imageUrl
*
* @param jobCode
* @param url
* @return
*/
private String getNewImageUrl(String jobCode, String url) throws IOException {
// 生成文件路径
String fileName = jobCode + ".png";
String filePath = RuoYiConfig.getUploadPath() + headImagePre + "/" + fileName;
try {
fileName = FileUploadUtils.getPathFileName(RuoYiConfig.getUploadPath() + headImagePre, fileName);
} catch (IOException e) {
throw new RuntimeException(e);
}
log.info("图片开始上传");
// 获取图片数据
InputStream is = HttpUtil.createGet(url).execute().bodyStream();
// 上传图片
ThreadJobService.uploadImage(is, filePath);
log.info("图片上传完毕");
return fileName;
}
private File getLocationFile(String jobCode) {
String image = driverMapper.getDriverImageByJobCode(jobCode);
return new File(RuoYiConfig.getProfile() + File.separator + image.replace("/profile", ""));
}
}