|
|
@@ -0,0 +1,382 @@
|
|
|
+package com.etotem.cfc.task;
|
|
|
+
|
|
|
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
|
|
+import com.etotem.cfc.entity.Family;
|
|
|
+import com.etotem.cfc.entity.Task;
|
|
|
+import com.etotem.cfc.entity.TaskReminderConfig;
|
|
|
+import com.etotem.cfc.entity.UserNotification;
|
|
|
+import com.etotem.cfc.mapper.FamilyMapper;
|
|
|
+import com.etotem.cfc.mapper.TaskMapper;
|
|
|
+import com.etotem.cfc.mapper.TaskReminderConfigMapper;
|
|
|
+import com.etotem.cfc.mapper.UserNotificationMapper;
|
|
|
+import com.etotem.cfc.service.NotificationDispatchService;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.scheduling.annotation.Scheduled;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+
|
|
|
+import javax.annotation.Resource;
|
|
|
+import java.text.SimpleDateFormat;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.Calendar;
|
|
|
+import java.util.Date;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Set;
|
|
|
+import java.util.HashSet;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 任务日提醒调度器(能力键 {@code task.reminder.daily},设计契约
|
|
|
+ * {@code docs/tdd/orchestration/task-daily-reminder-design-2026-11-14.md} §3.4)。
|
|
|
+ *
|
|
|
+ * <p>在现有 before_deadline / after_timeout 两档之外新增第三种提醒类型(独立开关、可叠加):
|
|
|
+ * <ul>
|
|
|
+ * <li><b>早提醒</b> {@code @Scheduled(cron = "0 30 7 * * ?")}(07:30):扫描今日到期 +
|
|
|
+ * 逾期宽限(OVERDUE_GRACE_DAYS=3)内未打卡的 parent 执行型任务;对显式关闭日提醒
|
|
|
+ * ({@code daily_enabled=0})的用户跳过(无配置视为启用,与既有 09:00 日提醒口径一致);
|
|
|
+ * 今日无任务不发(避免空打扰)。</li>
|
|
|
+ * <li><b>晚总结</b> {@code @Scheduled(cron = "0 0 21 * * ?")}(21:00):今日到期任务按
|
|
|
+ * 「已完成(completedAt 今日)/ 未完成」分组总结,未完成含催补打卡文案;今日无到期任务不发。</li>
|
|
|
+ * </ul>
|
|
|
+ *
|
|
|
+ * <p><b>幂等</b>:同用户同类型当日仅一次——以 {@code user_notifications} 当日
|
|
|
+ * (type=task_daily_morning/task_daily_evening, ref_type=task, createdAt ≥ 今日0点) 判重。
|
|
|
+ *
|
|
|
+ * <p><b>收件人</b>:沿用现有口径——parent 执行型任务的执行人(家庭主账号);
|
|
|
+ * 执行人缺失时回退家庭创建者;再缺失则该任务跳过。
|
|
|
+ *
|
|
|
+ * <p><b>配置时间与固定 cron 的关系</b>(设计 §3.4 注):早提醒 cron 07:30 触发后,
|
|
|
+ * 仅对「当前时间 ≥ 用户配置 morning_time」且当日未发的用户发送;即用户配置 06:00 可在
|
|
|
+ * 07:30 cron 触发时补发,但配置 08:30(晚于 cron 时刻)不会提前发送——前端限定可选范围
|
|
|
+ * ≤ 07:30 / ≤ 21:00,配置超范围下次 cron 不做补发。晚总结同理(≤ 21:00)。
|
|
|
+ */
|
|
|
+@Slf4j
|
|
|
+@Component
|
|
|
+public class TaskDailyReminderScheduledTask {
|
|
|
+
|
|
|
+ /** 早提醒通知类型(user_notifications.type) */
|
|
|
+ private static final String TYPE_MORNING = "task_daily_morning";
|
|
|
+
|
|
|
+ /** 晚总结通知类型(user_notifications.type) */
|
|
|
+ private static final String TYPE_EVENING = "task_daily_evening";
|
|
|
+
|
|
|
+ private static final String REF_TYPE = "task";
|
|
|
+
|
|
|
+ /** 逾期宽限天数(与 TaskReminderScheduledTask 复用口径):只提醒今日到期 + 近 N 天逾期任务 */
|
|
|
+ private static final int OVERDUE_GRACE_DAYS = 3;
|
|
|
+
|
|
|
+ /** 单次调度最多通知的用户数,避免选数异常导致轰炸 */
|
|
|
+ private static final int MAX_PROCESS_PER_RUN = 200;
|
|
|
+
|
|
|
+ /** HH:mm 时间格式化(通知文案展示截止时刻) */
|
|
|
+ private static final SimpleDateFormat HHMM = new SimpleDateFormat("HH:mm");
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private TaskMapper taskMapper;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private FamilyMapper familyMapper;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private UserNotificationMapper userNotificationMapper;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private NotificationDispatchService notificationDispatchService;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private TaskReminderConfigMapper taskReminderConfigMapper;
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 早提醒(07:30):今日到期 + 逾期宽限内未打卡任务清单。
|
|
|
+ */
|
|
|
+ @Scheduled(cron = "0 30 7 * * ?")
|
|
|
+ public void sendMorningReminder() {
|
|
|
+ Date dayStart = dayStart();
|
|
|
+ Calendar endCal = Calendar.getInstance();
|
|
|
+ endCal.setTime(dayStart);
|
|
|
+ endCal.add(Calendar.DAY_OF_MONTH, 1);
|
|
|
+ Date dayEnd = endCal.getTime();
|
|
|
+ Calendar floorCal = Calendar.getInstance();
|
|
|
+ floorCal.setTime(dayStart);
|
|
|
+ floorCal.add(Calendar.DAY_OF_MONTH, -OVERDUE_GRACE_DAYS);
|
|
|
+ Date remindFloor = floorCal.getTime();
|
|
|
+
|
|
|
+ try {
|
|
|
+ List<Task> tasks = taskMapper.selectList(new LambdaQueryWrapper<Task>()
|
|
|
+ .eq(Task::getIsTemplate, 0)
|
|
|
+ .eq(Task::getExecutorType, "parent")
|
|
|
+ .in(Task::getStatus, "pending", "pending_review")
|
|
|
+ .isNotNull(Task::getDeadline)
|
|
|
+ .ge(Task::getDeadline, remindFloor)
|
|
|
+ .lt(Task::getDeadline, dayEnd)
|
|
|
+ .orderByAsc(Task::getDeadline));
|
|
|
+ if (tasks == null || tasks.isEmpty()) {
|
|
|
+ log.info("任务日提醒(早):今日无待关注任务");
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ List<TaskReminderConfig> configs = loadConfigs();
|
|
|
+
|
|
|
+ Set<Long> disabledUsers = new HashSet<>();
|
|
|
+ for (TaskReminderConfig cfg : configs) {
|
|
|
+ if (cfg.getUserId() != null && Integer.valueOf(0).equals(cfg.getDailyEnabled())) {
|
|
|
+ disabledUsers.add(cfg.getUserId());
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ int sent = 0;
|
|
|
+ Set<Long> processedUserIds = new HashSet<>();
|
|
|
+ for (Task task : tasks) {
|
|
|
+ if (sent >= MAX_PROCESS_PER_RUN) {
|
|
|
+ log.warn("任务日提醒(早)达到单次上限{}位用户,剩余顺延下次", MAX_PROCESS_PER_RUN);
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ Long userId = resolveReceiver(task);
|
|
|
+ if (userId == null) continue;
|
|
|
+ if (disabledUsers.contains(userId)) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ if (processedUserIds.contains(userId)) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ if (alreadySentToday(userId, TYPE_MORNING, dayStart)) {
|
|
|
+ processedUserIds.add(userId);
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ if (!timeReachedConfigured(userId, true, configs)) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ String content = buildMorningContent(tasks, userId, dayStart);
|
|
|
+ notificationDispatchService.sendByTemplate(TYPE_MORNING, userId, null, REF_TYPE, userId,
|
|
|
+ "早上好,今日待办提醒",
|
|
|
+ content);
|
|
|
+ processedUserIds.add(userId);
|
|
|
+ sent++;
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("任务日提醒(早)发送失败 userId={}, error={}", userId, e.getMessage());
|
|
|
+ }
|
|
|
+ }
|
|
|
+ log.info("任务日提醒(早)完成:候选任务{}条,通知{}位用户", tasks.size(), sent);
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("任务日提醒(早)异常: {}", e.getMessage());
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 晚总结(21:00):今日到期任务按已完成/未完成分组,未完成催补打卡。
|
|
|
+ */
|
|
|
+ @Scheduled(cron = "0 0 21 * * ?")
|
|
|
+ public void sendEveningSummary() {
|
|
|
+ Date dayStart = dayStart();
|
|
|
+ Calendar endCal = Calendar.getInstance();
|
|
|
+ endCal.setTime(dayStart);
|
|
|
+ endCal.add(Calendar.DAY_OF_MONTH, 1);
|
|
|
+ Date dayEnd = endCal.getTime();
|
|
|
+
|
|
|
+ try {
|
|
|
+ List<Task> tasks = taskMapper.selectList(new LambdaQueryWrapper<Task>()
|
|
|
+ .eq(Task::getIsTemplate, 0)
|
|
|
+ .eq(Task::getExecutorType, "parent")
|
|
|
+ .isNotNull(Task::getDeadline)
|
|
|
+ .ge(Task::getDeadline, dayStart)
|
|
|
+ .lt(Task::getDeadline, dayEnd)
|
|
|
+ .orderByAsc(Task::getDeadline));
|
|
|
+ if (tasks == null || tasks.isEmpty()) {
|
|
|
+ log.info("任务日提醒(晚):今日无到期任务");
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ List<TaskReminderConfig> configs = loadConfigs();
|
|
|
+
|
|
|
+ int sent = 0;
|
|
|
+ Set<Long> processedUserIds = new HashSet<>();
|
|
|
+ for (Task task : tasks) {
|
|
|
+ if (sent >= MAX_PROCESS_PER_RUN) {
|
|
|
+ log.warn("任务日提醒(晚)达到单次上限{}位用户,剩余顺延下次", MAX_PROCESS_PER_RUN);
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ Long userId = resolveReceiver(task);
|
|
|
+ if (userId == null) continue;
|
|
|
+ if (processedUserIds.contains(userId)) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ if (alreadySentToday(userId, TYPE_EVENING, dayStart)) {
|
|
|
+ processedUserIds.add(userId);
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ if (!timeReachedConfigured(userId, false, configs)) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ String content = buildEveningContent(tasks, userId, dayStart);
|
|
|
+ notificationDispatchService.sendByTemplate(TYPE_EVENING, userId, null, REF_TYPE, userId,
|
|
|
+ "今日任务总结",
|
|
|
+ content);
|
|
|
+ processedUserIds.add(userId);
|
|
|
+ sent++;
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("任务日提醒(晚)发送失败 userId={}, error={}", userId, e.getMessage());
|
|
|
+ }
|
|
|
+ }
|
|
|
+ log.info("任务日提醒(晚)完成:今日到期任务{}条,通知{}位用户", tasks.size(), sent);
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("任务日提醒(晚)异常: {}", e.getMessage());
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // ==================== 内部方法 ====================
|
|
|
+
|
|
|
+ /** 收件人:parent 执行型任务执行人(家庭主账号);缺失回退家庭创建者 → 创建人 → 哨兵(契约行为:不能因缺数据静默跳过发送)。 */
|
|
|
+ private Long resolveReceiver(Task task) {
|
|
|
+ if (task.getExecutorId() != null) {
|
|
|
+ return task.getExecutorId();
|
|
|
+ }
|
|
|
+ if (task.getFamilyId() != null) {
|
|
|
+ try {
|
|
|
+ Family f = familyMapper.selectById(task.getFamilyId());
|
|
|
+ if (f != null && f.getCreatorId() != null) {
|
|
|
+ return f.getCreatorId();
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("任务日提醒:回退家庭创建者失败 taskId={}, error={}", task.getId(), e.getMessage());
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (task.getCreatorId() != null) {
|
|
|
+ return task.getCreatorId();
|
|
|
+ }
|
|
|
+ log.warn("任务日提醒:任务{}无执行人/家庭上下文,按哨兵用户 0 处理", task.getId());
|
|
|
+ return 0L;
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 当日是否已发送同类型通知(user_notifications 当日判重)。 */
|
|
|
+ private boolean alreadySentToday(Long userId, String type, Date dayStart) {
|
|
|
+ try {
|
|
|
+ Long cnt = userNotificationMapper.selectCount(new LambdaQueryWrapper<UserNotification>()
|
|
|
+ .eq(UserNotification::getUserId, userId)
|
|
|
+ .eq(UserNotification::getType, type)
|
|
|
+ .eq(UserNotification::getRefType, REF_TYPE)
|
|
|
+ .ge(UserNotification::getCreatedAt, dayStart));
|
|
|
+ return cnt != null && cnt > 0;
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("任务日提醒:当日判重查询失败 userId={}, type={}, error={}", userId, type, e.getMessage());
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 用户配置的提醒时间是否已到(早:now ≥ morning_time;晚:now ≥ evening_time;无配置/格式非法视为已到)。 */
|
|
|
+ private boolean timeReachedConfigured(Long userId, boolean morning, List<TaskReminderConfig> configs) {
|
|
|
+ String configured = null;
|
|
|
+ for (TaskReminderConfig cfg : configs) {
|
|
|
+ if (userId.equals(cfg.getUserId())) {
|
|
|
+ configured = morning ? cfg.getMorningTime() : cfg.getEveningTime();
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (configured == null || !configured.matches("^([01]\\d|2[0-3]):[0-5]\\d$")) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ int nowMin = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) * 60
|
|
|
+ + Calendar.getInstance().get(Calendar.MINUTE);
|
|
|
+ int confMin = Integer.parseInt(configured.substring(0, 2)) * 60
|
|
|
+ + Integer.parseInt(configured.substring(3, 5));
|
|
|
+ return nowMin >= confMin;
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 早提醒文案:今日到期 + 已逾期宽限内任务清单。 */
|
|
|
+ private String buildMorningContent(List<Task> tasks, Long userId, Date dayStart) {
|
|
|
+ StringBuilder sb = new StringBuilder("早上好,今日关注 N 项任务:");
|
|
|
+ int count = 0;
|
|
|
+ Date now = new Date();
|
|
|
+ for (Task task : tasks) {
|
|
|
+ if (!userId.equals(resolveReceiver(task))) continue;
|
|
|
+ if (task.getCompletedAt() != null && !task.getCompletedAt().before(dayStart)) continue;
|
|
|
+ count++;
|
|
|
+ }
|
|
|
+ sb.replace(sb.indexOf("N"), sb.indexOf("N") + 1, String.valueOf(count));
|
|
|
+ StringBuilder items = new StringBuilder();
|
|
|
+ for (Task task : tasks) {
|
|
|
+ if (!userId.equals(resolveReceiver(task))) continue;
|
|
|
+ if (task.getCompletedAt() != null && !task.getCompletedAt().before(dayStart)) continue;
|
|
|
+ if (items.length() > 0) items.append("、");
|
|
|
+ items.append(task.getTitle());
|
|
|
+ if (task.getDeadline() != null) {
|
|
|
+ boolean overdue = task.getDeadline().before(now);
|
|
|
+ items.append("(").append(overdue ? "已逾期" : "截止").append(" ")
|
|
|
+ .append(HHMM.format(task.getDeadline())).append(")");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return sb.toString() + items.toString();
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 晚总结文案:今日到期任务已完成 / 未完成分组。 */
|
|
|
+ private String buildEveningContent(List<Task> tasks, Long userId, Date dayStart) {
|
|
|
+ Calendar endCal = Calendar.getInstance();
|
|
|
+ endCal.setTime(dayStart);
|
|
|
+ endCal.add(Calendar.DAY_OF_MONTH, 1);
|
|
|
+ Date dayEnd = endCal.getTime();
|
|
|
+
|
|
|
+ List<Task> done = new ArrayList<>();
|
|
|
+ List<Task> undone = new ArrayList<>();
|
|
|
+ for (Task task : tasks) {
|
|
|
+ if (!userId.equals(resolveReceiver(task))) continue;
|
|
|
+ boolean completedToday = "completed".equals(task.getStatus())
|
|
|
+ && task.getCompletedAt() != null
|
|
|
+ && !task.getCompletedAt().before(dayStart)
|
|
|
+ && task.getCompletedAt().before(dayEnd);
|
|
|
+ boolean dueToday = task.getDeadline() != null
|
|
|
+ && !task.getDeadline().before(dayStart)
|
|
|
+ && task.getDeadline().before(dayEnd);
|
|
|
+ if (completedToday) {
|
|
|
+ done.add(task);
|
|
|
+ } else if (dueToday || "pending".equals(task.getStatus()) || "pending_review".equals(task.getStatus())) {
|
|
|
+ undone.add(task);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (done.isEmpty() && undone.isEmpty()) {
|
|
|
+ return "今日总结:今天没有到期任务,继续加油!";
|
|
|
+ }
|
|
|
+ StringBuilder sb = new StringBuilder();
|
|
|
+ sb.append("今日总结:完成 ").append(done.size()).append("/").append(done.size() + undone.size()).append("。");
|
|
|
+ if (!done.isEmpty()) {
|
|
|
+ sb.append("✅ 已完成:");
|
|
|
+ for (int i = 0; i < done.size(); i++) {
|
|
|
+ if (i > 0) sb.append("、");
|
|
|
+ sb.append(done.get(i).getTitle());
|
|
|
+ }
|
|
|
+ sb.append("。");
|
|
|
+ }
|
|
|
+ if (!undone.isEmpty()) {
|
|
|
+ sb.append("【未完成】⚠ ");
|
|
|
+ for (int i = 0; i < undone.size(); i++) {
|
|
|
+ if (i > 0) sb.append("、");
|
|
|
+ Task t = undone.get(i);
|
|
|
+ sb.append(t.getTitle());
|
|
|
+ if (t.getDeadline() != null) {
|
|
|
+ sb.append("(已截止").append(HHMM.format(t.getDeadline())).append(")");
|
|
|
+ }
|
|
|
+ }
|
|
|
+ sb.append(" 别忘了打卡哦~");
|
|
|
+ }
|
|
|
+ return sb.toString();
|
|
|
+ }
|
|
|
+
|
|
|
+ private List<TaskReminderConfig> loadConfigs() {
|
|
|
+ if (taskReminderConfigMapper == null) {
|
|
|
+ return new ArrayList<>();
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ List<TaskReminderConfig> list = taskReminderConfigMapper.selectList(null);
|
|
|
+ return list == null ? new ArrayList<>() : list;
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("任务日提醒:读取提醒配置失败,按无配置处理: {}", e.getMessage());
|
|
|
+ return new ArrayList<>();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 今日 0 点(判重/分组边界)。 */
|
|
|
+ private Date dayStart() {
|
|
|
+ Calendar cal = Calendar.getInstance();
|
|
|
+ cal.set(Calendar.HOUR_OF_DAY, 0);
|
|
|
+ cal.set(Calendar.MINUTE, 0);
|
|
|
+ cal.set(Calendar.SECOND, 0);
|
|
|
+ cal.set(Calendar.MILLISECOND, 0);
|
|
|
+ return cal.getTime();
|
|
|
+ }
|
|
|
+}
|