package com.xiaopeng.maintenance.schedule; import com.alibaba.fastjson2.JSONObject; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; 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.utils.StringUtils; import com.xiaopeng.api.vo.maintenance.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.util.*; import java.util.stream.Collectors; /** * 常规任务通知定时任务 *

* 每天 9:00 / 12:00 / 18:00 执行,查询常规待处理任务, * 通知相关运维人员(handleUserId) *

* * @author mitao * @since 2026-03-02 */ @Component public class RoutineTaskNotificationScheduleTask { private static final Logger log = LoggerFactory.getLogger(RoutineTaskNotificationScheduleTask.class); /** * 任务名称 */ private static final String TASK_NAME = "常规任务通知定时任务"; /** * 推送标题 */ private static final String PUSH_TITLE = "待完成日常任务提示"; /** * 通知内容模板 */ private static final String CONTENT_TEMPLATE = "你目前剩余%s条待办任务,请及时处理!"; @Autowired private XpTaskMapper taskMapper; @Autowired private XpOperationUserClient xpOperationUserClient; @Autowired private XpOperationUserNotificationClient xpOperationUserNotificationClient; @Autowired private XpAliPushMessageClient xpAliPushMessageClient; /** * 每天 9:00 / 12:00 / 18:00 执行 */ @Scheduled(cron = "0 0 9,12,18 * * ?") public void executeRoutineTaskNotification() { log.info("========== 开始执行{} ==========", TASK_NAME); try { List tasks = queryPendingRoutineTasks(); if (CollectionUtils.isEmpty(tasks)) { log.info("未找到待处理常规任务,跳过通知"); return; } Map userTaskCountMap = buildUserTaskCountMap(tasks); if (userTaskCountMap.isEmpty()) { log.warn("任务接收人为空,跳过通知"); return; } Set allUserIds = userTaskCountMap.keySet(); Map userMap = fetchOperationUsers(allUserIds); if (CollectionUtils.isEmpty(userMap)) { log.warn("未获取到运维人员信息,跳过通知"); return; } List notifications = new ArrayList<>(); int pushCount = 0; for (Map.Entry entry : userTaskCountMap.entrySet()) { Long userId = entry.getKey(); Integer taskCount = entry.getValue(); if (taskCount == null || taskCount <= 0) { continue; } XpOperationsUser user = userMap.get(userId); if (user == null) { continue; } String content = buildContent(taskCount); String bodyJson = buildPushBodyJson(content); XpOperationsUserNotification notification = new XpOperationsUserNotification(); notification.setNotificationType(NotificationTypeEnum.TASK_NEW.getCode()); notification.setNotificationContent(content); notification.setOperationsUserId(userId); notification.setDataId(0L); notification.setReadStatus(0); notification.setNotificationExt(bodyJson); notifications.add(notification); if (pushTaskNotification(user, bodyJson)) { pushCount++; } } if (!CollectionUtils.isEmpty(notifications)) { xpOperationUserNotificationClient.addNotificationBatch(notifications); log.info("常规任务通知记录保存成功,共 {} 条", notifications.size()); } log.info("========== {} 执行完成,推送次数: {} ==========", TASK_NAME, pushCount); } catch (Exception e) { log.error("{}执行失败", TASK_NAME, e); } } /** * 查询待处理常规任务 */ private List queryPendingRoutineTasks() { return taskMapper.selectList(new LambdaQueryWrapper() .eq(XpTask::getTaskCategory, TaskScheduleConstants.TASK_CATEGORY_ROUTINE) .eq(XpTask::getStatus, TaskScheduleConstants.TASK_STATUS_PENDING)); } /** * 构建用户待办数量映射 */ private Map buildUserTaskCountMap(List tasks) { Map userTaskCountMap = new HashMap<>(); for (XpTask task : tasks) { Set userIds = parseUserIds(task.getHandleUserId()); if (!CollectionUtils.isEmpty(userIds)) { for (Long userId : userIds) { userTaskCountMap.put(userId, userTaskCountMap.getOrDefault(userId, 0) + 1); } } } return userTaskCountMap; } /** * 获取运维人员信息 */ private Map fetchOperationUsers(Set userIds) { if (CollectionUtils.isEmpty(userIds)) { return Collections.emptyMap(); } try { R> 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(); } } /** * 解析 handleUserId */ private Set parseUserIds(String handleUserId) { if (StringUtils.isBlank(handleUserId)) { return Collections.emptySet(); } String[] parts = handleUserId.split(","); Set 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(Integer taskCount) { return String.format(CONTENT_TEMPLATE, String.valueOf(taskCount)); } /** * 构建推送 body JSON */ private String buildPushBodyJson(String content) { Map param = new HashMap<>(); param.put("content", content); param.put("strategy", NotificationTypeEnum.TASK_NEW.getCode()); param.put("type", 0); param.put("id", 0); return JSONObject.toJSONString(param); } /** * 推送任务提醒 */ private boolean pushTaskNotification(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; } } }