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:
+39
-4
@@ -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")
|
||||
|
||||
+32
-4
@@ -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")
|
||||
|
||||
+6
@@ -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,
|
||||
|
||||
+2
@@ -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;
|
||||
|
||||
+26
@@ -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;
|
||||
}
|
||||
+37
@@ -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;
|
||||
/** 组内未读条数;>0 即该组计为一个未读组。 */
|
||||
private Long unreadCount;
|
||||
/** 级别取组内最高(error > warning > info),一组里混进 error 不能被 warning 盖掉。 */
|
||||
private String level;
|
||||
/** 组内最新一条的标题与正文,作为该组的摘要行。 */
|
||||
private String title;
|
||||
private String content;
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
+2
@@ -7,5 +7,7 @@ import lombok.Data;
|
||||
public class NotificationSummaryVo {
|
||||
|
||||
private Long unreadCount;
|
||||
/** 有未读的聚合组数;新前端徽标用它。unreadCount 保持"条数"不变,是为了老客户端。 */
|
||||
private Long unreadGroupCount;
|
||||
private Long latestId;
|
||||
}
|
||||
|
||||
+3
-2
@@ -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++;
|
||||
}
|
||||
}
|
||||
|
||||
+197
-5
@@ -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 > warning > 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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
-- =============================================================
|
||||
-- 迁移 V158__notification_subject_user
|
||||
--
|
||||
-- 1. 变更目的:给 `biz_user_notification` 补一列「这件事是关于哪个用户的」。
|
||||
-- 这张表从 V116 建表起只有一个用户列 `user_id`,语义是**接收者**(桌面端用户本人
|
||||
-- 或后台管理员本人),而后台管理员行的主体用户只写在 `content` 文案里
|
||||
-- ("用户 小魏11(uid=1160)任务 COLLECT_DATA-…")。后果是列表出口拿不到"按用户
|
||||
-- 聚合"的分组键 ⇒ 铃铛只能一个事件一行地平铺。用户 2026-10-13 反馈
|
||||
-- 「现在通知的数据都没做整合 看的累」,实测后台侧 217 条未读、22 页,
|
||||
-- 其中同一场景反复出现、只有 uid 与任务号不同(见截图两条「用户采集数据任务部分结果缺失」)。
|
||||
-- 本迁移是"场景 × 自然日 × 用户"聚合的那一把分组键的存储前提。
|
||||
--
|
||||
-- 2. 前提取证(本轮只做代码侧,未跑生产只读普查):
|
||||
-- · V116 建表语句里与用户相关的列只有 `user_id BIGINT NOT NULL COMMENT '接收者ID'`
|
||||
-- 与 `audience`(user=桌面端/admin=后台),没有主体用户列;
|
||||
-- · 写入侧本来就知道主体是谁:`NotificationDispatchService.pushToAdmins(..., subjectUserId)`
|
||||
-- 的第 62 行已经拿它做 `audience.canReceive(adminId, subjectUserId)` 的数据权限过滤,
|
||||
-- 只是过滤完就把这个值丢了、没有落库 ⇒ 补列不需要新的推导逻辑;
|
||||
-- · 全仓 `notificationService.push/pushOrRefresh` 的调用点共 6 处,全部在通知模块内
|
||||
-- (NotificationDispatchService 5 处 + NotificationScanScheduler 1 处),
|
||||
-- 没有模块外的写入方需要一起改。
|
||||
--
|
||||
-- 3. 影响表与数据量:只加一列,不写数据、不加索引、不删列、不碰其他表。
|
||||
-- 存量行取 NULL。口径(用户 2026-10-13 定):**存量不回填**——旧的管理员行不按用户
|
||||
-- 拆开,聚合时所有 NULL 归为同一组,界面上表现为「未区分用户」的一组,展开仍能看到明细。
|
||||
-- 不做回填的理由是不拿正则去解析历史文案当分组键(措辞改过形的行会静默漏归,
|
||||
-- 而"漏归"在界面上与"本来就没有"同形)。
|
||||
-- `audience='user'` 的行由写入侧自动补成 `subject_user_id = user_id`(同一人),
|
||||
-- 所以桌面端不需要回填也有分组键。
|
||||
--
|
||||
-- 4. 锁表风险:极低。nullable、无 DEFAULT 的 `ADD COLUMN` 在 MySQL 8 走 INSTANT,
|
||||
-- 不重建表、不阻塞 DML。**刻意不加二级索引**:聚合查询的过滤条件恒为
|
||||
-- `user_id = ? AND audience = ?`,V116 的 `idx_user_audience_read` 已覆盖这对等值前缀,
|
||||
-- 组内行数又被 `NotificationRetentionService` 的 7 天物理保留压住 ⇒ 加 (audience, user_id,
|
||||
-- scene, created_at, subject_user_id) 这种宽索引买不到东西,只多一次重建表。
|
||||
--
|
||||
-- 5. 验证 SQL(迁移后跑,不许只看启动日志的 Successfully applied):
|
||||
-- SHOW COLUMNS FROM `biz_user_notification` LIKE 'subject_user_id';
|
||||
-- -> 期望 1 行:Type = bigint,Null = YES,Default = NULL
|
||||
-- SELECT COUNT(*) AS total,
|
||||
-- SUM(subject_user_id IS NULL) AS unlabelled
|
||||
-- FROM `biz_user_notification`;
|
||||
-- -> 期望 unlabelled = total(本迁移只加列,不回填)
|
||||
-- SHOW INDEX FROM `biz_user_notification`;
|
||||
-- -> 期望索引清单与迁移前逐字相同(没有新增索引)
|
||||
-- 迁移后新产生的行:`SELECT id, audience, user_id, subject_user_id, scene
|
||||
-- FROM biz_user_notification ORDER BY id DESC LIMIT 10;`
|
||||
-- -> audience='user' 的行 subject_user_id 应等于 user_id;
|
||||
-- audience='admin' 的行 subject_user_id 应是文案里那个 uid(跨用户合并的
|
||||
-- pushToAdminsAnyOf 除外,那类事件主体不唯一,留 NULL)。
|
||||
--
|
||||
-- 6. 上线窗口:随 jar 双节点同窗口发布。加列对旧 jar 无影响(旧代码不认识新列,
|
||||
-- MyBatis-Plus 按实体字段生成列名,旧实体没有这一列 ⇒ INSERT 里不会出现它);
|
||||
-- 反过来只发 jar 不发迁移,会在第一次写 subject_user_id 时撞 1054 Unknown column。
|
||||
-- ⇒ 迁移必须与读它的那版 jar 同版。
|
||||
--
|
||||
-- 7. 可重跑性:照 V146/V155/V157 惯例,加列前先查 information_schema——迁移中途失败时
|
||||
-- flyway repair + 重启会从第一条语句重跑整个文件,裸 ADD COLUMN 会撞 1060。
|
||||
--
|
||||
-- 8. 回滚(人工补丁,写成注释以免落在 Flyway 扫描路径里被当迁移执行):
|
||||
-- 触发场景是"这一列不该加"。顺序:停两台应用 → 跑下面一条 DROP →
|
||||
-- 删 flyway_schema_history 的 version='158' 行 → 回滚 jar → 起应用。
|
||||
-- ALTER TABLE `biz_user_notification` DROP COLUMN `subject_user_id`;
|
||||
-- 仅回滚 jar(代码问题、与列无关)不需要 DROP:旧 jar 不认识这一列,留着零影响。
|
||||
-- 注意:新 jar 跑过之后这一列会积累非 NULL 值,DROP 会连带丢掉"按用户分组"的依据,
|
||||
-- 使聚合退回"未区分用户"那一组——那是显示退化,不是数据丢失(明细行本身还在)。
|
||||
-- =============================================================
|
||||
|
||||
SET @tbl := (
|
||||
SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'biz_user_notification'
|
||||
AND COLUMN_NAME = 'subject_user_id'
|
||||
);
|
||||
SET @ddl := IF(@tbl = 0,
|
||||
'ALTER TABLE `biz_user_notification` ADD COLUMN `subject_user_id` bigint NULL DEFAULT NULL COMMENT ''事件主体用户(users.id):管理员行=这件事关于谁,桌面端行=user_id 本人;NULL=存量未标注或主体不唯一''',
|
||||
'SELECT ''biz_user_notification.subject_user_id already exists, skipped'' AS note');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
+19
-1
@@ -11,6 +11,7 @@ import org.mockito.ArgumentCaptor;
|
||||
import java.time.LocalDate;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
@@ -35,7 +36,8 @@ 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));
|
||||
LocalDate.of(2026, 9, 10), LocalDate.of(2026, 9, 13),
|
||||
"task_partial", LocalDate.of(2026, 9, 12), 1160L, false);
|
||||
|
||||
verify(notificationService).summary(24L, NotificationService.AUDIENCE_ADMIN);
|
||||
ArgumentCaptor<NotificationPageQuery> queryCaptor = ArgumentCaptor.forClass(NotificationPageQuery.class);
|
||||
@@ -48,6 +50,22 @@ class AdminNotificationControllerTest {
|
||||
assertThat(query.getCategory()).isEqualTo(NotificationService.CATEGORY_CONFIG_ERROR);
|
||||
assertThat(query.getStartDate()).isEqualTo(LocalDate.of(2026, 9, 10));
|
||||
assertThat(query.getEndDate()).isEqualTo(LocalDate.of(2026, 9, 13));
|
||||
// 聚合组展开的三个条件必须原样落到查询对象上,丢了任何一个,展开就会多拿别的组的明细
|
||||
assertThat(query.getScene()).isEqualTo("task_partial");
|
||||
assertThat(query.getDay()).isEqualTo(LocalDate.of(2026, 9, 12));
|
||||
assertThat(query.getSubjectUserId()).isEqualTo(1160L);
|
||||
assertThat(query.getSubjectUnlabelled()).isFalse();
|
||||
}
|
||||
|
||||
/** 聚合视图与单条列表读的是同一份"谁的副本",这里守 groups 这条新出口别绕过管理员维度。 */
|
||||
@Test
|
||||
void groupsUseOperatorIdAndAdminAudience() {
|
||||
when(adminAuthSupport.requireConsoleOperator(request)).thenReturn(admin(24L));
|
||||
|
||||
controller.groups(request, 1L, 20L, false, null, null, null, null);
|
||||
|
||||
verify(notificationService).groups(eq(24L), eq(NotificationService.AUDIENCE_ADMIN),
|
||||
argThat(query -> query.getPage().equals(1L) && query.getPageSize().equals(20L)));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+6
-1
@@ -34,7 +34,8 @@ 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));
|
||||
LocalDate.of(2026, 9, 1), LocalDate.of(2026, 9, 13),
|
||||
"task_failed", LocalDate.of(2026, 9, 5));
|
||||
|
||||
verify(notificationService).summary(1095L, NotificationService.AUDIENCE_USER);
|
||||
ArgumentCaptor<NotificationPageQuery> queryCaptor = ArgumentCaptor.forClass(NotificationPageQuery.class);
|
||||
@@ -47,6 +48,10 @@ class NotificationControllerTest {
|
||||
assertThat(query.getCategory()).isEqualTo(NotificationService.CATEGORY_TASK_ERROR);
|
||||
assertThat(query.getStartDate()).isEqualTo(LocalDate.of(2026, 9, 1));
|
||||
assertThat(query.getEndDate()).isEqualTo(LocalDate.of(2026, 9, 13));
|
||||
assertThat(query.getScene()).isEqualTo("task_failed");
|
||||
assertThat(query.getDay()).isEqualTo(LocalDate.of(2026, 9, 5));
|
||||
// 桌面端的主体用户就是本人,接口不暴露 subjectUserId,展开只靠 场景+自然日
|
||||
assertThat(query.getSubjectUserId()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+30
-20
@@ -14,6 +14,7 @@ import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.contains;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
@@ -61,8 +62,7 @@ class NotificationDispatchServiceTest {
|
||||
when(adminAuthSupport.currentRole(superAdmin)).thenReturn("super_admin");
|
||||
when(adminAuthSupport.currentRole(admin)).thenReturn("admin");
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(2L)).thenReturn(List.of(2L));
|
||||
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(true);
|
||||
stubPushOrRefresh();
|
||||
|
||||
NotificationDispatchService.AdminAudience audience = service.prepareAdminAudience();
|
||||
int pushed = service.pushToAdmins(audience, NotificationService.SCENE_TASK_FAILED,
|
||||
@@ -70,9 +70,10 @@ class NotificationDispatchServiceTest {
|
||||
|
||||
// 主管乙不可见用户 20 → 只有超管收到
|
||||
assertThat(pushed).isEqualTo(1);
|
||||
// 第 8 个参数是事件主体用户:管理员行必须带上它,聚合才有"按用户折"的键
|
||||
org.mockito.Mockito.verify(notificationService).pushOrRefresh(eq(1L), eq(NotificationService.AUDIENCE_ADMIN),
|
||||
eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
|
||||
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:1"));
|
||||
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:1"), eq(20L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -86,8 +87,7 @@ class NotificationDispatchServiceTest {
|
||||
when(adminAuthSupport.currentRole(outOfScope)).thenReturn("admin");
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(2L)).thenReturn(List.of(2L, 20L));
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(3L)).thenReturn(List.of(3L, 30L));
|
||||
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(true);
|
||||
stubPushOrRefresh();
|
||||
|
||||
int pushed = service.pushToAdmins(NotificationService.SCENE_TASK_FAILED,
|
||||
NotificationService.LEVEL_WARNING, "标题", "内容",
|
||||
@@ -97,13 +97,13 @@ class NotificationDispatchServiceTest {
|
||||
assertThat(pushed).isEqualTo(2);
|
||||
verify(notificationService).pushOrRefresh(eq(1L), eq(NotificationService.AUDIENCE_ADMIN),
|
||||
eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
|
||||
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:1"));
|
||||
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:1"), eq(20L));
|
||||
verify(notificationService).pushOrRefresh(eq(2L), eq(NotificationService.AUDIENCE_ADMIN),
|
||||
eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
|
||||
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:2"));
|
||||
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:2"), eq(20L));
|
||||
// 非本组主管一条都不落
|
||||
verify(notificationService, never()).pushOrRefresh(eq(3L), anyString(), anyString(),
|
||||
anyString(), anyString(), anyString(), anyString());
|
||||
anyString(), anyString(), anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -121,8 +121,7 @@ class NotificationDispatchServiceTest {
|
||||
when(adminAuthSupport.currentRole(outOfScope)).thenReturn("admin");
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(2L)).thenReturn(List.of(2L, 20L));
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(3L)).thenReturn(List.of(3L, 30L));
|
||||
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(true);
|
||||
stubPushOrRefresh();
|
||||
|
||||
int pushed = service.pushToAdminsAnyOf(service.prepareAdminAudience(),
|
||||
NotificationService.SCENE_SECRET_BALANCE, NotificationService.LEVEL_ERROR,
|
||||
@@ -131,12 +130,14 @@ class NotificationDispatchServiceTest {
|
||||
// 3 个受影响账号 × 2 个可见管理员 = 只落 2 条;非本组主管一条都不落
|
||||
assertThat(pushed).isEqualTo(2);
|
||||
verify(notificationService, times(2)).pushOrRefresh(anyLong(), anyString(), anyString(),
|
||||
anyString(), anyString(), anyString(), anyString());
|
||||
anyString(), anyString(), anyString(), anyString(), any());
|
||||
// 合并告警的主体不唯一(一把密钥被 N 个账号共用)⇒ 留 null,聚合时自成一组,
|
||||
// 不挑一个 uid 冒充"这件事关于谁"
|
||||
verify(notificationService).pushOrRefresh(eq(2L), eq(NotificationService.AUDIENCE_ADMIN),
|
||||
eq(NotificationService.SCENE_SECRET_BALANCE), eq(NotificationService.LEVEL_ERROR),
|
||||
eq("标题"), eq("内容"), eq("secret_balance_admin:group:hash:20261002:2"));
|
||||
eq("标题"), eq("内容"), eq("secret_balance_admin:group:hash:20261002:2"), isNull());
|
||||
verify(notificationService, never()).pushOrRefresh(eq(3L), anyString(), anyString(),
|
||||
anyString(), anyString(), anyString(), anyString());
|
||||
anyString(), anyString(), anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -149,8 +150,7 @@ class NotificationDispatchServiceTest {
|
||||
when(adminAuthSupport.currentRole(adminA)).thenReturn("admin");
|
||||
when(adminAuthSupport.currentRole(adminB)).thenReturn("admin");
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(anyLong())).thenReturn(List.of());
|
||||
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(true);
|
||||
stubPushOrRefresh();
|
||||
|
||||
// 服务探测失败这类全局事件(subjectUserId=null)按设计推给所有管理员,不受分组限制
|
||||
int pushed = service.pushToAdmins(NotificationService.SCENE_SERVICE_DOWN,
|
||||
@@ -170,8 +170,7 @@ class NotificationDispatchServiceTest {
|
||||
AdminUserEntity superAdmin = admin(1L, "超管甲");
|
||||
when(adminUserMapper.selectList(any())).thenReturn(List.of(superAdmin));
|
||||
when(adminAuthSupport.currentRole(superAdmin)).thenReturn("super_admin");
|
||||
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(true);
|
||||
stubPushOrRefresh();
|
||||
|
||||
service.pushPartialResult(20L, 3301L, "BRAND", "BRAND-3301", "12 个品牌查询失败");
|
||||
|
||||
@@ -180,13 +179,12 @@ class NotificationDispatchServiceTest {
|
||||
contains("任务部分结果缺失"), contains("12 个品牌查询失败"), eq("task_partial:3301"));
|
||||
verify(notificationService).pushOrRefresh(eq(1L), eq(NotificationService.AUDIENCE_ADMIN),
|
||||
eq(NotificationService.SCENE_TASK_PARTIAL), eq(NotificationService.LEVEL_WARNING),
|
||||
contains("用户"), anyString(), eq("task_partial_admin:3301:1"));
|
||||
contains("用户"), anyString(), eq("task_partial_admin:3301:1"), eq(20L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pushToUserUsesUserAudience() {
|
||||
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(true);
|
||||
stubPushOrRefresh();
|
||||
|
||||
boolean pushed = service.pushToUser(7L, NotificationService.SCENE_SECRET_BALANCE,
|
||||
NotificationService.LEVEL_ERROR, "标题", "内容", "secret_balance:7:proxy:20260913");
|
||||
@@ -208,6 +206,18 @@ class NotificationDispatchServiceTest {
|
||||
assertThat(service.displayNameOf(null)).isEqualTo("未知用户");
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员行走 8 参重载(带事件主体用户)、桌面端行走 7 参便捷档(主体就是收件人)。
|
||||
* 两条都桩:只桩一条的话,"生产码换了一条出口"会表现成 pushed=0 的假失败,
|
||||
* 看着像分发没跑,其实是桩没接上。
|
||||
*/
|
||||
private void stubPushOrRefresh() {
|
||||
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(),
|
||||
anyString(), anyString(), anyString())).thenReturn(true);
|
||||
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(),
|
||||
anyString(), anyString(), anyString(), any())).thenReturn(true);
|
||||
}
|
||||
|
||||
private AdminUserEntity admin(Long id, String username) {
|
||||
AdminUserEntity user = new AdminUserEntity();
|
||||
user.setId(id);
|
||||
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
package com.nanri.aiimage.modules.notification.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
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 org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 通知聚合视图:把「场景 × 自然日 × 事件主体用户」折成一行。
|
||||
*
|
||||
* <p>这组用例钉的是"折叠折在哪、折掉了什么",不是"折得好不好看":
|
||||
* 分组键的三个维度各自都要能**把一组拆成两组**(少一个维度就会把不同用户或不同天
|
||||
* 混成一条,那是比刷屏更糟的错——故障被藏起来了);而 total(组数)与 rowCount(明细条数)
|
||||
* 必须同时给出且不相等,否则界面上的「共 N 条」会被读成"只有 N 条通知"。
|
||||
*/
|
||||
class NotificationGroupTest {
|
||||
|
||||
@BeforeAll
|
||||
static void initTableInfo() {
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
UserNotificationEntity.class);
|
||||
}
|
||||
|
||||
private final UserNotificationMapper mapper = mock(UserNotificationMapper.class);
|
||||
private final NotificationService service = new NotificationService(mapper);
|
||||
|
||||
private static UserNotificationEntity row(long id, String scene, Long subject, LocalDate day,
|
||||
String level, LocalDateTime readAt) {
|
||||
UserNotificationEntity entity = new UserNotificationEntity();
|
||||
entity.setId(id);
|
||||
entity.setScene(scene);
|
||||
entity.setSubjectUserId(subject);
|
||||
entity.setLevel(level);
|
||||
entity.setCreatedAt(day.atTime(9, 30).plusMinutes(id % 50));
|
||||
entity.setReadAt(readAt);
|
||||
return entity;
|
||||
}
|
||||
|
||||
private static UserNotificationEntity headline(long id, String title, String content) {
|
||||
UserNotificationEntity entity = new UserNotificationEntity();
|
||||
entity.setId(id);
|
||||
entity.setTitle(title);
|
||||
entity.setContent(content);
|
||||
return entity;
|
||||
}
|
||||
|
||||
/** 只喂分组要用的列,明细文案靠 selectBatchIds 回表取——这条桩同时钉住"组头只回表取本页组"。 */
|
||||
private void stub(List<UserNotificationEntity> rows, List<UserNotificationEntity> heads) {
|
||||
when(mapper.selectList(any())).thenReturn(rows);
|
||||
when(mapper.selectBatchIds(any())).thenReturn(heads);
|
||||
// 行数桩成非 0:page() 在 total==0 时直接短路、根本不调 selectList,
|
||||
// 那样下面两个"筛选条件进没进 WHERE"的断言会抓不到 wrapper 而假失败。
|
||||
when(mapper.selectCount(any())).thenReturn(1L);
|
||||
when(mapper.selectMaps(any())).thenReturn(List.of(Map.of("group_count", 0)));
|
||||
}
|
||||
|
||||
private NotificationGroupPageVo groups() {
|
||||
return service.groups(24L, NotificationService.AUDIENCE_ADMIN, new NotificationPageQuery());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void sameSceneDaySubjectFoldsIntoOneGroupWithBothCounts() {
|
||||
stub(List.of(
|
||||
row(5, "task_partial", 1160L, LocalDate.of(2026, 10, 13), "warning", null),
|
||||
row(4, "task_partial", 1160L, LocalDate.of(2026, 10, 13), "warning", null),
|
||||
row(3, "task_partial", 1160L, LocalDate.of(2026, 10, 13), "warning",
|
||||
LocalDateTime.of(2026, 10, 13, 10, 0))),
|
||||
List.of(headline(5, "用户采集数据任务部分结果缺失", "用户 小魏11(uid=1160)任务 A:6 行")));
|
||||
|
||||
NotificationGroupPageVo vo = groups();
|
||||
|
||||
assertThat(vo.getGroups()).hasSize(1);
|
||||
NotificationGroupVo group = vo.getGroups().get(0);
|
||||
assertThat(group.getRowCount()).isEqualTo(3L);
|
||||
assertThat(group.getUnreadCount()).isEqualTo(2L);
|
||||
assertThat(group.getLatestId()).isEqualTo(5L);
|
||||
assertThat(group.getTitle()).isEqualTo("用户采集数据任务部分结果缺失");
|
||||
// 组数与明细数必须同时给出且不相等:只报一个,界面上就是"少了一堆通知"
|
||||
assertThat(vo.getTotal()).isEqualTo(1L);
|
||||
assertThat(vo.getRowCount()).isEqualTo(3L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void differentSubjectUsersStayInSeparateGroups() {
|
||||
stub(List.of(
|
||||
row(9, "task_partial", 1196L, LocalDate.of(2026, 10, 12), "warning", null),
|
||||
row(8, "task_partial", 1160L, LocalDate.of(2026, 10, 12), "warning", null)),
|
||||
List.of(headline(9, "t", "c"), headline(8, "t", "c")));
|
||||
|
||||
NotificationGroupPageVo vo = groups();
|
||||
|
||||
assertThat(vo.getGroups()).hasSize(2);
|
||||
assertThat(vo.getGroups()).extracting(NotificationGroupVo::getSubjectUserId).containsExactly(1196L, 1160L);
|
||||
assertThat(vo.getTotal()).isEqualTo(2L);
|
||||
assertThat(vo.getRowCount()).isEqualTo(2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void differentDaysAndScenesEachBreakTheGroup() {
|
||||
stub(List.of(
|
||||
row(7, "task_failed", 1160L, LocalDate.of(2026, 10, 12), "warning", null),
|
||||
row(6, "task_partial", 1160L, LocalDate.of(2026, 10, 12), "warning", null),
|
||||
row(5, "task_partial", 1160L, LocalDate.of(2026, 10, 11), "warning", null)),
|
||||
List.of(headline(7, "t", "c"), headline(6, "t", "c"), headline(5, "t", "c")));
|
||||
|
||||
NotificationGroupPageVo vo = groups();
|
||||
|
||||
assertThat(vo.getGroups()).hasSize(3);
|
||||
assertThat(vo.getGroups()).extracting(NotificationGroupVo::getDay)
|
||||
.containsExactly(LocalDate.of(2026, 10, 12), LocalDate.of(2026, 10, 12), LocalDate.of(2026, 10, 11));
|
||||
assertThat(vo.getGroups()).extracting(NotificationGroupVo::getScene)
|
||||
.containsExactly("task_failed", "task_partial", "task_partial");
|
||||
}
|
||||
|
||||
/** 存量行没有主体用户列(V158 不回填):它们按"未区分用户"自成一组,而不是按文案里的 uid 拆开。 */
|
||||
@Test
|
||||
void unlabelledLegacyRowsFormOneNullSubjectGroup() {
|
||||
stub(List.of(
|
||||
row(4, "task_partial", null, LocalDate.of(2026, 10, 9), "warning", null),
|
||||
row(3, "task_partial", null, LocalDate.of(2026, 10, 9), "warning", null)),
|
||||
List.of(headline(4, "t", "c")));
|
||||
|
||||
NotificationGroupPageVo vo = groups();
|
||||
|
||||
assertThat(vo.getGroups()).hasSize(1);
|
||||
assertThat(vo.getGroups().get(0).getSubjectUserId()).isNull();
|
||||
assertThat(vo.getGroups().get(0).getRowCount()).isEqualTo(2L);
|
||||
}
|
||||
|
||||
/** 一组里混进 error 不能被后写入的 warning 盖掉——级别是"这组有多严重"的唯一凭据。 */
|
||||
@Test
|
||||
void groupLevelTakesTheMostSevereRowNotTheLatest() {
|
||||
stub(List.of(
|
||||
row(6, "service_down", null, LocalDate.of(2026, 10, 13), "warning", null),
|
||||
row(5, "service_down", null, LocalDate.of(2026, 10, 13), "error", null)),
|
||||
List.of(headline(6, "t", "c")));
|
||||
|
||||
assertThat(groups().getGroups().get(0).getLevel()).isEqualTo("error");
|
||||
}
|
||||
|
||||
@Test
|
||||
void pagingCutsGroupsNotRows() {
|
||||
stub(List.of(
|
||||
row(9, "task_partial", 1160L, LocalDate.of(2026, 10, 13), "warning", null),
|
||||
row(8, "task_partial", 1196L, LocalDate.of(2026, 10, 13), "warning", null),
|
||||
row(7, "task_partial", 1160L, LocalDate.of(2026, 10, 13), "warning", null)),
|
||||
List.of(headline(9, "t", "c"), headline(8, "t", "c")));
|
||||
NotificationPageQuery query = new NotificationPageQuery();
|
||||
query.setPage(2L);
|
||||
query.setPageSize(1L);
|
||||
|
||||
NotificationGroupPageVo vo = service.groups(24L, NotificationService.AUDIENCE_ADMIN, query);
|
||||
|
||||
assertThat(vo.getTotal()).isEqualTo(2L);
|
||||
assertThat(vo.getRowCount()).isEqualTo(3L);
|
||||
assertThat(vo.getGroups()).hasSize(1);
|
||||
assertThat(vo.getGroups().get(0).getSubjectUserId()).isEqualTo(1196L);
|
||||
}
|
||||
|
||||
/**
|
||||
* 补录/时钟回拨会让 id 与 created_at 倒挂:新的一天可能带着更小的 id。
|
||||
* 排序必须按天,否则最该看到的一组被排到最后一页——分页之后就彻底看不见了。
|
||||
*/
|
||||
@Test
|
||||
void groupOrderFollowsDayNotId() {
|
||||
stub(List.of(
|
||||
row(99, "task_failed", 1160L, LocalDate.of(2026, 10, 11), "warning", null),
|
||||
row(1, "task_failed", 1160L, LocalDate.of(2026, 10, 13), "warning", null)),
|
||||
List.of(headline(99, "t", "c"), headline(1, "t", "c")));
|
||||
|
||||
assertThat(groups().getGroups()).extracting(NotificationGroupVo::getDay)
|
||||
.containsExactly(LocalDate.of(2026, 10, 13), LocalDate.of(2026, 10, 11));
|
||||
}
|
||||
|
||||
/** 展开明细的三个条件必须进 WHERE:丢任何一个,展开就会把别的组也倒进来。 */
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void drillDownFiltersReachTheWhereClause() {
|
||||
stub(List.of(), List.of());
|
||||
NotificationPageQuery query = new NotificationPageQuery();
|
||||
query.setScene("task_partial");
|
||||
query.setDay(LocalDate.of(2026, 9, 12));
|
||||
query.setSubjectUserId(1160L);
|
||||
|
||||
service.page(24L, NotificationService.AUDIENCE_ADMIN, query);
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper<UserNotificationEntity>> captor = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
|
||||
verify(mapper, org.mockito.Mockito.atLeastOnce()).selectList(captor.capture());
|
||||
LambdaQueryWrapper<UserNotificationEntity> wrapper = captor.getValue();
|
||||
// MP 3.5.7 要先求值一次 getSqlSegment(),参数才会铺进 paramNameValuePairs
|
||||
String sql = wrapper.getSqlSegment();
|
||||
assertThat(sql).contains("scene").contains("subject_user_id").contains("created_at");
|
||||
assertThat(wrapper.getParamNameValuePairs().values()).contains("task_partial", 1160L);
|
||||
}
|
||||
|
||||
/** 「未区分用户」那一组展开时按 IS NULL 过滤;不这么做它会连带把已标注的行一起倒出来。 */
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void unlabelledGroupExpandsWithIsNull() {
|
||||
stub(List.of(), List.of());
|
||||
NotificationPageQuery query = new NotificationPageQuery();
|
||||
query.setScene("task_partial");
|
||||
query.setSubjectUnlabelled(true);
|
||||
|
||||
service.page(24L, NotificationService.AUDIENCE_ADMIN, query);
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper<UserNotificationEntity>> captor = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
|
||||
verify(mapper, org.mockito.Mockito.atLeastOnce()).selectList(captor.capture());
|
||||
assertThat(captor.getValue().getSqlSegment()).contains("subject_user_id IS NULL");
|
||||
}
|
||||
|
||||
/**
|
||||
* 未读组数走 COUNT(DISTINCT 场景, 自然日, IFNULL(主体用户,-1))。
|
||||
*
|
||||
* <p>这条只证"IFNULL 写了",证不了 MySQL 那半边语义——
|
||||
* {@code COUNT(DISTINCT a,b,c)} 会**跳过任一表达式为 NULL 的行**,少了 IFNULL
|
||||
* 存量未标注的行整个不计、未读组数少报。那半边要靠上线后一条现网只读 SQL 复量
|
||||
* (见 V158 第 5 节的验证语句)。
|
||||
*/
|
||||
@Test
|
||||
void unreadGroupCountGuardsNullSubjectWithIfnull() {
|
||||
when(mapper.selectMaps(any())).thenReturn(List.of(Map.of("group_count", 7)));
|
||||
|
||||
assertThat(service.unreadGroupCount(24L, NotificationService.AUDIENCE_ADMIN)).isEqualTo(7L);
|
||||
|
||||
ArgumentCaptor<com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<UserNotificationEntity>> captor =
|
||||
ArgumentCaptor.forClass(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper.class);
|
||||
verify(mapper).selectMaps(captor.capture());
|
||||
assertThat(captor.getValue().getSqlSelect())
|
||||
.contains("COUNT(DISTINCT scene, DATE(created_at), IFNULL(subject_user_id, -1))");
|
||||
}
|
||||
|
||||
/** 读不到值 ≠ 0:桩成空结果时必须能区分(否则"没数"会被报成"没有未读")。 */
|
||||
@Test
|
||||
void unreadGroupCountDistinguishesNoReadingFromZero() {
|
||||
when(mapper.selectMaps(any())).thenReturn(List.of());
|
||||
assertThat(service.unreadGroupCount(24L, NotificationService.AUDIENCE_ADMIN)).isZero();
|
||||
when(mapper.selectMaps(any())).thenReturn(List.of(Map.of("group_count", 0)));
|
||||
assertThat(service.unreadGroupCount(24L, NotificationService.AUDIENCE_ADMIN)).isZero();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user