feat(通知): 四级严重度与严重度/时间双排序,客户端与后台管理同步
通知表新增 severity(紧急/高危/中危/低危,V161),由 scene + level 推导且 不回改 level:老客户端配色不受影响,secret_balance 的余量偏低与欠费也能分档。 列表与聚合接口默认按严重度倒序(同档按时间倒序),sort=time 切纯时间排序; 聚合组取组内最高严重度。两端铃铛加彩色等级标签与排序切换,展开明细沿用 同一排序,严重度排序下隐藏会跨天误导的日期头。
This commit is contained in:
+15
-6
@@ -48,7 +48,8 @@ public class AdminNotificationController {
|
||||
@Operation(summary = "通知聚合列表(铃铛默认视图)",
|
||||
description = "按「场景 × 自然日 × 事件主体用户」折叠,分页按组切。"
|
||||
+ "返回 total=组数、rowCount=同条件下折叠前的明细条数,两个数都要显示,"
|
||||
+ "否则「共 12 条」会被读成只有 12 条通知。筛选条件与单条列表共用一套实现。")
|
||||
+ "否则「共 12 条」会被读成只有 12 条通知。筛选条件与单条列表共用一套实现。"
|
||||
+ "sort 默认 severity(紧急→低危,同档按时间倒序),传 time 则纯时间倒序。")
|
||||
public ApiResponse<NotificationGroupPageVo> groups(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "页码(按组)") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@@ -60,10 +61,14 @@ public class AdminNotificationController {
|
||||
@Parameter(description = "起始日期(yyyy-MM-dd,含)")
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
|
||||
@Parameter(description = "结束日期(yyyy-MM-dd,含)")
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
|
||||
@Parameter(description = "排序:severity=按严重度(默认)/ time=按时间倒序")
|
||||
@RequestParam(required = false, defaultValue = NotificationService.SORT_SEVERITY) String sort) {
|
||||
Long userId = currentAdminId(request);
|
||||
return ApiResponse.success(notificationService.groups(userId, NotificationService.AUDIENCE_ADMIN,
|
||||
NotificationPageQuery.of(page, pageSize, onlyUnread, keyword, category, startDate, endDate)));
|
||||
NotificationPageQuery query = NotificationPageQuery.of(
|
||||
page, pageSize, onlyUnread, keyword, category, startDate, endDate);
|
||||
query.setSort(sort);
|
||||
return ApiResponse.success(notificationService.groups(userId, NotificationService.AUDIENCE_ADMIN, query));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@@ -71,7 +76,8 @@ public class AdminNotificationController {
|
||||
description = "onlyUnread=true 时只返回未读;keyword 模糊匹配标题/内容;"
|
||||
+ "category 按类型大类筛选(system_error/task_error/config_error/system_notice);"
|
||||
+ "startDate/endDate 为年月日闭区间;"
|
||||
+ "scene/day/subjectUserId 三个条件用于展开聚合组、取该组内的明细。")
|
||||
+ "scene/day/subjectUserId 三个条件用于展开聚合组、取该组内的明细;"
|
||||
+ "sort 默认 severity,传 time 则按时间倒序。")
|
||||
public ApiResponse<NotificationPageVo> page(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@@ -89,7 +95,9 @@ public class AdminNotificationController {
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate day,
|
||||
@Parameter(description = "聚合组展开:事件主体用户 id") @RequestParam(required = false) Long subjectUserId,
|
||||
@Parameter(description = "聚合组展开:取「未区分用户」那一组(subject_user_id 为空的存量行)")
|
||||
@RequestParam(required = false, defaultValue = "false") Boolean subjectUnlabelled) {
|
||||
@RequestParam(required = false, defaultValue = "false") Boolean subjectUnlabelled,
|
||||
@Parameter(description = "排序:severity=按严重度(默认)/ time=按时间倒序")
|
||||
@RequestParam(required = false, defaultValue = NotificationService.SORT_SEVERITY) String sort) {
|
||||
Long userId = currentAdminId(request);
|
||||
NotificationPageQuery query = NotificationPageQuery.of(page, pageSize, onlyUnread, keyword, category,
|
||||
startDate, endDate);
|
||||
@@ -97,6 +105,7 @@ public class AdminNotificationController {
|
||||
query.setDay(day);
|
||||
query.setSubjectUserId(subjectUserId);
|
||||
query.setSubjectUnlabelled(subjectUnlabelled);
|
||||
query.setSort(sort);
|
||||
return ApiResponse.success(notificationService.page(userId, NotificationService.AUDIENCE_ADMIN, query));
|
||||
}
|
||||
|
||||
|
||||
+15
-6
@@ -47,7 +47,8 @@ public class NotificationController {
|
||||
@GetMapping("/groups")
|
||||
@Operation(summary = "通知聚合列表(铃铛默认视图)",
|
||||
description = "按「场景 × 自然日」折叠(桌面端的主体用户就是本人,分组键里的用户列恒等于自己)。"
|
||||
+ "total=组数、rowCount=折叠前的明细条数,两个数都要显示。")
|
||||
+ "total=组数、rowCount=折叠前的明细条数,两个数都要显示。"
|
||||
+ "sort 默认 severity(紧急→低危,同档按时间倒序),传 time 则纯时间倒序。")
|
||||
public ApiResponse<NotificationGroupPageVo> groups(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "页码(按组)") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@@ -59,17 +60,22 @@ public class NotificationController {
|
||||
@Parameter(description = "起始日期(yyyy-MM-dd,含)")
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
|
||||
@Parameter(description = "结束日期(yyyy-MM-dd,含)")
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
|
||||
@Parameter(description = "排序:severity=按严重度(默认)/ time=按时间倒序")
|
||||
@RequestParam(required = false, defaultValue = NotificationService.SORT_SEVERITY) String sort) {
|
||||
Long userId = currentUserId(request);
|
||||
return ApiResponse.success(notificationService.groups(userId, NotificationService.AUDIENCE_USER,
|
||||
NotificationPageQuery.of(page, pageSize, onlyUnread, keyword, category, startDate, endDate)));
|
||||
NotificationPageQuery query = NotificationPageQuery.of(
|
||||
page, pageSize, onlyUnread, keyword, category, startDate, endDate);
|
||||
query.setSort(sort);
|
||||
return ApiResponse.success(notificationService.groups(userId, NotificationService.AUDIENCE_USER, query));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "通知分页列表",
|
||||
description = "onlyUnread=true 时只返回未读;keyword 模糊匹配标题/内容;"
|
||||
+ "category 按类型大类筛选(system_error/task_error/config_error/system_notice);"
|
||||
+ "startDate/endDate 为年月日闭区间;scene/day 用于展开聚合组、取该组内的明细。")
|
||||
+ "startDate/endDate 为年月日闭区间;scene/day 用于展开聚合组、取该组内的明细;"
|
||||
+ "sort 默认 severity,传 time 则按时间倒序。")
|
||||
public ApiResponse<NotificationPageVo> page(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@@ -84,12 +90,15 @@ public class NotificationController {
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
|
||||
@Parameter(description = "聚合组展开:场景") @RequestParam(required = false) String scene,
|
||||
@Parameter(description = "聚合组展开:自然日(yyyy-MM-dd)")
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate day) {
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate day,
|
||||
@Parameter(description = "排序:severity=按严重度(默认)/ time=按时间倒序")
|
||||
@RequestParam(required = false, defaultValue = NotificationService.SORT_SEVERITY) String sort) {
|
||||
Long userId = currentUserId(request);
|
||||
NotificationPageQuery query = NotificationPageQuery.of(page, pageSize, onlyUnread, keyword, category,
|
||||
startDate, endDate);
|
||||
query.setScene(scene);
|
||||
query.setDay(day);
|
||||
query.setSort(sort);
|
||||
return ApiResponse.success(notificationService.page(userId, NotificationService.AUDIENCE_USER, query));
|
||||
}
|
||||
|
||||
|
||||
+2
@@ -19,6 +19,8 @@ public class NotificationPageQuery {
|
||||
private String category;
|
||||
private LocalDate startDate;
|
||||
private LocalDate endDate;
|
||||
/** 排序:severity=按严重度(默认,紧急→低危,同档按时间倒序);time=按时间倒序。 */
|
||||
private String sort;
|
||||
/** 聚合组展开:只取该组内的明细,三个条件成对出现(空表示不限制)。 */
|
||||
private String scene;
|
||||
private LocalDate day;
|
||||
|
||||
+2
@@ -19,6 +19,8 @@ public class UserNotificationEntity {
|
||||
private String audience;
|
||||
private String scene;
|
||||
private String level;
|
||||
/** 业务严重度:urgent=紧急/high=高危/medium=中危/low=低危;列表默认按它排序。 */
|
||||
private String severity;
|
||||
private String title;
|
||||
private String content;
|
||||
private String dedupeKey;
|
||||
|
||||
+2
@@ -30,6 +30,8 @@ public class NotificationGroupVo {
|
||||
private Long unreadCount;
|
||||
/** 级别取组内最高(error > warning > info),一组里混进 error 不能被 warning 盖掉。 */
|
||||
private String level;
|
||||
/** 严重度取组内最高(urgent > high > medium > low),列表默认排序依据。 */
|
||||
private String severity;
|
||||
/** 组内最新一条的标题与正文,作为该组的摘要行。 */
|
||||
private String title;
|
||||
private String content;
|
||||
|
||||
+3
-1
@@ -13,8 +13,10 @@ public class NotificationItemVo {
|
||||
private String scene;
|
||||
/** 类型大类(铃铛筛选用):system_error/task_error/config_error/system_notice */
|
||||
private String category;
|
||||
/** 级别:info/warning/error */
|
||||
/** 呈现级别:info/warning/error(老客户端配色继续用它)。 */
|
||||
private String level;
|
||||
/** 业务严重度:urgent/high/medium/low(紧急/高危/中危/低危),列表默认排序依据。 */
|
||||
private String severity;
|
||||
private String title;
|
||||
private String content;
|
||||
/** 是否已读(前端展示用,等价于 readAt 非空) */
|
||||
|
||||
+122
-17
@@ -40,6 +40,15 @@ public class NotificationService {
|
||||
public static final String LEVEL_WARNING = "warning";
|
||||
public static final String LEVEL_ERROR = "error";
|
||||
|
||||
/** 业务严重度:列表默认按 urgent → high → medium → low 排序。 */
|
||||
public static final String SEVERITY_URGENT = "urgent";
|
||||
public static final String SEVERITY_HIGH = "high";
|
||||
public static final String SEVERITY_MEDIUM = "medium";
|
||||
public static final String SEVERITY_LOW = "low";
|
||||
|
||||
public static final String SORT_SEVERITY = "severity";
|
||||
public static final String SORT_TIME = "time";
|
||||
|
||||
public static final String SCENE_SECRET_BALANCE = "secret_balance";
|
||||
public static final String SCENE_SECRET_INVALID = "secret_invalid";
|
||||
public static final String SCENE_TASK_FAILED = "task_failed";
|
||||
@@ -78,6 +87,10 @@ public class NotificationService {
|
||||
private static final int CONTENT_MAX_LENGTH = 512;
|
||||
private static final int DEDUPE_KEY_MAX_LENGTH = 160;
|
||||
|
||||
/** 严重度排序表达式:与 {@link #severityRank} 同一口径,数据库侧分页必须同序。 */
|
||||
private static final String SEVERITY_ORDER_SQL =
|
||||
"CASE severity WHEN 'urgent' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 2 END ASC";
|
||||
|
||||
private final UserNotificationMapper userNotificationMapper;
|
||||
|
||||
/**
|
||||
@@ -109,12 +122,15 @@ public class NotificationService {
|
||||
return false;
|
||||
}
|
||||
String normalizedAudience = normalize(audience).isEmpty() ? AUDIENCE_USER : audience;
|
||||
String normalizedScene = normalize(scene).isEmpty() ? SCENE_SYSTEM : normalize(scene);
|
||||
String normalizedLevel = normalize(level).isEmpty() ? LEVEL_WARNING : normalize(level);
|
||||
UserNotificationEntity row = new UserNotificationEntity();
|
||||
row.setUserId(userId);
|
||||
row.setAudience(normalizedAudience);
|
||||
row.setSubjectUserId(resolveSubjectUserId(normalizedAudience, userId, subjectUserId));
|
||||
row.setScene(normalize(scene).isEmpty() ? SCENE_SYSTEM : scene);
|
||||
row.setLevel(normalize(level).isEmpty() ? LEVEL_WARNING : level);
|
||||
row.setScene(normalizedScene);
|
||||
row.setLevel(normalizedLevel);
|
||||
row.setSeverity(severityOf(normalizedScene, normalizedLevel));
|
||||
row.setTitle(truncate(title, TITLE_MAX_LENGTH));
|
||||
row.setContent(truncate(content == null ? "" : content, CONTENT_MAX_LENGTH));
|
||||
row.setDedupeKey(truncate(key, DEDUPE_KEY_MAX_LENGTH));
|
||||
@@ -126,8 +142,9 @@ public class NotificationService {
|
||||
log.warn("[notification] 推送落库失败 userId={} scene={} err={}", userId, scene, ex.getMessage(), ex);
|
||||
return false;
|
||||
}
|
||||
log.info("[notification] 已推送 id={} userId={} audience={} scene={} level={} title={}",
|
||||
row.getId(), userId, row.getAudience(), row.getScene(), row.getLevel(), row.getTitle());
|
||||
log.info("[notification] 已推送 id={} userId={} audience={} scene={} level={} severity={} title={}",
|
||||
row.getId(), userId, row.getAudience(), row.getScene(), row.getLevel(),
|
||||
row.getSeverity(), row.getTitle());
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -158,11 +175,14 @@ public class NotificationService {
|
||||
if (nextContent.equals(existing.getContent()) && nextTitle.equals(existing.getTitle())) {
|
||||
return false;
|
||||
}
|
||||
String normalizedScene = normalize(scene).isEmpty() ? SCENE_SYSTEM : normalize(scene);
|
||||
String normalizedLevel = normalize(level).isEmpty() ? LEVEL_WARNING : normalize(level);
|
||||
userNotificationMapper.update(null, new LambdaUpdateWrapper<UserNotificationEntity>()
|
||||
.eq(UserNotificationEntity::getId, existing.getId())
|
||||
.set(UserNotificationEntity::getTitle, nextTitle)
|
||||
.set(UserNotificationEntity::getContent, nextContent)
|
||||
.set(UserNotificationEntity::getLevel, normalize(level).isEmpty() ? LEVEL_WARNING : level));
|
||||
.set(UserNotificationEntity::getLevel, normalizedLevel)
|
||||
.set(UserNotificationEntity::getSeverity, severityOf(normalizedScene, normalizedLevel)));
|
||||
log.info("[notification] 同键通知已刷新 id={} userId={} scene={} dedupeKey={}",
|
||||
existing.getId(), userId, scene, key);
|
||||
return true;
|
||||
@@ -192,10 +212,16 @@ public class NotificationService {
|
||||
long total = totalValue == null ? 0L : totalValue;
|
||||
|
||||
long offset = Math.max(0L, (safePage - 1) * safeSize);
|
||||
LambdaQueryWrapper<UserNotificationEntity> listWrapper = baseWrapper(userId, audience, onlyUnread, safe);
|
||||
// 默认按严重度分档、同档内按时间倒序;time=纯时间倒序。分页在 SQL 侧完成,排序必须同源。
|
||||
if (isTimeSort(safe.getSort())) {
|
||||
listWrapper.orderByDesc(UserNotificationEntity::getId)
|
||||
.last("limit " + offset + "," + safeSize);
|
||||
} else {
|
||||
listWrapper.last("ORDER BY " + SEVERITY_ORDER_SQL + ", id DESC limit " + offset + "," + safeSize);
|
||||
}
|
||||
List<UserNotificationEntity> rows = total == 0 ? List.of()
|
||||
: userNotificationMapper.selectList(baseWrapper(userId, audience, onlyUnread, safe)
|
||||
.orderByDesc(UserNotificationEntity::getId)
|
||||
.last("limit " + offset + "," + safeSize));
|
||||
: userNotificationMapper.selectList(listWrapper);
|
||||
|
||||
NotificationPageVo vo = new NotificationPageVo();
|
||||
List<NotificationItemVo> items = new ArrayList<>(rows.size());
|
||||
@@ -207,9 +233,10 @@ public class NotificationService {
|
||||
vo.setPage(safePage);
|
||||
vo.setPageSize(safeSize);
|
||||
vo.setUnreadCount(unreadCount(userId, audience));
|
||||
log.info("[notification] 列表查询 userId={} audience={} page={} size={} onlyUnread={} category={} keyword={} 起={} 止={} 命中={}",
|
||||
log.info("[notification] 列表查询 userId={} audience={} page={} size={} onlyUnread={} category={} keyword={} 起={} 止={} sort={} 命中={}",
|
||||
userId, audience, safePage, safeSize, onlyUnread, normalize(safe.getCategory()),
|
||||
normalize(safe.getKeyword()), safe.getStartDate(), safe.getEndDate(), total);
|
||||
normalize(safe.getKeyword()), safe.getStartDate(), safe.getEndDate(),
|
||||
sortLabel(safe.getSort()), total);
|
||||
return vo;
|
||||
}
|
||||
|
||||
@@ -231,7 +258,8 @@ public class NotificationService {
|
||||
baseWrapper(userId, audience, Boolean.TRUE.equals(safe.getOnlyUnread()), safe)
|
||||
.select(UserNotificationEntity::getId, UserNotificationEntity::getScene,
|
||||
UserNotificationEntity::getSubjectUserId, UserNotificationEntity::getLevel,
|
||||
UserNotificationEntity::getCreatedAt, UserNotificationEntity::getReadAt)
|
||||
UserNotificationEntity::getSeverity, UserNotificationEntity::getCreatedAt,
|
||||
UserNotificationEntity::getReadAt)
|
||||
.orderByDesc(UserNotificationEntity::getId));
|
||||
|
||||
// 行按 id 倒序进来 ⇒ 每组第一次出现就是该组的最新一条(最终展示顺序另见下面显式排序)。
|
||||
@@ -250,6 +278,7 @@ public class NotificationService {
|
||||
group.setRowCount(0L);
|
||||
group.setUnreadCount(0L);
|
||||
group.setLevel(row.getLevel());
|
||||
group.setSeverity(normalizeSeverity(row.getSeverity(), row.getScene(), row.getLevel()));
|
||||
grouped.put(key, group);
|
||||
}
|
||||
group.setRowCount(group.getRowCount() + 1);
|
||||
@@ -259,13 +288,23 @@ public class NotificationService {
|
||||
if (levelRank(row.getLevel()) > levelRank(group.getLevel())) {
|
||||
group.setLevel(row.getLevel());
|
||||
}
|
||||
String rowSeverity = normalizeSeverity(row.getSeverity(), row.getScene(), row.getLevel());
|
||||
if (severityRank(rowSeverity) > severityRank(group.getSeverity())) {
|
||||
group.setSeverity(rowSeverity);
|
||||
}
|
||||
}
|
||||
|
||||
// 展示顺序显式按「自然日倒序 → 组内最新 id 倒序」。不靠"id 大就等于时间新":
|
||||
// 补录、时钟回拨都会让两者倒挂,那样最该看到的一组会被排到最后一页。
|
||||
// 默认「严重度倒序 → 自然日倒序 → 组内最新 id 倒序」;time=纯「自然日倒序 → 最新 id 倒序」。
|
||||
// 不靠"id 大就等于时间新":补录、时钟回拨都会让两者倒挂,那样最该看到的一组会被排到最后一页。
|
||||
List<NotificationGroupVo> all = new ArrayList<>(grouped.values());
|
||||
all.sort(Comparator.comparing(NotificationGroupVo::getDay, Comparator.reverseOrder())
|
||||
.thenComparing(NotificationGroupVo::getLatestId, Comparator.reverseOrder()));
|
||||
Comparator<NotificationGroupVo> timeOrder =
|
||||
Comparator.comparing(NotificationGroupVo::getDay, Comparator.reverseOrder())
|
||||
.thenComparing(NotificationGroupVo::getLatestId, Comparator.reverseOrder());
|
||||
all.sort(isTimeSort(safe.getSort())
|
||||
? timeOrder
|
||||
: Comparator.comparingInt((NotificationGroupVo group) -> severityRank(group.getSeverity()))
|
||||
.reversed()
|
||||
.thenComparing(timeOrder));
|
||||
long offset = Math.max(0L, (safePage - 1) * safeSize);
|
||||
List<NotificationGroupVo> slice = offset >= all.size() ? List.of()
|
||||
: all.subList((int) offset, (int) Math.min(offset + safeSize, all.size()));
|
||||
@@ -279,8 +318,9 @@ public class NotificationService {
|
||||
vo.setPageSize(safeSize);
|
||||
vo.setUnreadGroupCount(unreadGroupCount(userId, audience));
|
||||
vo.setUnreadCount(unreadCount(userId, audience));
|
||||
log.info("[notification] 聚合列表 userId={} audience={} page={} size={} 明细行={} 组数={} 未读组={}",
|
||||
userId, audience, safePage, safeSize, rows.size(), all.size(), vo.getUnreadGroupCount());
|
||||
log.info("[notification] 聚合列表 userId={} audience={} page={} size={} sort={} 明细行={} 组数={} 未读组={}",
|
||||
userId, audience, safePage, safeSize, sortLabel(safe.getSort()),
|
||||
rows.size(), all.size(), vo.getUnreadGroupCount());
|
||||
return vo;
|
||||
}
|
||||
|
||||
@@ -315,6 +355,70 @@ public class NotificationService {
|
||||
return LEVEL_WARNING.equals(level) ? 1 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 业务严重度唯一推导口径:scene 优先,level 只在同 scene 内区分轻重
|
||||
* (secret_balance 的 warning=余量偏低 / error=欠费停服)。
|
||||
* 迁移 V161 的回填 CASE 与此逐条一致,改这里必须同步改迁移注释。
|
||||
*/
|
||||
public static String severityOf(String scene, String level) {
|
||||
String s = normalize(scene);
|
||||
String l = normalize(level);
|
||||
if (SCENE_SERVICE_DOWN.equals(s)) {
|
||||
return SEVERITY_URGENT;
|
||||
}
|
||||
if (SCENE_SECRET_BALANCE.equals(s)) {
|
||||
return LEVEL_ERROR.equals(l) ? SEVERITY_URGENT : SEVERITY_MEDIUM;
|
||||
}
|
||||
if (SCENE_MAIXIANG_ANOMALY.equals(s) || SCENE_SECRET_INVALID.equals(s)
|
||||
|| SCENE_TASK_FAILED.equals(s)) {
|
||||
return SEVERITY_HIGH;
|
||||
}
|
||||
if (SCENE_TASK_PARTIAL.equals(s)) {
|
||||
return SEVERITY_MEDIUM;
|
||||
}
|
||||
if (SCENE_SYSTEM.equals(s)) {
|
||||
return SEVERITY_LOW;
|
||||
}
|
||||
if (LEVEL_ERROR.equals(l)) {
|
||||
return SEVERITY_URGENT;
|
||||
}
|
||||
if (LEVEL_WARNING.equals(l)) {
|
||||
return SEVERITY_HIGH;
|
||||
}
|
||||
if (LEVEL_INFO.equals(l)) {
|
||||
return SEVERITY_LOW;
|
||||
}
|
||||
return SEVERITY_MEDIUM;
|
||||
}
|
||||
|
||||
/** urgent=3 / high=2 / medium=1 / low=0;未知一律按中危。 */
|
||||
public static int severityRank(String severity) {
|
||||
return switch (normalize(severity)) {
|
||||
case SEVERITY_URGENT -> 3;
|
||||
case SEVERITY_HIGH -> 2;
|
||||
case SEVERITY_LOW -> 0;
|
||||
default -> 1;
|
||||
};
|
||||
}
|
||||
|
||||
/** 行上已有合法值时以它为准(允许人工修库);空/非法值回退到 scene+level 推导。 */
|
||||
static String normalizeSeverity(String severity, String scene, String level) {
|
||||
String value = normalize(severity);
|
||||
if (SEVERITY_URGENT.equals(value) || SEVERITY_HIGH.equals(value)
|
||||
|| SEVERITY_MEDIUM.equals(value) || SEVERITY_LOW.equals(value)) {
|
||||
return value;
|
||||
}
|
||||
return severityOf(scene, level);
|
||||
}
|
||||
|
||||
private static boolean isTimeSort(String sort) {
|
||||
return SORT_TIME.equalsIgnoreCase(normalize(sort));
|
||||
}
|
||||
|
||||
private static String sortLabel(String sort) {
|
||||
return isTimeSort(sort) ? SORT_TIME : SORT_SEVERITY;
|
||||
}
|
||||
|
||||
/** 分组键:场景 × 自然日 × 主体用户;subjectUserId 为 null 时所有未标注行自成一组。 */
|
||||
private record GroupKey(String scene, LocalDate day, Long subjectUserId) {
|
||||
}
|
||||
@@ -516,6 +620,7 @@ public class NotificationService {
|
||||
vo.setScene(row.getScene());
|
||||
vo.setCategory(categoryOf(row.getScene()));
|
||||
vo.setLevel(row.getLevel());
|
||||
vo.setSeverity(normalizeSeverity(row.getSeverity(), row.getScene(), row.getLevel()));
|
||||
vo.setTitle(row.getTitle());
|
||||
vo.setContent(row.getContent());
|
||||
vo.setRead(row.getReadAt() != null);
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
-- =============================================================
|
||||
-- 迁移 V161__notification_severity
|
||||
--
|
||||
-- 1. 变更目的:给站内通知补「严重度」一列(2026-10-21 需求)。
|
||||
-- 用户原话:「通知功能优化加个紧急、高危、中危、低危的状态,排序默认按这个排,
|
||||
-- 也可以支持按时间排序 2 种,客户端和后台管理都加」。
|
||||
-- 此前表里只有 `level`(info/warning/error),它是**呈现级别**不是业务严重度:
|
||||
-- task_partial 与 task_failed 都可能是 warning,但前者是交付不完整、后者是任务失败;
|
||||
-- 直接拿 level 当四级严重度会把两者压成同一档。故新增独立列,不回改 level——
|
||||
-- 老客户端的配色/图标按 level 走,改 level 的取值等于把它们一起打碎。
|
||||
--
|
||||
-- 2. 严重度口径(服务端唯一来源 NotificationService.severityOf):
|
||||
-- urgent 紧急:service_down(下游服务停摆)、secret_balance + error(代理欠费)
|
||||
-- high 高危:task_failed、secret_invalid、maixiang_anomaly(任务/密钥/调度异常)
|
||||
-- medium 中危:task_partial、secret_balance + warning(余量偏低)
|
||||
-- low 低危:system(普通系统通知)
|
||||
-- 未登记 scene 兜底:error→urgent、warning→high、info→low、其余 medium。
|
||||
--
|
||||
-- 3. 存量回填:按 scene + level 推导(与 Java 侧同一张表),不拿正则解析历史文案。
|
||||
-- 只回填空值/空串/默认值 medium 的行;已经是 urgent/high/low 的行不动。
|
||||
--
|
||||
-- 4. 锁表风险:低。带 DEFAULT 的 ADD COLUMN 在 MySQL 8 走 INSTANT(不重建表)。
|
||||
-- 刻意不加二级索引:查询过滤条件恒为 user_id + audience,V116 的
|
||||
-- idx_user_audience_read 已覆盖;严重度只有四个值,宽索引买不到排序收益。
|
||||
--
|
||||
-- 5. 验证 SQL(迁移后跑,不许只看启动日志的 Successfully applied):
|
||||
-- SHOW COLUMNS FROM `biz_user_notification` LIKE 'severity';
|
||||
-- -> 期望 1 行:Type=varchar(16),Null=NO,Default=medium
|
||||
-- SELECT severity, COUNT(*) FROM biz_user_notification GROUP BY severity;
|
||||
-- -> 期望只出现 urgent/high/medium/low 四个值
|
||||
-- SELECT id, scene, level, severity FROM biz_user_notification ORDER BY id DESC LIMIT 10;
|
||||
-- -> 抽查:service_down 应为 urgent,task_failed 应为 high,system 应为 low
|
||||
--
|
||||
-- 6. 可重跑性:照 V146/V155/V157/V158 惯例,加列前先查 information_schema;
|
||||
-- 迁移中途失败时 flyway repair + 重启会从第一条语句重跑,裸 ADD COLUMN 会撞 1060。
|
||||
-- 回填语句本身幂等(只改 medium/空值,重算结果相同)。
|
||||
--
|
||||
-- 7. 回滚(人工补丁,写成注释以免被 Flyway 当迁移执行):
|
||||
-- ALTER TABLE `biz_user_notification` DROP COLUMN `severity`;
|
||||
-- 仅回滚 jar 不需要 DROP:旧 jar 的实体没有这一列,INSERT 不会写它。
|
||||
-- =============================================================
|
||||
|
||||
SET @has_col := (
|
||||
SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'biz_user_notification'
|
||||
AND COLUMN_NAME = 'severity'
|
||||
);
|
||||
SET @ddl := IF(@has_col = 0,
|
||||
'ALTER TABLE `biz_user_notification` ADD COLUMN `severity` varchar(16) NOT NULL DEFAULT ''medium'' COMMENT ''严重度:urgent=紧急/high=高危/medium=中危/low=低危'' AFTER `level`',
|
||||
'SELECT ''biz_user_notification.severity already exists, skipped'' AS note');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
UPDATE `biz_user_notification`
|
||||
SET `severity` = CASE
|
||||
WHEN `scene` = 'service_down' THEN 'urgent'
|
||||
WHEN `scene` = 'secret_balance' AND `level` = 'error' THEN 'urgent'
|
||||
WHEN `scene` IN ('maixiang_anomaly', 'secret_invalid', 'task_failed') THEN 'high'
|
||||
WHEN `scene` IN ('task_partial', 'secret_balance') THEN 'medium'
|
||||
WHEN `scene` = 'system' THEN 'low'
|
||||
WHEN `level` = 'error' THEN 'urgent'
|
||||
WHEN `level` = 'warning' THEN 'high'
|
||||
WHEN `level` = 'info' THEN 'low'
|
||||
ELSE 'medium'
|
||||
END
|
||||
WHERE `severity` IS NULL OR `severity` = '' OR `severity` = 'medium';
|
||||
+5
-3
@@ -37,7 +37,7 @@ class AdminNotificationControllerTest {
|
||||
controller.summary(request);
|
||||
controller.page(request, 1L, 20L, false, "余额", NotificationService.CATEGORY_CONFIG_ERROR,
|
||||
LocalDate.of(2026, 9, 10), LocalDate.of(2026, 9, 13),
|
||||
"task_partial", LocalDate.of(2026, 9, 12), 1160L, false);
|
||||
"task_partial", LocalDate.of(2026, 9, 12), 1160L, false, NotificationService.SORT_TIME);
|
||||
|
||||
verify(notificationService).summary(24L, NotificationService.AUDIENCE_ADMIN);
|
||||
ArgumentCaptor<NotificationPageQuery> queryCaptor = ArgumentCaptor.forClass(NotificationPageQuery.class);
|
||||
@@ -55,6 +55,7 @@ class AdminNotificationControllerTest {
|
||||
assertThat(query.getDay()).isEqualTo(LocalDate.of(2026, 9, 12));
|
||||
assertThat(query.getSubjectUserId()).isEqualTo(1160L);
|
||||
assertThat(query.getSubjectUnlabelled()).isFalse();
|
||||
assertThat(query.getSort()).isEqualTo(NotificationService.SORT_TIME);
|
||||
}
|
||||
|
||||
/** 聚合视图与单条列表读的是同一份"谁的副本",这里守 groups 这条新出口别绕过管理员维度。 */
|
||||
@@ -62,10 +63,11 @@ class AdminNotificationControllerTest {
|
||||
void groupsUseOperatorIdAndAdminAudience() {
|
||||
when(adminAuthSupport.requireConsoleOperator(request)).thenReturn(admin(24L));
|
||||
|
||||
controller.groups(request, 1L, 20L, false, null, null, null, null);
|
||||
controller.groups(request, 1L, 20L, false, null, null, null, null, NotificationService.SORT_SEVERITY);
|
||||
|
||||
verify(notificationService).groups(eq(24L), eq(NotificationService.AUDIENCE_ADMIN),
|
||||
argThat(query -> query.getPage().equals(1L) && query.getPageSize().equals(20L)));
|
||||
argThat(query -> query.getPage().equals(1L) && query.getPageSize().equals(20L)
|
||||
&& NotificationService.SORT_SEVERITY.equals(query.getSort())));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+2
-1
@@ -35,7 +35,7 @@ class NotificationControllerTest {
|
||||
controller.summary(request);
|
||||
controller.page(request, 2L, 20L, true, "欠费", NotificationService.CATEGORY_TASK_ERROR,
|
||||
LocalDate.of(2026, 9, 1), LocalDate.of(2026, 9, 13),
|
||||
"task_failed", LocalDate.of(2026, 9, 5));
|
||||
"task_failed", LocalDate.of(2026, 9, 5), NotificationService.SORT_TIME);
|
||||
|
||||
verify(notificationService).summary(1095L, NotificationService.AUDIENCE_USER);
|
||||
ArgumentCaptor<NotificationPageQuery> queryCaptor = ArgumentCaptor.forClass(NotificationPageQuery.class);
|
||||
@@ -50,6 +50,7 @@ class NotificationControllerTest {
|
||||
assertThat(query.getEndDate()).isEqualTo(LocalDate.of(2026, 9, 13));
|
||||
assertThat(query.getScene()).isEqualTo("task_failed");
|
||||
assertThat(query.getDay()).isEqualTo(LocalDate.of(2026, 9, 5));
|
||||
assertThat(query.getSort()).isEqualTo(NotificationService.SORT_TIME);
|
||||
// 桌面端的主体用户就是本人,接口不暴露 subjectUserId,展开只靠 场景+自然日
|
||||
assertThat(query.getSubjectUserId()).isNull();
|
||||
}
|
||||
|
||||
+27
@@ -156,6 +156,33 @@ class NotificationGroupTest {
|
||||
List.of(headline(6, "t", "c")));
|
||||
|
||||
assertThat(groups().getGroups().get(0).getLevel()).isEqualTo("error");
|
||||
// 严重度同样取组内最高:service_down 不论 level 都是紧急
|
||||
assertThat(groups().getGroups().get(0).getSeverity())
|
||||
.isEqualTo(NotificationService.SEVERITY_URGENT);
|
||||
}
|
||||
|
||||
/** 默认按严重度:高危组即使更旧也排在中危组前面;切 time 才回到自然日倒序。 */
|
||||
@Test
|
||||
void defaultGroupOrderPutsHigherSeverityFirstAndTimeSortRestoresDayOrder() {
|
||||
stub(List.of(
|
||||
row(9, "task_partial", 1160L, LocalDate.of(2026, 10, 13), "warning", null),
|
||||
row(8, "task_failed", 1160L, LocalDate.of(2026, 10, 12), "warning", null)),
|
||||
List.of(headline(9, "t", "c"), headline(8, "t", "c")));
|
||||
|
||||
NotificationGroupPageVo bySeverity = groups();
|
||||
assertThat(bySeverity.getGroups()).extracting(NotificationGroupVo::getScene)
|
||||
.containsExactly("task_failed", "task_partial");
|
||||
assertThat(bySeverity.getGroups()).extracting(NotificationGroupVo::getSeverity)
|
||||
.containsExactly(NotificationService.SEVERITY_HIGH, NotificationService.SEVERITY_MEDIUM);
|
||||
|
||||
NotificationPageQuery timeQuery = new NotificationPageQuery();
|
||||
timeQuery.setSort(NotificationService.SORT_TIME);
|
||||
NotificationGroupPageVo byTime = service.groups(24L, NotificationService.AUDIENCE_ADMIN, timeQuery);
|
||||
|
||||
assertThat(byTime.getGroups()).extracting(NotificationGroupVo::getScene)
|
||||
.containsExactly("task_partial", "task_failed");
|
||||
assertThat(byTime.getGroups()).extracting(NotificationGroupVo::getDay)
|
||||
.containsExactly(LocalDate.of(2026, 10, 13), LocalDate.of(2026, 10, 12));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+91
@@ -70,6 +70,7 @@ class NotificationServiceTest {
|
||||
assertThat(row.getAudience()).isEqualTo("user");
|
||||
assertThat(row.getScene()).isEqualTo("secret_balance");
|
||||
assertThat(row.getLevel()).isEqualTo("error");
|
||||
assertThat(row.getSeverity()).isEqualTo(NotificationService.SEVERITY_URGENT);
|
||||
assertThat(row.getTitle()).isEqualTo("代理欠费");
|
||||
assertThat(row.getContent()).isEqualTo("余额不足");
|
||||
assertThat(row.getDedupeKey()).isEqualTo("secret_balance:7:proxy:20260913");
|
||||
@@ -335,6 +336,96 @@ class NotificationServiceTest {
|
||||
.isEqualTo(NotificationService.CATEGORY_CONFIG_ERROR);
|
||||
}
|
||||
|
||||
/** 列表项还必须带严重度:后端是唯一推导源,前端不再各自按 scene/level 猜。 */
|
||||
@Test
|
||||
void pageItemsCarrySeverity() {
|
||||
UserNotificationEntity row = new UserNotificationEntity();
|
||||
row.setId(9L);
|
||||
row.setScene(NotificationService.SCENE_TASK_FAILED);
|
||||
row.setLevel(NotificationService.LEVEL_WARNING);
|
||||
when(mapper.selectCount(any())).thenReturn(1L, 0L);
|
||||
when(mapper.selectList(any())).thenReturn(List.of(row));
|
||||
|
||||
NotificationPageVo page = service.page(7L, NotificationService.AUDIENCE_USER,
|
||||
NotificationPageQuery.of(1L, 20L, false, null, null, null, null));
|
||||
|
||||
assertThat(page.getItems().get(0).getSeverity())
|
||||
.isEqualTo(NotificationService.SEVERITY_HIGH);
|
||||
}
|
||||
|
||||
/** 四级严重度的唯一推导口径:scene 优先,level 区分同场景轻重。 */
|
||||
@Test
|
||||
void severityMapsScenesAndLevelsToFourBands() {
|
||||
assertThat(NotificationService.severityOf(NotificationService.SCENE_SERVICE_DOWN,
|
||||
NotificationService.LEVEL_WARNING)).isEqualTo(NotificationService.SEVERITY_URGENT);
|
||||
assertThat(NotificationService.severityOf(NotificationService.SCENE_SECRET_BALANCE,
|
||||
NotificationService.LEVEL_ERROR)).isEqualTo(NotificationService.SEVERITY_URGENT);
|
||||
assertThat(NotificationService.severityOf(NotificationService.SCENE_SECRET_BALANCE,
|
||||
NotificationService.LEVEL_WARNING)).isEqualTo(NotificationService.SEVERITY_MEDIUM);
|
||||
assertThat(NotificationService.severityOf(NotificationService.SCENE_TASK_FAILED,
|
||||
NotificationService.LEVEL_WARNING)).isEqualTo(NotificationService.SEVERITY_HIGH);
|
||||
assertThat(NotificationService.severityOf(NotificationService.SCENE_SECRET_INVALID,
|
||||
NotificationService.LEVEL_WARNING)).isEqualTo(NotificationService.SEVERITY_HIGH);
|
||||
assertThat(NotificationService.severityOf(NotificationService.SCENE_MAIXIANG_ANOMALY,
|
||||
NotificationService.LEVEL_WARNING)).isEqualTo(NotificationService.SEVERITY_HIGH);
|
||||
assertThat(NotificationService.severityOf(NotificationService.SCENE_TASK_PARTIAL,
|
||||
NotificationService.LEVEL_WARNING)).isEqualTo(NotificationService.SEVERITY_MEDIUM);
|
||||
assertThat(NotificationService.severityOf(NotificationService.SCENE_SYSTEM,
|
||||
NotificationService.LEVEL_INFO)).isEqualTo(NotificationService.SEVERITY_LOW);
|
||||
// 未登记 scene 不让通知失去分档:按 level 兜底
|
||||
assertThat(NotificationService.severityOf("legacy_scene", NotificationService.LEVEL_ERROR))
|
||||
.isEqualTo(NotificationService.SEVERITY_URGENT);
|
||||
assertThat(NotificationService.severityOf("legacy_scene", NotificationService.LEVEL_INFO))
|
||||
.isEqualTo(NotificationService.SEVERITY_LOW);
|
||||
assertThat(NotificationService.severityOf(null, null))
|
||||
.isEqualTo(NotificationService.SEVERITY_MEDIUM);
|
||||
assertThat(NotificationService.severityRank(NotificationService.SEVERITY_URGENT))
|
||||
.isGreaterThan(NotificationService.severityRank(NotificationService.SEVERITY_HIGH));
|
||||
assertThat(NotificationService.severityRank(NotificationService.SEVERITY_HIGH))
|
||||
.isGreaterThan(NotificationService.severityRank(NotificationService.SEVERITY_MEDIUM));
|
||||
assertThat(NotificationService.severityRank(NotificationService.SEVERITY_MEDIUM))
|
||||
.isGreaterThan(NotificationService.severityRank(NotificationService.SEVERITY_LOW));
|
||||
}
|
||||
|
||||
/** 默认排序必须在 SQL 侧按严重度分档;分页不能先按 id 取一页再在内存里排。 */
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void pageDefaultSortUsesSeverityCase() {
|
||||
when(mapper.selectCount(any())).thenReturn(1L, 0L);
|
||||
when(mapper.selectList(any())).thenReturn(List.of());
|
||||
|
||||
service.page(7L, NotificationService.AUDIENCE_USER,
|
||||
NotificationPageQuery.of(1L, 20L, false, null, null, null, null));
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper<UserNotificationEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
|
||||
verify(mapper).selectList(captor.capture());
|
||||
assertThat(captor.getValue().getSqlSegment())
|
||||
.contains("CASE severity")
|
||||
.contains("'urgent'")
|
||||
.contains("'low'");
|
||||
}
|
||||
|
||||
/** 切到时间排序时不能再套严重度 CASE,否则「按时间」只是同一档内的局部排序。 */
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void pageTimeSortDoesNotUseSeverityCase() {
|
||||
when(mapper.selectCount(any())).thenReturn(1L, 0L);
|
||||
when(mapper.selectList(any())).thenReturn(List.of());
|
||||
NotificationPageQuery query = NotificationPageQuery.of(1L, 20L, false, null, null, null, null);
|
||||
query.setSort(NotificationService.SORT_TIME);
|
||||
|
||||
service.page(7L, NotificationService.AUDIENCE_USER, query);
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper<UserNotificationEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
|
||||
verify(mapper).selectList(captor.capture());
|
||||
assertThat(captor.getValue().getSqlSegment())
|
||||
.doesNotContain("CASE severity")
|
||||
.contains("ORDER BY")
|
||||
.contains("id DESC");
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void summaryAndUnreadCountScopeByReceiverAndAudience() {
|
||||
|
||||
Reference in New Issue
Block a user