feat(通知): 四级严重度与严重度/时间双排序,客户端与后台管理同步

通知表新增 severity(紧急/高危/中危/低危,V161),由 scene + level 推导且
不回改 level:老客户端配色不受影响,secret_balance 的余量偏低与欠费也能分档。
列表与聚合接口默认按严重度倒序(同档按时间倒序),sort=time 切纯时间排序;
聚合组取组内最高严重度。两端铃铛加彩色等级标签与排序切换,展开明细沿用
同一排序,严重度排序下隐藏会跨天误导的日期头。
This commit is contained in:
2026-10-21 13:33:07 +08:00
parent f6aa04d0f2
commit 86d78160fd
23 changed files with 804 additions and 40 deletions
@@ -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));
}
@@ -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));
}
@@ -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;
@@ -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;
@@ -30,6 +30,8 @@ public class NotificationGroupVo {
private Long unreadCount;
/** 级别取组内最高(error &gt; warning &gt; info),一组里混进 error 不能被 warning 盖掉。 */
private String level;
/** 严重度取组内最高(urgent &gt; high &gt; medium &gt; low),列表默认排序依据。 */
private String severity;
/** 组内最新一条的标题与正文,作为该组的摘要行。 */
private String title;
private String content;
@@ -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 非空) */
@@ -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);