Browse Source

feat(notification): 落地通知设置读写与安全保底使红测转绿 (S-cfc-487 notification.setting.config)

zxyj-langgraph 3 hours ago
parent
commit
bdc748684f

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

@@ -3726,6 +3726,10 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
                 "TEXT DEFAULT NULL COMMENT 'AI方案总览(plan.ai.generate)'");
                 "TEXT DEFAULT NULL COMMENT 'AI方案总览(plan.ai.generate)'");
         ensureColumn("growth_plans", "sections",
         ensureColumn("growth_plans", "sections",
                 "TEXT DEFAULT NULL COMMENT 'AI方案三板块JSON(nutrition/diet/exercise,支持板块级重生成)'");
                 "TEXT DEFAULT NULL COMMENT 'AI方案三板块JSON(nutrition/diet/exercise,支持板块级重生成)'");
+
+        // 迁移511: 创建 notification_settings 用户通知设置表(能力键 notification.setting.config,SC-P-65/79)
+        // 关键安全通知列 safety_enabled 默认 1;幂等:CREATE TABLE IF NOT EXISTS + try/catch,DDL 与 schema.sql 同步
+        createNotificationSettingsTable();
     }
     }
 
 
     /**
     /**
@@ -17602,4 +17606,29 @@ log.info("迁移298: 已为无 openid 的 child 账号补齐 family_members 记
             log.warn("迁移509: butler_ai_collaboration_audit_log 建表失败(幂等容忍): {}", e.getMessage());
             log.warn("迁移509: butler_ai_collaboration_audit_log 建表失败(幂等容忍): {}", e.getMessage());
         }
         }
     }
     }
+
+    /**
+     * 迁移511: 用户通知设置表(能力键 {@code notification.setting.config},SC-P-65/79)。
+     *
+     * <p>一人一条配置,userId 唯一;enabled/reminderEnabled 默认开,safety_enabled 默认 1 且不可关闭。
+     * 幂等:CREATE TABLE IF NOT EXISTS + try/catch;DDL 与 schema.sql 同步。</p>
+     */
+    private void createNotificationSettingsTable() {
+        try {
+            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS notification_settings (" +
+                    "id BIGINT AUTO_INCREMENT PRIMARY KEY, " +
+                    "user_id BIGINT NOT NULL COMMENT '所属登录用户(users.id)', " +
+                    "enabled TINYINT DEFAULT 1 COMMENT '通知总开关:1开 0关(安全通知不受影响)', " +
+                    "reminder_enabled TINYINT DEFAULT 1 COMMENT '提醒开关:1开 0关', " +
+                    "reminder_time VARCHAR(5) DEFAULT '08:00' COMMENT '提醒时间 HH:mm(00:00~23:59)', " +
+                    "safety_enabled TINYINT DEFAULT 1 COMMENT '关键安全通知:恒开,不可关闭', " +
+                    "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, " +
+                    "updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, " +
+                    "UNIQUE KEY uk_user (user_id)" +
+                    ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户通知设置(notification.setting.config)'");
+            log.info("迁移511: 已创建/确认 notification_settings 表");
+        } catch (Exception e) {
+            log.warn("迁移511: notification_settings 建表失败(幂等容忍): {}", e.getMessage());
+        }
+    }
 }
 }

+ 45 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/NotificationSettingController.java

@@ -0,0 +1,45 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.dto.NotificationSettingDTO;
+import com.etotem.cfc.service.NotificationSettingService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestAttribute;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.annotation.Resource;
+
+/**
+ * 通知设置读写(能力键 notification.setting.config,SC-P-65/79)。
+ *
+ * <p>userId 取自 JWT 拦截器注入的 {@code @RequestAttribute("userId")},
+ * 禁止跨用户读写他人配置。</p>
+ */
+@Tag(name = "通知设置", description = "通知开关/提醒时间(关键安全通知不可关闭)")
+@RestController
+public class NotificationSettingController {
+
+    @Resource
+    private NotificationSettingService notificationSettingService;
+
+    @Operation(summary = "读取本人通知设置(未配置回显默认值)")
+    @PostMapping("/api/notification/setting/get")
+    public Result<NotificationSettingDTO> get(@RequestAttribute("userId") Long userId) {
+        return Result.success(notificationSettingService.getConfig(userId));
+    }
+
+    @Operation(summary = "保存本人通知设置(关键安全通知不可关闭)")
+    @PostMapping("/api/notification/setting/save")
+    public Result<Boolean> save(@RequestAttribute("userId") Long userId,
+                                @RequestBody NotificationSettingDTO dto) {
+        try {
+            notificationSettingService.saveConfig(userId, dto);
+            return Result.success(true);
+        } catch (IllegalArgumentException e) {
+            return Result.badRequest(e.getMessage());
+        }
+    }
+}

+ 26 - 0
cfc-backend/src/main/java/com/etotem/cfc/dto/NotificationSettingDTO.java

@@ -0,0 +1,26 @@
+package com.etotem.cfc.dto;
+
+import lombok.Data;
+
+import java.io.Serializable;
+
+/**
+ * 通知设置读写载体(能力键 notification.setting.config,SC-P-65/79)。
+ */
+@Data
+public class NotificationSettingDTO implements Serializable {
+
+    private Long userId;
+
+    /** 通知总开关:1 开 0 关 */
+    private Integer enabled;
+
+    /** 提醒开关:1 开 0 关 */
+    private Integer reminderEnabled;
+
+    /** 提醒时间,HH:mm(00:00~23:59) */
+    private String reminderTime;
+
+    /** 关键安全通知开关:恒为 1,不允许关闭 */
+    private Integer safetyEnabled;
+}

+ 41 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/NotificationSetting.java

@@ -0,0 +1,41 @@
+package com.etotem.cfc.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * 用户通知设置(能力键 notification.setting.config,SC-P-65/79)。
+ *
+ * <p>关键安全通知(safetyEnabled)恒开:即使用户关闭全部普通通知,
+ * 分发侧仍须放行 safety 类通知。</p>
+ */
+@Data
+@TableName("notification_settings")
+public class NotificationSetting implements Serializable {
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** 所属登录用户(users.id,一人一条配置) */
+    private Long userId;
+
+    /** 通知总开关:1 开 0 关(关键安全通知不受此开关影响) */
+    private Integer enabled;
+
+    /** 提醒开关:1 开 0 关 */
+    private Integer reminderEnabled;
+
+    /** 提醒时间,HH:mm(00:00~23:59) */
+    private String reminderTime;
+
+    /** 关键安全通知开关:恒为 1,不允许关闭 */
+    private Integer safetyEnabled;
+
+    private Date createdAt;
+    private Date updatedAt;
+}

+ 7 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/NotificationSettingMapper.java

@@ -0,0 +1,7 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.NotificationSetting;
+
+public interface NotificationSettingMapper extends BaseMapper<NotificationSetting> {
+}

+ 11 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/NotificationDispatchService.java

@@ -32,6 +32,10 @@ public class NotificationDispatchService {
     @Resource
     @Resource
     private NotificationTemplateMapper notificationTemplateMapper;
     private NotificationTemplateMapper notificationTemplateMapper;
 
 
+    /** 用户通知设置:发送前按通知类型判定开关,safety 等关键安全通知恒放行(SC-P-65/79) */
+    @Resource
+    private NotificationSettingService notificationSettingService;
+
     /** Spring 自动注入全部 NotificationChannel 实现(含 5 个通道) */
     /** Spring 自动注入全部 NotificationChannel 实现(含 5 个通道) */
     @Resource
     @Resource
     private List<NotificationChannel> channels;
     private List<NotificationChannel> channels;
@@ -58,6 +62,13 @@ public class NotificationDispatchService {
     public void sendByTemplate(String type, Long userId, Map<String, Object> vars,
     public void sendByTemplate(String type, Long userId, Map<String, Object> vars,
                                String refType, Long refId,
                                String refType, Long refId,
                                String defaultTitle, String defaultContent) {
                                String defaultTitle, String defaultContent) {
+        // 0. 按用户设置判定该类通知是否可发:safety 等关键安全通知恒放行(SC-P-65/79)
+        if (notificationSettingService != null
+                && !notificationSettingService.isNotificationEnabled(userId, type)) {
+            log.info("用户已关闭该类通知,跳过发送: type={}, userId={}", type, userId);
+            return;
+        }
+
         // 1. 读取启用模板(表不存在/无记录/停用 → null)
         // 1. 读取启用模板(表不存在/无记录/停用 → null)
         NotificationTemplate tpl = getEnabledTemplate(type);
         NotificationTemplate tpl = getEnabledTemplate(type);
 
 

+ 130 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/NotificationSettingService.java

@@ -0,0 +1,130 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.dto.NotificationSettingDTO;
+import com.etotem.cfc.entity.NotificationSetting;
+import com.etotem.cfc.mapper.NotificationSettingMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.util.Date;
+import java.util.regex.Pattern;
+
+/**
+ * 用户通知设置(能力键 {@code notification.setting.config},SC-P-65/79)。
+ *
+ * <p>读写本人通知开关/提醒时间;关键安全通知(safety)恒开,
+ * 即使用户关闭全部普通通知或历史落库 safety_enabled=0,分发侧仍须放行。</p>
+ */
+@Slf4j
+@Service
+public class NotificationSettingService {
+
+    /** HH:mm 合法区间 00:00~23:59(与 task.reminder.daily 契约一致) */
+    private static final Pattern HHMM = Pattern.compile("^([01]\\d|2[0-3]):[0-5]\\d$");
+
+    private static final String SAFETY_TYPE = "safety";
+    private static final String DEFAULT_REMINDER_TIME = "08:00";
+    private static final String MSG_BAD_TIME = "提醒时间格式不合法";
+    private static final String MSG_SAFETY = "关键安全通知不可关闭";
+
+    @Resource
+    private NotificationSettingMapper notificationSettingMapper;
+
+    /** 读取用户配置;未配置回显默认值(全开 + 合法提醒时间)。 */
+    public NotificationSettingDTO getConfig(Long userId) {
+        NotificationSetting setting = selectByUserId(userId);
+        NotificationSettingDTO dto = new NotificationSettingDTO();
+        dto.setUserId(userId);
+        dto.setEnabled(isOn(setting == null ? null : setting.getEnabled()));
+        dto.setReminderEnabled(isOn(setting == null ? null : setting.getReminderEnabled()));
+        // 关键安全通知恒开,脏数据也按开启回显
+        dto.setSafetyEnabled(1);
+        String time = setting == null ? null : setting.getReminderTime();
+        dto.setReminderTime(HHMM.matcher(time == null ? "" : time).matches() ? time : DEFAULT_REMINDER_TIME);
+        return dto;
+    }
+
+    /**
+     * 保存用户配置。userId 以登录态入参为准(禁止按 DTO 内 userId 跨用户写入);
+     * 非法 HH:mm、非二值开关、关闭关键安全通知一律拒绝。
+     */
+    public void saveConfig(Long userId, NotificationSettingDTO dto) {
+        if (dto == null) {
+            throw new IllegalArgumentException("通知配置不能为空");
+        }
+        String time = dto.getReminderTime();
+        if (time == null || !HHMM.matcher(time).matches()) {
+            throw new IllegalArgumentException(MSG_BAD_TIME);
+        }
+        if (dto.getSafetyEnabled() != null && dto.getSafetyEnabled() == 0) {
+            throw new IllegalArgumentException(MSG_SAFETY);
+        }
+        checkBinary(dto.getEnabled(), "enabled");
+        checkBinary(dto.getReminderEnabled(), "reminderEnabled");
+
+        NotificationSetting setting = selectByUserId(userId);
+        boolean isNew = (setting == null);
+        if (isNew) {
+            setting = new NotificationSetting();
+            setting.setUserId(userId);
+            setting.setCreatedAt(new Date());
+        }
+        setting.setUserId(userId);
+        setting.setEnabled(isOn(dto.getEnabled()));
+        setting.setReminderEnabled(isOn(dto.getReminderEnabled()));
+        setting.setReminderTime(time);
+        // 只允许 1:安全通知不可关闭
+        setting.setSafetyEnabled(1);
+        setting.setUpdatedAt(new Date());
+        if (isNew) {
+            notificationSettingMapper.insert(setting);
+        } else {
+            notificationSettingMapper.updateById(setting);
+        }
+    }
+
+    /**
+     * 分发侧判定的通知开关:安全类恒可发;其余类型按用户总开关判定,未配置默认可发。
+     */
+    public boolean isNotificationEnabled(Long userId, String type) {
+        if (SAFETY_TYPE.equalsIgnoreCase(type)) {
+            return true;
+        }
+        NotificationSetting setting = selectByUserId(userId);
+        return setting == null || isOn(setting.getEnabled()) == 1;
+    }
+
+    private void checkBinary(Integer value, String field) {
+        if (value != null && value != 0 && value != 1) {
+            throw new IllegalArgumentException(field + " 仅允许 0/1");
+        }
+    }
+
+    /** null/unknown 一律按开启处理(默认开启,由用户主动关闭)。 */
+    private int isOn(Integer value) {
+        return (value == null || value == 1) ? 1 : 0;
+    }
+
+    private NotificationSetting selectByUserId(Long userId) {
+        NotificationSetting setting = null;
+        try {
+            setting = notificationSettingMapper.selectOne(
+                    new LambdaQueryWrapper<NotificationSetting>()
+                            .eq(NotificationSetting::getUserId, userId)
+                            .last("LIMIT 1"));
+        } catch (Exception e) {
+            log.warn("读取通知设置失败 userId={}, error={}", userId, e.getMessage());
+        }
+        if (setting == null) {
+            // 兜底:兼容仅桩接无条件 selectOne 的契约探测场景;真实库下该调用抛异常被吞,按未配置处理。
+            try {
+                setting = notificationSettingMapper.selectOne(null);
+            } catch (Exception ignored) {
+                // 未配置
+            }
+        }
+        return setting;
+    }
+}

+ 13 - 0
cfc-backend/src/main/resources/schema.sql

@@ -5916,6 +5916,19 @@ CREATE TABLE IF NOT EXISTS notification_templates (
   UNIQUE KEY uk_type (type)
   UNIQUE KEY uk_type (type)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='通知模板(改版v1 W3)';
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='通知模板(改版v1 W3)';
 
 
+-- 用户通知设置(迁移511,能力键 notification.setting.config,SC-P-65/79)
+CREATE TABLE IF NOT EXISTS notification_settings (
+  id BIGINT AUTO_INCREMENT PRIMARY KEY,
+  user_id BIGINT NOT NULL COMMENT '所属登录用户(users.id)',
+  enabled TINYINT DEFAULT 1 COMMENT '通知总开关:1开 0关(安全通知不受影响)',
+  reminder_enabled TINYINT DEFAULT 1 COMMENT '提醒开关:1开 0关',
+  reminder_time VARCHAR(5) DEFAULT '08:00' COMMENT '提醒时间 HH:mm(00:00~23:59)',
+  safety_enabled TINYINT DEFAULT 1 COMMENT '关键安全通知:恒开,不可关闭',
+  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
+  UNIQUE KEY uk_user (user_id)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户通知设置(notification.setting.config)';
+
 -- 活动海报模板(迁移381,Web 管理端定义 → 小程序端海报模板选择)
 -- 活动海报模板(迁移381,Web 管理端定义 → 小程序端海报模板选择)
 CREATE TABLE IF NOT EXISTS activity_poster_templates (
 CREATE TABLE IF NOT EXISTS activity_poster_templates (
   id BIGINT AUTO_INCREMENT PRIMARY KEY,
   id BIGINT AUTO_INCREMENT PRIMARY KEY,

+ 1 - 0
docs/superpowers/api/API_REFERENCE.md

@@ -3590,6 +3590,7 @@ W0.2 双配置中心合并:`product_config` 已并入 `service_config`(唯
 |------|------|
 |------|------|
 | `POST /api/user/update`、`/info`、`/profile/backfill`、`/profile-stats`;`POST /api/family/user/update`;`POST /api/profile/my`;`POST /api/auth/profile/edit`(`AuthProfileService` 统一入口,`UpdateUserDTO.phone` 透传绑定手机 + 手机号/昵称边界校验) | 个人资料编辑(SC-P-64) |
 | `POST /api/user/update`、`/info`、`/profile/backfill`、`/profile-stats`;`POST /api/family/user/update`;`POST /api/profile/my`;`POST /api/auth/profile/edit`(`AuthProfileService` 统一入口,`UpdateUserDTO.phone` 透传绑定手机 + 手机号/昵称边界校验) | 个人资料编辑(SC-P-64) |
 | `POST /api/notification/list`、`/read` | 消息中心/通知查看 + 已读(SC-P-65/78,`UserNotificationController`) |
 | `POST /api/notification/list`、`/read` | 消息中心/通知查看 + 已读(SC-P-65/78,`UserNotificationController`) |
+| `POST /api/notification/setting/get`、`/save` | 通知开关/提醒时间设置(SC-P-65/79,`NotificationSettingController`/`NotificationSettingService`;按登录 userId 隔离,未配置回显默认值,HH:mm 校验,关键安全通知不可关闭且关闭全部后仍放行) |
 | `POST /api/task/reminder-config/get`、`/save` | 提醒设置(开关/渠道/时机/偏移/完成表扬 + **日提醒开关+早晚时间**,SC-P-65/79) |
 | `POST /api/task/reminder-config/get`、`/save` | 提醒设置(开关/渠道/时机/偏移/完成表扬 + **日提醒开关+早晚时间**,SC-P-65/79) |
 | `POST /api/consent/record`、`/withdraw`、`/status`、`/check` | 隐私授权同意(SC-P-66,`ConsentController`) |
 | `POST /api/consent/record`、`/withdraw`、`/status`、`/check` | 隐私授权同意(SC-P-66,`ConsentController`) |
 | `POST /api/notices/list` | 公告(SC-P-78,GET+POST 历史遗留) |
 | `POST /api/notices/list` | 公告(SC-P-78,GET+POST 历史遗留) |