Просмотр исходного кода

feat(task): 任务频率/周期配置(SC-P-12) S-cfc-360 task.frequency.config

- Task 实体新增自定义周期字段 frequencyUnit/frequencyInterval/cycleAnchor 与暂停标记 isPaused
- TaskService.createTask 支持 frequency=custom,从 actionConfig 解析 periodUnit/periodInterval/cycleAnchor 并落库
- TaskService 新增 pauseTask/resumeTask(仅模板任务、创建者本人,幂等)
- RepeatTaskGenerator 新增自定义周期生成分支与按锚点推进的跨月/跨年周期计算(generateCustomPeriodTasks / computeNextOccurrence)
- TaskController 新增 POST /api/tasks/{id}/pause、/api/tasks/{id}/resume
- schema.sql tasks 表同步 frequency_unit/frequency_interval/cycle_anchor/is_paused 列与 status 的 paused 枚举;DatabaseInitializer 迁移478 同步
Agnes Agent 1 день назад
Родитель
Сommit
053e76f53f

+ 28 - 0
cfc-backend/src/main/java/com/etotem/cfc/config/DatabaseInitializer.java

@@ -3549,6 +3549,9 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
         createButlerResourceMatchLogTable();
         // 迁移477: 资源参与回访沉淀偏好表 butler_resource_follow_up(AC4 回访记录写入家长档案)
         createButlerResourceFollowUpTable();
+
+        // 迁移478: tasks 表自定义周期/暂停扩展列 + status 增加 paused(SC-P-12 task.frequency.config)
+        addTaskFrequencyConfigColumns();
     }
 
     /**
@@ -3639,6 +3642,31 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
         }
     }
 
+    /**
+     * 迁移478: tasks 表自定义周期/暂停扩展列 + status 增加 paused(SC-P-12 task.frequency.config)。
+     *
+     * <p>承载任务频率/周期配置:自定义周期(任意 N 天)持久化周期单位/间隔/锚点;
+     * 暂停标记用于暂停后不再生成实例,恢复后按原周期继续。幂等:ensureColumn + MODIFY 包裹。</p>
+     */
+    private void addTaskFrequencyConfigColumns() {
+        try {
+            ensureColumn("tasks", "frequency_unit", "VARCHAR(16) NULL COMMENT '自定义周期单位: DAY/WEEK/MONTH(SC-P-12 frequency=custom)'");
+            ensureColumn("tasks", "frequency_interval", "INT NULL COMMENT '自定义周期间隔(每 N 个 frequency_unit 生成一次实例)'");
+            ensureColumn("tasks", "cycle_anchor", "DATETIME NULL COMMENT '自定义周期锚点(按锚点推进,跨月/跨年不漂移)'");
+            ensureColumn("tasks", "is_paused", "TINYINT(1) NOT NULL DEFAULT 0 COMMENT '暂停标记(1=暂停,RepeatTaskGenerator 不再生成实例)'");
+        } catch (Exception e) {
+            log.warn("迁移478: tasks 自定义周期/暂停扩展列添加失败(可能已存在): {}", e.getMessage());
+        }
+        try {
+            jdbcTemplate.execute("ALTER TABLE tasks MODIFY COLUMN status "
+                    + "ENUM('pending', 'assigned', 'in_progress', 'completed', 'rejected', "
+                    + "'overdue', 'cancelled', 'locked', 'pending_review', 'paused') DEFAULT 'pending'");
+            log.info("迁移478: tasks.status 已增加 paused 枚举值");
+        } catch (Exception e) {
+            log.warn("迁移478: tasks.status 增加 paused 失败(可能已包含): {}", e.getMessage());
+        }
+    }
+
     /** 迁移473(FamilyWorkbench): tasks 加家庭+时间复合索引,支撑工作台按家庭聚合计数与近 30 天逐日趋势。 */
     void addTasksFamilyCreatedIndex() {
         try {

+ 23 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/task/TaskController.java

@@ -355,6 +355,29 @@ public class TaskController {
         return Result.success(success);
     }
 
+    /**
+     * 暂停重复任务模板(SC-P-12 task.frequency.config)。
+     *
+     * <p>暂停后 {@code RepeatTaskGenerator} 不再为其生成周期实例;重复任务在恢复后
+     * 按原周期锚点继续生成。仅模板任务(is_template=1)可暂停。</p>
+     */
+    @Operation(summary = "暂停周期任务")
+    @PostMapping("/{id}/pause")
+    public Result<Boolean> pauseTask(@PathVariable Long id,
+                                     @RequestAttribute("userId") Long userId) {
+        return Result.success(taskService.pauseTask(id, userId));
+    }
+
+    /**
+     * 恢复周期任务模板(SC-P-12 task.frequency.config):恢复后按原周期继续生成实例。
+     */
+    @Operation(summary = "恢复周期任务")
+    @PostMapping("/{id}/resume")
+    public Result<Boolean> resumeTask(@PathVariable Long id,
+                                      @RequestAttribute("userId") Long userId) {
+        return Result.success(taskService.resumeTask(id, userId));
+    }
+
     /**
      * 获取家庭成员可关联的任务列表(含所有状态),供创建任务时选择前置/后置任务
      */

+ 12 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/Task.java

@@ -81,6 +81,18 @@ private String frequency;
 // 周期内最多完成次数
 private Integer maxFrequency;
 
+/** SC-P-12 task.frequency.config: 自定义周期单位(DAY/WEEK/MONTH),frequency=custom 时有效 */
+private String frequencyUnit;
+
+/** SC-P-12 task.frequency.config: 自定义周期间隔(每 N 个 frequencyUnit 生成一次实例) */
+private Integer frequencyInterval;
+
+/** SC-P-12 task.frequency.config: 自定义周期锚点(按锚点推进周期,跨月/跨年不漂移) */
+private Date cycleAnchor;
+
+/** SC-P-12 task.frequency.config: 暂停标记(1=暂停,RepeatTaskGenerator 不再生成实例) */
+private Integer isPaused;
+
 // 完成方式(多选,JSON格式: ["checkin","text","image"])
 private String completeTypes;
 

+ 110 - 2
cfc-backend/src/main/java/com/etotem/cfc/service/TaskService.java

@@ -100,7 +100,7 @@ public class TaskService implements TaskServiceInterface {
 
     // ==================== SC-P-10 创建任务校验(S-cfc-12) ====================
     private static final Set<String> VALID_FREQUENCIES = Collections.unmodifiableSet(
-            new HashSet<>(Arrays.asList("none", "daily", "weekly", "monthly", "every_other_day", "hourly")));
+            new HashSet<>(Arrays.asList("none", "daily", "weekly", "monthly", "every_other_day", "hourly", "custom")));
     /** 幂等窗口:同一创建请求在 30 秒内重复提交仅生成 1 条任务(重复提交不重复发分) */
     private static final long TASK_DEDUP_WINDOW_MS = 30_000L;
     /** 按任务去重键持有的 JVM 内锁,保证并发双发时 check-then-insert 原子性 */
@@ -345,6 +345,13 @@ public class TaskService implements TaskServiceInterface {
         task.setFrequency(dto.getFrequency());
         task.setMaxFrequency(dto.getMaxFrequency());
 
+        // SC-P-12 task.frequency.config: 自定义周期(frequency=custom)周期单位/间隔/锚点
+        // 周期单位+间隔按 API_REFERENCE §4.3 以 actionType + actionConfig 声明,
+        // 此处解析后持久化到 Task 实体,供 RepeatTaskGenerator 按周期锚点推进生成实例。
+        if ("custom".equals(dto.getFrequency())) {
+            applyCustomFrequencyPeriod(task, dto);
+        }
+
         // 完成方式(转为JSON存储)
         if (dto.getCompleteTypes() != null && !dto.getCompleteTypes().isEmpty()) {
             task.setCompleteTypes(String.join(",", dto.getCompleteTypes()));
@@ -358,7 +365,9 @@ public class TaskService implements TaskServiceInterface {
         task.setLatestEnd(dto.getLatestEnd());
 
         // 如果是重复任务,标记为模板
-        if (!"none".equals(task.getRepeatType())) {
+        // SC-P-12 task.frequency.config: frequency=custom 同样是周期任务,须标记为模板,
+        // 否则 RepeatTaskGenerator(仅处理 is_template=1)永远不会为其生成实例。
+        if (!"none".equals(task.getRepeatType()) || "custom".equals(task.getFrequency())) {
             task.setIsTemplate(1); // 模板任务
         } else {
             task.setIsTemplate(0);
@@ -436,6 +445,54 @@ task.setReviewByCategory(dto.getReviewByCategory() != null ? dto.getReviewByCate
         return member != null ? member.getId() : null;
     }
 
+    /**
+     * SC-P-12 task.frequency.config: 解析 actionConfig 中自定义周期配置并写回 Task。
+     *
+     * <p>actionConfig JSON 字段约定(API_REFERENCE §4.3 任务配置声明):
+     * {@code periodUnit} 周期单位(DAY/WEEK/MONTH,默认 DAY),{@code periodInterval} 间隔
+     * (每 N 个周期单位生成一次实例,默认 1)。锚点 {@code cycleAnchor} 优先取 actionConfig,
+     * 缺省取模板截止时间或创建时间,保证 RepeatTaskGenerator 能按锚点逐周期推进。</p>
+     */
+    private void applyCustomFrequencyPeriod(Task task, CreateTaskDTO dto) {
+        String periodUnit = "DAY";
+        int periodInterval = 1;
+        JSONObject actionConfig = null;
+        if (dto.getActionConfig() != null && !dto.getActionConfig().trim().isEmpty()) {
+            try {
+                actionConfig = JSON.parseObject(dto.getActionConfig());
+            } catch (Exception e) {
+                log.warn("SC-P-12 自定义周期 actionConfig 解析失败,按默认 DAY/1 处理: taskId={}", task.getId());
+            }
+        }
+        if (actionConfig != null) {
+            String configuredUnit = actionConfig.getString("periodUnit");
+            if (configuredUnit != null && !configuredUnit.trim().isEmpty()) {
+                periodUnit = configuredUnit.trim().toUpperCase(Locale.ROOT);
+            }
+            Integer configuredInterval = actionConfig.getInteger("periodInterval");
+            if (configuredInterval != null && configuredInterval > 0) {
+                periodInterval = configuredInterval;
+            }
+        }
+        task.setFrequencyUnit(periodUnit);
+        task.setFrequencyInterval(periodInterval);
+
+        Date anchor = null;
+        if (actionConfig != null && actionConfig.getDate("cycleAnchor") != null) {
+            anchor = actionConfig.getDate("cycleAnchor");
+        }
+        if (anchor == null && task.getDeadline() != null) {
+            anchor = task.getDeadline();
+        }
+        if (anchor == null && task.getCreatedAt() != null) {
+            anchor = task.getCreatedAt();
+        }
+        if (anchor == null) {
+            anchor = new Date();
+        }
+        task.setCycleAnchor(anchor);
+    }
+
 /**
  * 实现接口:获取今日任务列表(按memberId,不过滤维度)
  */
@@ -1068,6 +1125,57 @@ public List<Task> getTodayTasks(Long memberId, String dimensionCode) {
             .set(Task::getUpdatedAt, new Date()));
     }
 
+    /**
+     * SC-P-12 task.frequency.config: 暂停重复任务模板(暂停后 RepeatTaskGenerator 不再生成实例)。
+     *
+     * <p>仅对 {@code is_template=1} 的周期任务有效;重复调用幂等返回 true。
+     * 非模板任务/任务不存在返回 false,避免误改一次性任务状态。</p>
+     */
+    @Transactional
+    public boolean pauseTask(Long taskId, Long userId) {
+        Task task = taskMapper.selectById(taskId);
+        if (task == null || !task.getCreatorId().equals(userId)) {
+            return false;
+        }
+        if (task.getIsTemplate() == null || task.getIsTemplate() != 1) {
+            return false;
+        }
+        if ("paused".equals(task.getStatus())) {
+            return true;
+        }
+        task.setStatus("paused");
+        task.setIsPaused(1);
+        task.setUpdatedAt(new Date());
+        taskMapper.updateById(task);
+        return true;
+    }
+
+    /**
+     * SC-P-12 task.frequency.config: 恢复暂停的重复任务模板(按原周期继续生成实例)。
+     *
+     * <p>恢复后状态回到 {@code pending},{@code is_paused=0},RepeatTaskGenerator 下一轮
+     * 按周期锚点继续推进生成。重复调用幂等返回 true。</p>
+     */
+    @Transactional
+    public boolean resumeTask(Long taskId, Long userId) {
+        Task task = taskMapper.selectById(taskId);
+        if (task == null || !task.getCreatorId().equals(userId)) {
+            return false;
+        }
+        if (task.getIsTemplate() == null || task.getIsTemplate() != 1) {
+            return false;
+        }
+        if ("paused".equals(task.getStatus()) || Integer.valueOf(1).equals(task.getIsPaused())) {
+            task.setStatus("pending");
+            task.setIsPaused(0);
+            task.setUpdatedAt(new Date());
+            taskMapper.updateById(task);
+            return true;
+        }
+        // 非暂停态:幂等返回 true(不改变状态)
+        return true;
+    }
+
     private Map<String, Object> submitTaskForReview(Task task, Long memberId, Date now, String content, String contentType) {
         task.setStatus("pending_review");
         task.setCompletedAt(now);

+ 134 - 0
cfc-backend/src/main/java/com/etotem/cfc/task/RepeatTaskGenerator.java

@@ -139,6 +139,9 @@ public class RepeatTaskGenerator {
             }
             log.info("每小时重复任务生成完成,处理{}个模板", hourlyTasks.size());
 
+            // 6. 自定义周期任务(frequency=custom,每 N 个 DAY/WEEK/MONTH),SC-P-12 task.frequency.config
+            generateCustomPeriodTasks(todayCal);
+
         } catch (Exception e) {
             log.error("生成重复任务失败", e);
         }
@@ -154,6 +157,137 @@ public class RepeatTaskGenerator {
         return diffDays % 2 == 0;
     }
 
+    /**
+     * SC-P-12 task.frequency.config: 自定义周期(每 N 个 DAY/WEEK/MONTH)任务实例生成。
+     *
+     * <p>只处理 {@code frequency=custom} 且未暂停({@code is_paused=0} 或 NULL)的模板;
+     * 今天是否落在周期上由 {@link #isCustomCycleDue(Task, Date)} 按锚点判定,
+     * 判定的推进计算由 {@link #computeNextOccurrence(Task, Date)} 提供(跨月/跨年不漂移)。
+     * 暂停的模板被查询条件排除,恢复后下一轮自动按原锚点继续。</p>
+     */
+    private void generateCustomPeriodTasks(Calendar todayCal) {
+        Date today = startOfDay(todayCal.getTime());
+        List<Task> customTasks = taskMapper.selectList(
+            new LambdaQueryWrapper<Task>()
+                .eq(Task::getIsTemplate, 1)
+                .eq(Task::getFrequency, "custom")
+                .and(w -> w.eq(Task::getIsPaused, 0).or().isNull(Task::getIsPaused))
+        );
+        for (Task template : customTasks) {
+            if (isCustomCycleDue(template, today) && !hasTaskForDate(template, today, 86400000L)) {
+                createTaskFromTemplate(template, today, false);
+            }
+        }
+        log.info("自定义周期任务生成完成,处理{}个模板", customTasks.size());
+    }
+
+    /**
+     * 判断今天是否落在自定义周期上(以 cycleAnchor 为第 0 个周期,逐周期推进到 >= 今天)。
+     */
+    private boolean isCustomCycleDue(Task template, Date today) {
+        Date anchor = cycleAnchorOf(template);
+        if (anchor == null) {
+            return false;
+        }
+        Date cursor = startOfDay(anchor);
+        // 防御性上限:避免异常配置(间隔为 0/负数)导致死循环
+        int guard = 0;
+        while (cursor.before(today) && guard++ < 20000) {
+            cursor = startOfDay(computeNextOccurrence(template, cursor));
+        }
+        return sameDay(cursor, today);
+    }
+
+    /**
+     * SC-P-12 边界「周期计算跨月/跨年正确」:按周期锚点 + 间隔计算 {@code from} 之后的下一个周期日。
+     *
+     * <p>采用「锚点 + k×间隔」而非逐次累加,避免月末日期漂移
+     * (如 1 月 31 日按 1 个月推进:2 月 28 日 → 3 月 31 日,而非 3 月 28 日)。
+     * MONTH/YEAR 使用 {@link Calendar} 按月进位处理跨月/跨年,目标月天数不足时收敛到当月最后一天。</p>
+     */
+    private Date computeNextOccurrence(Task template, Date from) {
+        Date anchor = startOfDay(cycleAnchorOf(template));
+        Date fromDay = startOfDay(from);
+        String unit = normalizeUnit(template.getFrequencyUnit());
+        int interval = template.getFrequencyInterval() != null && template.getFrequencyInterval() > 0
+            ? template.getFrequencyInterval() : 1;
+
+        if ("MONTH".equals(unit) || "YEAR".equals(unit)) {
+            int stepMonths = "YEAR".equals(unit) ? 12 * interval : interval;
+            Calendar anchorCal = Calendar.getInstance();
+            anchorCal.setTime(anchor);
+            Calendar fromCal = Calendar.getInstance();
+            fromCal.setTime(fromDay);
+            int monthsDiff = (fromCal.get(Calendar.YEAR) - anchorCal.get(Calendar.YEAR)) * 12
+                + (fromCal.get(Calendar.MONTH) - anchorCal.get(Calendar.MONTH));
+            int k = monthsDiff > 0 ? monthsDiff / stepMonths : 0;
+            Calendar occurrence = monthOffset(anchorCal, k * stepMonths);
+            while (!occurrence.getTime().after(fromDay)) {
+                k++;
+                occurrence = monthOffset(anchorCal, k * stepMonths);
+            }
+            return occurrence.getTime();
+        }
+
+        long stepDays = "WEEK".equals(unit) ? 7L * interval : interval;
+        long diffDays = (fromDay.getTime() - anchor.getTime()) / 86400000L;
+        long k = diffDays > 0 ? diffDays / stepDays : 0;
+        Calendar occurrence = Calendar.getInstance();
+        occurrence.setTime(anchor);
+        occurrence.add(Calendar.DAY_OF_MONTH, (int) (k * stepDays));
+        while (!occurrence.getTime().after(fromDay)) {
+            k++;
+            occurrence.setTime(anchor);
+            occurrence.add(Calendar.DAY_OF_MONTH, (int) (k * stepDays));
+        }
+        return occurrence.getTime();
+    }
+
+    /**
+     * 锚点月 + N 个月,日期收敛到目标月最后一天(1 月 31 日 + 1 个月 = 2 月 28/29 日)。
+     */
+    private Calendar monthOffset(Calendar anchorCal, int months) {
+        Calendar cal = Calendar.getInstance();
+        cal.setTime(anchorCal.getTime());
+        int anchorDay = anchorCal.get(Calendar.DAY_OF_MONTH);
+        cal.set(Calendar.DAY_OF_MONTH, 1);
+        cal.add(Calendar.MONTH, months);
+        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
+        cal.set(Calendar.DAY_OF_MONTH, Math.min(anchorDay, lastDay));
+        return cal;
+    }
+
+    /**
+     * 周期锚点:优先 cycleAnchor,其次模板截止时间,缺省回退模板创建时间。
+     */
+    private Date cycleAnchorOf(Task template) {
+        if (template.getCycleAnchor() != null) {
+            return template.getCycleAnchor();
+        }
+        if (template.getDeadline() != null) {
+            return template.getDeadline();
+        }
+        return template.getCreatedAt();
+    }
+
+    /**
+     * 周期单位归一(day/daily → DAY,week/weekly → WEEK,month/monthly → MONTH,year/yearly → YEAR)。
+     */
+    private String normalizeUnit(String unit) {
+        if (unit == null || unit.trim().isEmpty()) {
+            return "DAY";
+        }
+        String u = unit.trim().toUpperCase(java.util.Locale.ROOT);
+        if ("WEEKLY".equals(u)) return "WEEK";
+        if ("MONTHLY".equals(u)) return "MONTH";
+        if ("YEARLY".equals(u)) return "YEAR";
+        return u;
+    }
+
+    private boolean sameDay(Date a, Date b) {
+        return a != null && b != null && startOfDay(a).getTime() == startOfDay(b).getTime();
+    }
+
     /**
      * 检查指定时间窗口内是否已存在该模板的任务实例
      * @param windowMs 去重窗口(毫秒):86400000=当天,3600000=最近1小时

+ 5 - 1
cfc-backend/src/main/resources/schema.sql

@@ -120,10 +120,14 @@ CREATE TABLE IF NOT EXISTS tasks (
     category VARCHAR(32),
     need_review TINYINT DEFAULT 0 COMMENT '是否需要审核',
     review_by_category TINYINT DEFAULT 0 COMMENT '是否按分类审核',
-    status ENUM('pending', 'assigned', 'in_progress', 'completed', 'rejected', 'overdue', 'cancelled', 'locked', 'pending_review') DEFAULT 'pending',
+    status ENUM('pending', 'assigned', 'in_progress', 'completed', 'rejected', 'overdue', 'cancelled', 'locked', 'pending_review', 'paused') DEFAULT 'pending',
     completed_at DATETIME,
     bonus_rule JSON COMMENT '积分奖励规则',
     points_expire_days INT DEFAULT 0 COMMENT '积分有效期天数',
+    frequency_unit VARCHAR(16) NULL COMMENT '自定义周期单位: DAY/WEEK/MONTH(SC-P-12 frequency=custom)',
+    frequency_interval INT NULL COMMENT '自定义周期间隔(每 N 个 frequency_unit 生成一次实例)',
+    cycle_anchor DATETIME NULL COMMENT '自定义周期锚点(按锚点推进,跨月/跨年不漂移)',
+    is_paused TINYINT(1) NOT NULL DEFAULT 0 COMMENT '暂停标记(1=暂停,RepeatTaskGenerator 不再生成实例)',
     dimension_code VARCHAR(20) COMMENT '五维维度: body/mind/wisdom/action/wealth',
     dimension_weights JSON COMMENT '五维权重: {"body":0,"mind":0,"wisdom":0,"action":0,"wealth":0}',
     parent_task_id BIGINT NULL COMMENT '父任务ID(购买任务→每日使用子任务链;子任务在父任务完成前不显示)',