liujie
2026-03-20 100f2d185dd0dabcfb2e7a0cd81aef840324238d
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
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;
 
/**
 * 常规任务通知定时任务
 * <p>
 * 每天 9:00 / 12:00 / 18:00 执行,查询常规待处理任务,
 * 通知相关运维人员(handleUserId)
 * </p>
 *
 * @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<XpTask> tasks = queryPendingRoutineTasks();
            if (CollectionUtils.isEmpty(tasks)) {
                log.info("未找到待处理常规任务,跳过通知");
                return;
            }
 
            Map<Long, List<Long>> userTaskIdsMap = buildUserTaskIdsMap(tasks);
            if (userTaskIdsMap.isEmpty()) {
                log.warn("任务接收人为空,跳过通知");
                return;
            }
 
            Set<Long> allUserIds = userTaskIdsMap.keySet();
 
            Map<Long, XpOperationsUser> userMap = fetchOperationUsers(allUserIds);
            if (CollectionUtils.isEmpty(userMap)) {
                log.warn("未获取到运维人员信息,跳过通知");
                return;
            }
 
            List<XpOperationsUserNotification> notifications = new ArrayList<>();
            int pushCount = 0;
 
            for (Map.Entry<Long, List<Long>> entry : userTaskIdsMap.entrySet()) {
                Long userId = entry.getKey();
                List<Long> taskIds = entry.getValue();
                int taskCount = taskIds == null ? 0 : taskIds.size();
                if (taskCount <= 0) {
                    continue;
                }
 
                XpOperationsUser user = userMap.get(userId);
                if (user == null) {
                    continue;
                }
 
                // 只有一个待完成任务时 dataId 赋值为该任务 ID,多个则赋值为 0
                long dataId = taskCount == 1 ? taskIds.get(0) : 0L;
 
                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(dataId);
                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<XpTask> queryPendingRoutineTasks() {
        return taskMapper.selectList(new LambdaQueryWrapper<XpTask>()
                .eq(XpTask::getTaskCategory, TaskScheduleConstants.TASK_CATEGORY_ROUTINE)
                .eq(XpTask::getStatus, TaskScheduleConstants.TASK_STATUS_PENDING));
    }
 
    /**
     * 构建用户待办任务 ID 列表映射
     * key: 运维人员 ID,value: 该用户名下的待办任务 ID 列表
     */
    private Map<Long, List<Long>> buildUserTaskIdsMap(List<XpTask> tasks) {
        Map<Long, List<Long>> userTaskIdsMap = new HashMap<>();
        for (XpTask task : tasks) {
            Set<Long> userIds = parseUserIds(task.getHandleUserId());
            if (!CollectionUtils.isEmpty(userIds)) {
                for (Long userId : userIds) {
                    userTaskIdsMap.computeIfAbsent(userId, k -> new ArrayList<>()).add(task.getId());
                }
            }
        }
        return userTaskIdsMap;
    }
 
    /**
     * 获取运维人员信息
     */
    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();
        }
    }
 
    /**
     * 解析 handleUserId
     */
    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(Integer taskCount) {
        return String.format(CONTENT_TEMPLATE, String.valueOf(taskCount));
    }
 
    /**
     * 构建推送 body JSON
     */
    private String buildPushBodyJson(String content) {
        Map<String, Object> 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;
        }
    }
}