package com.xiaopeng.maintenance.schedule;
|
|
import com.alibaba.fastjson2.JSONObject;
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
import com.xiaopeng.api.dto.pushMessage.AliPushMessageDTO;
|
import com.xiaopeng.api.feignClient.account.XpOperationUserClient;
|
import com.xiaopeng.api.feignClient.account.XpOperationUserNotificationClient;
|
import com.xiaopeng.api.feignClient.pushMessage.XpAliPushMessageClient;
|
import com.xiaopeng.api.model.account.XpOperationsUser;
|
import com.xiaopeng.api.model.account.XpOperationsUserNotification;
|
import com.xiaopeng.api.model.maintenance.XpTask;
|
import com.xiaopeng.common.core.constant.AliPushTypeConstant;
|
import com.xiaopeng.common.core.domain.R;
|
import com.xiaopeng.common.core.enums.NotificationTypeEnum;
|
import com.xiaopeng.common.core.enums.TaskTypeEnum;
|
import com.xiaopeng.common.core.utils.StringUtils;
|
import com.xiaopeng.maintenance.constant.TaskScheduleConstants;
|
import com.xiaopeng.maintenance.mapper.XpTaskMapper;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.scheduling.annotation.Scheduled;
|
import org.springframework.stereotype.Component;
|
import org.springframework.util.CollectionUtils;
|
|
import java.time.LocalDateTime;
|
import java.util.ArrayList;
|
import java.util.Collections;
|
import java.util.HashMap;
|
import java.util.HashSet;
|
import java.util.List;
|
import java.util.Map;
|
import java.util.Objects;
|
import java.util.Set;
|
import java.util.stream.Collectors;
|
|
/**
|
* 常规任务过期检查定时任务
|
*
|
* @author mitao
|
* @since 2026-03-02
|
*/
|
@Component
|
public class RoutineTaskExpireCheckScheduleTask {
|
|
private static final Logger log = LoggerFactory.getLogger(RoutineTaskExpireCheckScheduleTask.class);
|
|
private static final String TASK_NAME = "常规任务过期检查定时任务";
|
|
private static final String PUSH_TITLE = "日常任务过期提示";
|
|
private static final String CONTENT_TEMPLATE = "你有一条%s任务已超过3天未处理,系统已按过期处理;";
|
|
@Autowired
|
private XpTaskMapper taskMapper;
|
|
@Autowired
|
private XpOperationUserClient xpOperationUserClient;
|
|
@Autowired
|
private XpOperationUserNotificationClient xpOperationUserNotificationClient;
|
|
@Autowired
|
private XpAliPushMessageClient xpAliPushMessageClient;
|
|
/**
|
* 每分钟执行一次
|
*/
|
@Scheduled(cron = "0 * * * * ?")
|
public void executeRoutineTaskExpireCheck() {
|
log.info("========== 开始执行{} ==========", TASK_NAME);
|
try {
|
List<XpTask> tasks = queryExpiredRoutineTasks();
|
if (CollectionUtils.isEmpty(tasks)) {
|
log.info("未找到超过3天未处理的常规任务,跳过执行");
|
return;
|
}
|
|
Map<Long, Set<Long>> taskUserIdsMap = buildTaskUserIdsMap(tasks);
|
if (taskUserIdsMap.isEmpty()) {
|
log.warn("过期任务未配置有效处理人,跳过执行");
|
return;
|
}
|
|
Set<Long> allUserIds = taskUserIdsMap.values().stream()
|
.flatMap(Set::stream)
|
.collect(Collectors.toSet());
|
Map<Long, XpOperationsUser> userMap = fetchOperationUsers(allUserIds);
|
if (CollectionUtils.isEmpty(userMap)) {
|
log.warn("未获取到运维人员信息,跳过执行");
|
return;
|
}
|
|
int notifiedTaskCount = 0;
|
int notificationCount = 0;
|
int pushCount = 0;
|
|
for (XpTask task : tasks) {
|
try {
|
Set<Long> userIds = taskUserIdsMap.get(task.getId());
|
if (CollectionUtils.isEmpty(userIds)) {
|
continue;
|
}
|
|
List<XpOperationsUser> validUsers = userIds.stream()
|
.map(userMap::get)
|
.filter(Objects::nonNull)
|
.collect(Collectors.toList());
|
if (CollectionUtils.isEmpty(validUsers)) {
|
log.warn("任务ID={} 未匹配到有效运维人员,跳过通知", task.getId());
|
continue;
|
}
|
|
int affectedRows = markExpiredNoticeSent(task.getId());
|
if (affectedRows <= 0) {
|
continue;
|
}
|
|
String content = buildContent(task.getTaskTypeId());
|
String bodyJson = buildPushBodyJson(content, task);
|
|
List<XpOperationsUserNotification> notifications = new ArrayList<>();
|
for (XpOperationsUser user : validUsers) {
|
XpOperationsUserNotification notification = new XpOperationsUserNotification();
|
notification.setNotificationType(NotificationTypeEnum.TASK_EXPIRED.getCode());
|
notification.setNotificationContent(content);
|
notification.setOperationsUserId(user.getId());
|
notification.setDataId(task.getId());
|
notification.setReadStatus(0);
|
notification.setNotificationExt(bodyJson);
|
notifications.add(notification);
|
|
if (pushTaskExpiredNotification(user, bodyJson)) {
|
pushCount++;
|
}
|
}
|
|
if (!CollectionUtils.isEmpty(notifications)) {
|
xpOperationUserNotificationClient.addNotificationBatch(notifications);
|
notificationCount += notifications.size();
|
}
|
|
notifiedTaskCount++;
|
} catch (Exception e) {
|
log.error("处理过期任务通知失败,任务ID={}", task.getId(), e);
|
}
|
}
|
|
log.info("========== {} 执行完成,任务数: {},通知记录数: {},推送次数: {} ==========",
|
TASK_NAME, notifiedTaskCount, notificationCount, pushCount);
|
} catch (Exception e) {
|
log.error("{}执行失败", TASK_NAME, e);
|
}
|
}
|
|
private List<XpTask> queryExpiredRoutineTasks() {
|
return taskMapper.selectList(new LambdaQueryWrapper<XpTask>()
|
.eq(XpTask::getTaskCategory, TaskScheduleConstants.TASK_CATEGORY_ROUTINE)
|
.eq(XpTask::getStatus, TaskScheduleConstants.TASK_STATUS_PENDING)
|
.lt(XpTask::getEndTime, LocalDateTime.now())
|
.eq(XpTask::getExpiredNoticeSent, TaskScheduleConstants.TASK_EXPIRED_NOTICE_NOT_SENT));
|
}
|
|
private int markExpiredNoticeSent(Long taskId) {
|
return taskMapper.update(null, new LambdaUpdateWrapper<XpTask>()
|
.set(XpTask::getExpiredNoticeSent, TaskScheduleConstants.TASK_EXPIRED_NOTICE_SENT)
|
.eq(XpTask::getId, taskId)
|
.eq(XpTask::getTaskCategory, TaskScheduleConstants.TASK_CATEGORY_ROUTINE)
|
.eq(XpTask::getStatus, TaskScheduleConstants.TASK_STATUS_PENDING)
|
.lt(XpTask::getEndTime, LocalDateTime.now())
|
.eq(XpTask::getExpiredNoticeSent, TaskScheduleConstants.TASK_EXPIRED_NOTICE_NOT_SENT));
|
}
|
|
private Map<Long, Set<Long>> buildTaskUserIdsMap(List<XpTask> tasks) {
|
Map<Long, Set<Long>> taskUserIdsMap = new HashMap<>();
|
for (XpTask task : tasks) {
|
if (task == null || task.getId() == null) {
|
continue;
|
}
|
Set<Long> userIds = parseUserIds(task.getHandleUserId());
|
if (!CollectionUtils.isEmpty(userIds)) {
|
taskUserIdsMap.put(task.getId(), userIds);
|
}
|
}
|
return taskUserIdsMap;
|
}
|
|
private Map<Long, XpOperationsUser> fetchOperationUsers(Set<Long> userIds) {
|
if (CollectionUtils.isEmpty(userIds)) {
|
return Collections.emptyMap();
|
}
|
try {
|
R<List<XpOperationsUser>> result = xpOperationUserClient.listByIds(new ArrayList<>(userIds));
|
if (result == null || CollectionUtils.isEmpty(result.getData())) {
|
return Collections.emptyMap();
|
}
|
return result.getData().stream()
|
.collect(Collectors.toMap(XpOperationsUser::getId, user -> user, (a, b) -> a));
|
} catch (Exception e) {
|
log.error("获取运维人员信息失败", e);
|
return Collections.emptyMap();
|
}
|
}
|
|
private Set<Long> parseUserIds(String handleUserId) {
|
if (StringUtils.isBlank(handleUserId)) {
|
return Collections.emptySet();
|
}
|
String[] parts = handleUserId.split(",");
|
Set<Long> userIds = new HashSet<>();
|
for (String part : parts) {
|
if (StringUtils.isBlank(part)) {
|
continue;
|
}
|
try {
|
userIds.add(Long.valueOf(part.trim()));
|
} catch (NumberFormatException e) {
|
log.warn("任务接收人ID非法,handleUserId={}", handleUserId);
|
}
|
}
|
return userIds;
|
}
|
|
private String buildContent(String taskTypeId) {
|
String taskTypeName = resolveTaskTypeName(taskTypeId);
|
return String.format(CONTENT_TEMPLATE, taskTypeName);
|
}
|
|
private String resolveTaskTypeName(String taskTypeId) {
|
Integer taskTypeCode = parseTaskTypeCode(taskTypeId);
|
if (taskTypeCode == null) {
|
return "常规";
|
}
|
String taskTypeName = TaskTypeEnum.getEnumDescByCode(taskTypeCode);
|
return StringUtils.isBlank(taskTypeName) ? "常规" : taskTypeName;
|
}
|
|
private Integer parseTaskTypeCode(String taskTypeId) {
|
if (StringUtils.isBlank(taskTypeId)) {
|
return null;
|
}
|
try {
|
return Integer.valueOf(taskTypeId.trim());
|
} catch (NumberFormatException e) {
|
return null;
|
}
|
}
|
|
private String buildPushBodyJson(String content, XpTask task) {
|
Map<String, Object> param = new HashMap<>();
|
Integer taskTypeCode = parseTaskTypeCode(task.getTaskTypeId());
|
param.put("content", content);
|
param.put("strategy", NotificationTypeEnum.TASK_EXPIRED.getCode());
|
param.put("type", taskTypeCode == null ? 0 : taskTypeCode);
|
param.put("id", task.getId() == null ? "0" : task.getId().toString());
|
return JSONObject.toJSONString(param);
|
}
|
|
private boolean pushTaskExpiredNotification(XpOperationsUser user, String bodyJson) {
|
if (user.getDeviceType() == null || StringUtils.isBlank(user.getPhoneNumber())) {
|
return false;
|
}
|
AliPushMessageDTO pushDTO = AliPushMessageDTO.builder()
|
.deviceType(user.getDeviceType())
|
.account(user.getPhoneNumber())
|
.title(PUSH_TITLE)
|
.body(bodyJson)
|
.pushType(AliPushTypeConstant.MESSAGE)
|
.build();
|
try {
|
xpAliPushMessageClient.pushMessage(pushDTO);
|
return true;
|
} catch (Exception e) {
|
log.error("过期任务推送失败,运维用户ID={}", user.getId(), e);
|
return false;
|
}
|
}
|
}
|