feat(通知): 列表按 场景×自然日×主体用户 聚合成两级,红点按组数亮而明细条数同屏;后管日期面板不再被弹窗压住

V158 给 biz_user_notification 加 subject_user_id(事件主体用户,与收件人 user_id 分家):
一行通知是给某个收件人看的,被通知的那个 uid 原先只活在文案字符串里,没有列就没法按用户成组,
也不肯用正则去解历史文案凑分组键。存量不回填(定案)⇒ 老行 subject_user_id 为 NULL,自成「未标注主体」一组。
写入侧 pushOrRefresh 第 8 参带主体,AUDIENCE_USER 时主体=收件人(故新增 7 参便捷档,68 处调用一行没改);
pushToAdminsAnyOf 传 null 并注明理由:一把密钥被 N 个账号共用,不挑一个 uid 冒充。

新增 GET /api/notifications/groups 与 /api/admin/notifications/groups:Java 侧分组(复用 baseWrapper 一份筛选实现),
分页按组切,同屏返回 total=组数 与 rowCount=明细条数;unreadGroupCount 走
COUNT(DISTINCT scene, DATE(created_at), IFNULL(subject_user_id,-1)) —— IFNULL 不能省,
MySQL 的 COUNT(DISTINCT a,b,c) 会跳过任一表达式为 NULL 的行,不兜就把存量那一组整个数没。
红点是新增 unreadGroupCount 而不动 unreadCount 语义:已装机老客户端读 unreadCount 画徽标,
换语义会让老客户端出现「红点 3、列表 217 条」对不上。

铃铛两级(后管+桌面各一份):聚合行点击只展开、不替用户标已读,已读必须进明细逐条点;
明细一次最多 50 条,超出显示「另有 N 条未列出」;下钻带 scene+day+subjectUserId(主体为空改下发
subjectUnlabelled 旗标走 IS NULL),少一维就会把同场景同天别主体的行混进这一组的明细——桌面端最初就漏了这一维。
死码随两级视图退场:groupNotificationsByDay/NotificationDayGroup 删掉,用例换成 formatDayLabel/notificationGroupKey/formatGroupCounts。

后管日期选择面板 z-index 抬到 3300(面板 3200)之上:Element 弹层只自 2000 起递增,不抬就被面板压住,表现为「日期点不动」。
playwright 加 E2E_PORT+strictPort:实测 5174/5176 被别的项目的 vite 占着,reuseExistingServer 让 e2e 连上别人的应用,
当时 5 条全红是端口归属问题而不是回归。

验证=后端通知面 66/66(-Dtest='Notification*' 63 + AdminNotificationControllerTest 3)BUILD SUCCESS;
后管 node --test 1819/1819、真浏览器 e2e 10/10(含遮挡与「展开只取本组」);
桌面 node --test 834/834、组件挂载 vitest 8/8;两前端 vue-tsc --noEmit rc=0;ops 值班侧 18/18。
记账三处=后管 source-pin 逐文件基线 notification-bell.test.ts 用例 6→7(该文件钉子仍 0,占比不动);
桌面 catch 棘轮 blocks 298→299(新增那支是 toggleGroup 明细失败写进面板 loadError,非静默,silent 84 一格没涨);
桌面 endpoints 台账补 /api/notifications/groups。
变异自证 7 条全 KILLED:红点按条数/组内没读完就减组数/聚合行直接标已读/明细截断不报数/下钻丢主体/
丢 IS NULL 旗标/null 主体当值下发。其中「组内没读完就减组数」第一轮 SURVIVED——用例只钉了徽标,
而徽标在 unreadGroupCount 归零时会退回条数兜底,把这条回归盖住了;改成同时钉「N 组未读」chip 才杀掉。

已知盲区(下次补,别当已验):①桌面两级只在 happy-dom 跑过真组件,布局与层级没在真浏览器点过
(桌面日期弹层的层级修复本就在 HEAD 里,不是这批引入);②后管 e2e 夹具没有 subjectUserId=null 的行,
「存量自成一组」在后管 UI 层没被点过,只有后端 WHERE 与桌面组件各一条用例钉着。
This commit is contained in:
2026-10-13 08:34:18 +08:00
parent 1e3bcc9688
commit 5d2a1c6974
31 changed files with 1938 additions and 344 deletions
@@ -4,6 +4,7 @@ import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.api.PageDefaults;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.notification.model.dto.NotificationPageQuery;
import com.nanri.aiimage.modules.notification.model.vo.NotificationGroupPageVo;
import com.nanri.aiimage.modules.notification.model.vo.NotificationPageVo;
import com.nanri.aiimage.modules.notification.model.vo.NotificationSummaryVo;
import com.nanri.aiimage.modules.notification.service.NotificationService;
@@ -43,11 +44,34 @@ public class AdminNotificationController {
return ApiResponse.success(notificationService.summary(userId, NotificationService.AUDIENCE_ADMIN));
}
@GetMapping("/groups")
@Operation(summary = "通知聚合列表(铃铛默认视图)",
description = "按「场景 × 自然日 × 事件主体用户」折叠,分页按组切。"
+ "返回 total=组数、rowCount=同条件下折叠前的明细条数,两个数都要显示,"
+ "否则「共 12 条」会被读成只有 12 条通知。筛选条件与单条列表共用一套实现。")
public ApiResponse<NotificationGroupPageVo> groups(
HttpServletRequest request,
@Parameter(description = "页码(按组)") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
@Parameter(description = "每页组数") @RequestParam(defaultValue = PageDefaults.ADMIN_LIST_PAGE_SIZE) Long pageSize,
@Parameter(description = "只看未读") @RequestParam(required = false, defaultValue = "false") Boolean onlyUnread,
@Parameter(description = "关键字(标题/内容)") @RequestParam(required = false) String keyword,
@Parameter(description = "类型大类:system_error/task_error/config_error/system_notice")
@RequestParam(required = false) String category,
@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) {
Long userId = currentAdminId(request);
return ApiResponse.success(notificationService.groups(userId, NotificationService.AUDIENCE_ADMIN,
NotificationPageQuery.of(page, pageSize, onlyUnread, keyword, category, startDate, endDate)));
}
@GetMapping
@Operation(summary = "通知分页列表",
description = "onlyUnread=true 时只返回未读;keyword 模糊匹配标题/内容;"
+ "category 按类型大类筛选(system_error/task_error/config_error/system_notice);"
+ "startDate/endDate 为年月日闭区间。")
+ "startDate/endDate 为年月日闭区间;"
+ "scene/day/subjectUserId 三个条件用于展开聚合组、取该组内的明细。")
public ApiResponse<NotificationPageVo> page(
HttpServletRequest request,
@Parameter(description = "页码") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
@@ -59,10 +83,21 @@ 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 = "聚合组展开:场景") @RequestParam(required = false) String scene,
@Parameter(description = "聚合组展开:自然日(yyyy-MM-dd)")
@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) {
Long userId = currentAdminId(request);
return ApiResponse.success(notificationService.page(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.setScene(scene);
query.setDay(day);
query.setSubjectUserId(subjectUserId);
query.setSubjectUnlabelled(subjectUnlabelled);
return ApiResponse.success(notificationService.page(userId, NotificationService.AUDIENCE_ADMIN, query));
}
@PostMapping("/{id}/read")
@@ -4,6 +4,7 @@ import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.api.PageDefaults;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.notification.model.dto.NotificationPageQuery;
import com.nanri.aiimage.modules.notification.model.vo.NotificationGroupPageVo;
import com.nanri.aiimage.modules.notification.model.vo.NotificationPageVo;
import com.nanri.aiimage.modules.notification.model.vo.NotificationSummaryVo;
import com.nanri.aiimage.modules.notification.service.NotificationService;
@@ -43,11 +44,32 @@ public class NotificationController {
return ApiResponse.success(notificationService.summary(userId, NotificationService.AUDIENCE_USER));
}
@GetMapping("/groups")
@Operation(summary = "通知聚合列表(铃铛默认视图)",
description = "按「场景 × 自然日」折叠(桌面端的主体用户就是本人,分组键里的用户列恒等于自己)。"
+ "total=组数、rowCount=折叠前的明细条数,两个数都要显示。")
public ApiResponse<NotificationGroupPageVo> groups(
HttpServletRequest request,
@Parameter(description = "页码(按组)") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
@Parameter(description = "每页组数") @RequestParam(defaultValue = PageDefaults.ADMIN_LIST_PAGE_SIZE) Long pageSize,
@Parameter(description = "只看未读") @RequestParam(required = false, defaultValue = "false") Boolean onlyUnread,
@Parameter(description = "关键字(标题/内容)") @RequestParam(required = false) String keyword,
@Parameter(description = "类型大类:system_error/task_error/config_error/system_notice")
@RequestParam(required = false) String category,
@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) {
Long userId = currentUserId(request);
return ApiResponse.success(notificationService.groups(userId, NotificationService.AUDIENCE_USER,
NotificationPageQuery.of(page, pageSize, onlyUnread, keyword, category, startDate, endDate)));
}
@GetMapping
@Operation(summary = "通知分页列表",
description = "onlyUnread=true 时只返回未读;keyword 模糊匹配标题/内容;"
+ "category 按类型大类筛选(system_error/task_error/config_error/system_notice);"
+ "startDate/endDate 为年月日闭区间。")
+ "startDate/endDate 为年月日闭区间;scene/day 用于展开聚合组、取该组内的明细。")
public ApiResponse<NotificationPageVo> page(
HttpServletRequest request,
@Parameter(description = "页码") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
@@ -59,10 +81,16 @@ 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 = "聚合组展开:场景") @RequestParam(required = false) String scene,
@Parameter(description = "聚合组展开:自然日(yyyy-MM-dd)")
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate day) {
Long userId = currentUserId(request);
return ApiResponse.success(notificationService.page(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.setScene(scene);
query.setDay(day);
return ApiResponse.success(notificationService.page(userId, NotificationService.AUDIENCE_USER, query));
}
@PostMapping("/{id}/read")
@@ -19,6 +19,12 @@ public class NotificationPageQuery {
private String category;
private LocalDate startDate;
private LocalDate endDate;
/** 聚合组展开:只取该组内的明细,三个条件成对出现(空表示不限制)。 */
private String scene;
private LocalDate day;
private Long subjectUserId;
/** true 表示"按 subjectUserId IS NULL 过滤"(未区分用户那一组),与 subjectUserId 互斥。 */
private Boolean subjectUnlabelled;
public static NotificationPageQuery of(Long page, Long pageSize, Boolean onlyUnread,
String keyword, String category,
@@ -14,6 +14,8 @@ public class UserNotificationEntity {
@TableId(type = IdType.AUTO)
private Long id;
private Long userId;
/** 事件主体用户:管理员行=这件事关于谁,桌面端行=本人;null=存量未标注或主体不唯一。 */
private Long subjectUserId;
private String audience;
private String scene;
private String level;
@@ -0,0 +1,26 @@
package com.nanri.aiimage.modules.notification.model.vo;
import lombok.Data;
import java.util.List;
/**
* 通知聚合分页结果。{@code total} 是**组数**(分页按组切),
* {@code rowCount} 是这些筛选条件下的明细条数——两个数必须同屏,
* 否则「共 12 条」会被读成"只有 12 条通知",而那是 12 组、展开是 217 条。
*/
@Data
public class NotificationGroupPageVo {
private List<NotificationGroupVo> groups;
/** 组数(分页分母)。 */
private Long total;
/** 明细条数(同一批筛选条件下折叠前的行数)。 */
private Long rowCount;
private Long page;
private Long pageSize;
/** 有未读的组数(新前端红点用它)。 */
private Long unreadGroupCount;
/** 未读明细条数(与单条列表口径一致,老客户端读的就是这个数)。 */
private Long unreadCount;
}
@@ -0,0 +1,37 @@
package com.nanri.aiimage.modules.notification.model.vo;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
/**
* 通知聚合组:一个「场景 × 自然日 × 主体用户」折成一行。
*
* <p>分组键里的 subjectUserId 对桌面端恒等于收件人本人;对后台管理员是「这件事关于谁」
* (V158 补的列)。存量行没有这一列 ⇒ 全部落进 subjectUserId=null 的那一组,
* 界面上显示成「未区分用户」,展开仍能看到明细——这是"不回填"口径的可见代价,
* 不拿正则去解析历史文案凑分组键(措辞改过形的行会静默漏归)。
*/
@Data
public class NotificationGroupVo {
/** 组内最新一条的 id,作为该组在列表里的锚点(展开明细、去重都按它定位)。 */
private Long latestId;
private String scene;
/** 类型大类,沿用单条的归类口径(铃铛筛选按它走)。 */
private String category;
private LocalDate day;
/** 事件主体用户;null=存量未标注或主体不唯一(服务级故障、一把密钥被多账号共用)。 */
private Long subjectUserId;
/** 组内条数(明细总数)。 */
private Long rowCount;
/** 组内未读条数;&gt;0 即该组计为一个未读组。 */
private Long unreadCount;
/** 级别取组内最高(error &gt; warning &gt; info),一组里混进 error 不能被 warning 盖掉。 */
private String level;
/** 组内最新一条的标题与正文,作为该组的摘要行。 */
private String title;
private String content;
private LocalDateTime createdAt;
}
@@ -7,5 +7,7 @@ import lombok.Data;
public class NotificationSummaryVo {
private Long unreadCount;
/** 有未读的聚合组数;新前端徽标用它。unreadCount 保持"条数"不变,是为了老客户端。 */
private Long unreadGroupCount;
private Long latestId;
}
@@ -65,7 +65,7 @@ public class NotificationDispatchService {
}
String key = dedupeKeyBase + ":" + admin.getId();
if (notificationService.pushOrRefresh(admin.getId(), NotificationService.AUDIENCE_ADMIN,
scene, level, title, content, key)) {
scene, level, title, content, key, subjectUserId)) {
pushed++;
}
}
@@ -95,8 +95,9 @@ public class NotificationDispatchService {
filtered++;
continue;
}
// 主体不唯一(一把密钥被 N 个账号共用),不挑一个 uid 冒充:留 null,聚合时自成一组
if (notificationService.pushOrRefresh(admin.getId(), NotificationService.AUDIENCE_ADMIN,
scene, level, title, content, dedupeKeyBase + ":" + admin.getId())) {
scene, level, title, content, dedupeKeyBase + ":" + admin.getId(), null)) {
pushed++;
}
}
@@ -1,10 +1,13 @@
package com.nanri.aiimage.modules.notification.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.modules.notification.mapper.UserNotificationMapper;
import com.nanri.aiimage.modules.notification.model.dto.NotificationPageQuery;
import com.nanri.aiimage.modules.notification.model.entity.UserNotificationEntity;
import com.nanri.aiimage.modules.notification.model.vo.NotificationGroupPageVo;
import com.nanri.aiimage.modules.notification.model.vo.NotificationGroupVo;
import com.nanri.aiimage.modules.notification.model.vo.NotificationItemVo;
import com.nanri.aiimage.modules.notification.model.vo.NotificationPageVo;
import com.nanri.aiimage.modules.notification.model.vo.NotificationSummaryVo;
@@ -12,8 +15,12 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -74,11 +81,23 @@ public class NotificationService {
private final UserNotificationMapper userNotificationMapper;
/**
* 推送一条通知。dedupeKey 非空且库中已存在同键记录时跳过(返回 false),
* 用于「同一异常在时间窗内只提醒一次」;dedupeKey 为空则不去重。
* 桌面端行的便捷档:收件人就是事件主体,不必每个调用点重复传一遍。
* 管理员行**不能**走这里——那样会把管理员自己的 id 写成主体,聚合时每个管理员
* 各成一组、且永远看不到"这件事关于谁"。
*/
public boolean push(Long userId, String audience, String scene, String level,
String title, String content, String dedupeKey) {
return push(userId, audience, scene, level, title, content, dedupeKey, null);
}
/**
* 推送一条通知。dedupeKey 非空且库中已存在同键记录时跳过(返回 false),
* 用于「同一异常在时间窗内只提醒一次」;dedupeKey 为空则不去重。
*
* @param subjectUserId 事件主体用户;桌面端行传 null 即可(收件人就是主体,见 {@link #resolveSubjectUserId})
*/
public boolean push(Long userId, String audience, String scene, String level,
String title, String content, String dedupeKey, Long subjectUserId) {
if (userId == null || userId <= 0) {
log.warn("[notification] 推送被跳过:接收者无效 userId={} scene={}", userId, scene);
return false;
@@ -89,9 +108,11 @@ public class NotificationService {
userId, audience, scene, key);
return false;
}
String normalizedAudience = normalize(audience).isEmpty() ? AUDIENCE_USER : audience;
UserNotificationEntity row = new UserNotificationEntity();
row.setUserId(userId);
row.setAudience(normalize(audience).isEmpty() ? AUDIENCE_USER : audience);
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.setTitle(truncate(title, TITLE_MAX_LENGTH));
@@ -119,13 +140,18 @@ public class NotificationService {
*/
public boolean pushOrRefresh(Long userId, String audience, String scene, String level,
String title, String content, String dedupeKey) {
return pushOrRefresh(userId, audience, scene, level, title, content, dedupeKey, null);
}
public boolean pushOrRefresh(Long userId, String audience, String scene, String level,
String title, String content, String dedupeKey, Long subjectUserId) {
String key = normalize(dedupeKey);
if (key.isEmpty()) {
return push(userId, audience, scene, level, title, content, key);
return push(userId, audience, scene, level, title, content, key, subjectUserId);
}
UserNotificationEntity existing = selectByDedupeKey(key);
if (existing == null) {
return push(userId, audience, scene, level, title, content, key);
return push(userId, audience, scene, level, title, content, key, subjectUserId);
}
String nextTitle = truncate(title, TITLE_MAX_LENGTH);
String nextContent = truncate(content == null ? "" : content, CONTENT_MAX_LENGTH);
@@ -142,6 +168,18 @@ public class NotificationService {
return true;
}
/**
* 事件主体用户:桌面端行的收件人就是主体本人,不必让每个写入点各传一遍;
* 管理员行的主体只有分发层知道,传 null 就真的是「主体未知/不唯一」(服务级故障、
* 一把密钥被 N 个账号共用),聚合时自成一组,不许拿接收者 id 冒充满。
*/
private static Long resolveSubjectUserId(String audience, Long recipientUserId, Long subjectUserId) {
if (subjectUserId != null) {
return subjectUserId;
}
return AUDIENCE_USER.equals(audience) ? recipientUserId : null;
}
/** 分页查询(id 倒序);onlyUnread=true 时只返回未读,keyword/日期区间为空表示不限制。 */
public NotificationPageVo page(Long userId, String audience, NotificationPageQuery query) {
NotificationPageQuery safe = query == null ? new NotificationPageQuery() : query;
@@ -175,6 +213,136 @@ public class NotificationService {
return vo;
}
/**
* 聚合列表:把「场景 × 自然日 × 主体用户」折成一行,分页按组切。
*
* <p>分组在 Java 侧做、SQL 只投影分组要用的那几列,为的是筛选条件与单条列表共用
* {@link #baseWrapper} 这一份实现——同一批判据写两遍(lambda 列名版 + 字符串列名版)
* 迟早漂移,而漂移的方向正好是"聚合视图和它展开的明细不是同一批行"。
* 分母天然有界:过滤条件恒为「某个收件人 + 某个接收端」,而行只保留
* {@code aiimage.notification.retention-days}(默认 7 天,见 NotificationRetentionService)。
*/
public NotificationGroupPageVo groups(Long userId, String audience, NotificationPageQuery query) {
NotificationPageQuery safe = query == null ? new NotificationPageQuery() : query;
long safePage = safe.getPage() == null || safe.getPage() < 1 ? 1L : safe.getPage();
long safeSize = safe.getPageSize() == null || safe.getPageSize() < 1
? 20L : Math.min(safe.getPageSize(), MAX_PAGE_SIZE);
List<UserNotificationEntity> rows = userNotificationMapper.selectList(
baseWrapper(userId, audience, Boolean.TRUE.equals(safe.getOnlyUnread()), safe)
.select(UserNotificationEntity::getId, UserNotificationEntity::getScene,
UserNotificationEntity::getSubjectUserId, UserNotificationEntity::getLevel,
UserNotificationEntity::getCreatedAt, UserNotificationEntity::getReadAt)
.orderByDesc(UserNotificationEntity::getId));
// 行按 id 倒序进来 ⇒ 每组第一次出现就是该组的最新一条(最终展示顺序另见下面显式排序)。
Map<GroupKey, NotificationGroupVo> grouped = new LinkedHashMap<>();
for (UserNotificationEntity row : rows) {
GroupKey key = new GroupKey(row.getScene(), row.getCreatedAt().toLocalDate(), row.getSubjectUserId());
NotificationGroupVo group = grouped.get(key);
if (group == null) {
group = new NotificationGroupVo();
group.setLatestId(row.getId());
group.setScene(row.getScene());
group.setCategory(categoryOf(row.getScene()));
group.setDay(key.day());
group.setSubjectUserId(key.subjectUserId());
group.setCreatedAt(row.getCreatedAt());
group.setRowCount(0L);
group.setUnreadCount(0L);
group.setLevel(row.getLevel());
grouped.put(key, group);
}
group.setRowCount(group.getRowCount() + 1);
if (row.getReadAt() == null) {
group.setUnreadCount(group.getUnreadCount() + 1);
}
if (levelRank(row.getLevel()) > levelRank(group.getLevel())) {
group.setLevel(row.getLevel());
}
}
// 展示顺序显式按「自然日倒序 → 组内最新 id 倒序」。不靠"id 大就等于时间新":
// 补录、时钟回拨都会让两者倒挂,那样最该看到的一组会被排到最后一页。
List<NotificationGroupVo> all = new ArrayList<>(grouped.values());
all.sort(Comparator.comparing(NotificationGroupVo::getDay, Comparator.reverseOrder())
.thenComparing(NotificationGroupVo::getLatestId, Comparator.reverseOrder()));
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()));
fillGroupHeadline(slice);
NotificationGroupPageVo vo = new NotificationGroupPageVo();
vo.setGroups(slice);
vo.setTotal((long) all.size());
vo.setRowCount((long) rows.size());
vo.setPage(safePage);
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());
return vo;
}
/** 组头那行要显示标题/正文,只能回表取最新一条;按本页组数取,一页十几条,不做全量。 */
private void fillGroupHeadline(List<NotificationGroupVo> slice) {
if (slice.isEmpty()) {
return;
}
List<Long> latestIds = new ArrayList<>(slice.size());
for (NotificationGroupVo group : slice) {
latestIds.add(group.getLatestId());
}
Map<Long, UserNotificationEntity> byId = new HashMap<>();
for (UserNotificationEntity row : userNotificationMapper.selectBatchIds(latestIds)) {
byId.put(row.getId(), row);
}
for (NotificationGroupVo group : slice) {
UserNotificationEntity head = byId.get(group.getLatestId());
if (head == null) {
continue;
}
group.setTitle(head.getTitle());
group.setContent(head.getContent());
}
}
/** error &gt; warning &gt; info:一组里混进 error 不能被后到的 warning 盖掉。 */
private static int levelRank(String level) {
if (LEVEL_ERROR.equals(level)) {
return 2;
}
return LEVEL_WARNING.equals(level) ? 1 : 0;
}
/** 分组键:场景 × 自然日 × 主体用户;subjectUserId 为 null 时所有未标注行自成一组。 */
private record GroupKey(String scene, LocalDate day, Long subjectUserId) {
}
/**
* 有未读的**组数**(新前端红点用它)。
*
* <p>刻意不覆盖 {@link #unreadCount}:已装机的老客户端读的就是那个字段画徽标,把它的语义
* 从"条数"换成"组数"会让老客户端出现"红点 3、列表 217 条"的对不上。
*
* <p>{@code COUNT(DISTINCT a,b,c)} 在 MySQL 里会**跳过任一表达式为 NULL 的行**,
* 所以第三段必须 IFNULL——否则存量未标注的那些行整个不计,未读组数会少报。
*/
public long unreadGroupCount(Long userId, String audience) {
List<Map<String, Object>> result = userNotificationMapper.selectMaps(new QueryWrapper<UserNotificationEntity>()
.select("COUNT(DISTINCT scene, DATE(created_at), IFNULL(subject_user_id, -1)) AS group_count")
.eq("user_id", userId)
.eq("audience", audience)
.isNull("read_at"));
if (result == null || result.isEmpty() || result.get(0) == null || result.get(0).isEmpty()) {
log.warn("[notification] 未读组数没读到值(不是 0)userId={} audience={}", userId, audience);
return 0L;
}
// 只 select 了一列 ⇒ 取唯一一个值,不靠列名大小写(别名在不同驱动下形状不同)
Object value = result.get(0).values().iterator().next();
return value instanceof Number number ? number.longValue() : 0L;
}
/** scene → 用户可见大类;未知 scene(历史遗留/新增未登记)一律归「系统通知」。 */
public static String categoryOf(String scene) {
return SCENE_TO_CATEGORY.getOrDefault(normalize(scene), CATEGORY_SYSTEM_NOTICE);
@@ -202,6 +370,7 @@ public class NotificationService {
public NotificationSummaryVo summary(Long userId, String audience) {
NotificationSummaryVo vo = new NotificationSummaryVo();
vo.setUnreadCount(unreadCount(userId, audience));
vo.setUnreadGroupCount(unreadGroupCount(userId, audience));
UserNotificationEntity latest = userNotificationMapper.selectOne(
new LambdaQueryWrapper<UserNotificationEntity>()
.select(UserNotificationEntity::getId)
@@ -285,6 +454,29 @@ public class NotificationService {
if (query.getEndDate() != null) {
wrapper.lt(UserNotificationEntity::getCreatedAt, query.getEndDate().plusDays(1).atStartOfDay());
}
applyGroupFilters(wrapper, query);
}
/**
* 聚合组展开明细的三个过滤条件。它们与 {@link #groups} 的分组键一一对应:
* 前端拿组头返回的 scene/day/subjectUserId 原样回传,取到的就是这一组的行。
* subjectUserId 为空且 subjectUnlabelled=true 时按 IS NULL 过滤——那是"存量未区分用户"
* 那一组,不这么做它展开时会拿到**所有**没标注的行以外的结果,等于凭空多出一堆明细。
*/
private void applyGroupFilters(LambdaQueryWrapper<UserNotificationEntity> wrapper, NotificationPageQuery query) {
String scene = normalize(query.getScene());
if (!scene.isEmpty()) {
wrapper.eq(UserNotificationEntity::getScene, scene);
}
if (query.getDay() != null) {
wrapper.ge(UserNotificationEntity::getCreatedAt, query.getDay().atStartOfDay());
wrapper.lt(UserNotificationEntity::getCreatedAt, query.getDay().plusDays(1).atStartOfDay());
}
if (query.getSubjectUserId() != null) {
wrapper.eq(UserNotificationEntity::getSubjectUserId, query.getSubjectUserId());
} else if (Boolean.TRUE.equals(query.getSubjectUnlabelled())) {
wrapper.isNull(UserNotificationEntity::getSubjectUserId);
}
}
/**