puzhibing
2026-03-11 c98d3f2fc620b3f5d699e2be34eaabc1033b42b2
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
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.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.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;
        }
    }
}