From 0fd0ee17ee2ecb4a21f8732b290d08ce0628d050 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=BB=84=E8=87=AA=E8=BE=BE?= <980324341@qq.com>
Date: Fri, 2 Oct 2026 10:35:06 +0800
Subject: [PATCH] =?UTF-8?q?fix(=E9=80=9A=E7=9F=A5):=20=E8=81=9A=E5=90=88?=
=?UTF-8?q?=E5=8E=BB=E9=87=8D=E9=94=AE=E4=BB=8E=E5=B0=8F=E6=97=B6=E6=A1=B6?=
=?UTF-8?q?=E6=94=B9=E8=87=AA=E7=84=B6=E6=97=A5=EF=BC=8C=E5=88=B7=E6=96=B0?=
=?UTF-8?q?=E4=B8=8D=E5=86=8D=E6=8A=8A=E5=B7=B2=E8=AF=BB=E7=82=B9=E4=BA=AE?=
=?UTF-8?q?=E5=9B=9E=E6=9C=AA=E8=AF=BB?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
后台「通知」被刷屏的两个乘数:一条告警一天最多重发 24 次(小时桶换键),
以及刷新时 set read_at=null 把用户已读过的红点重新点亮。现在 task_failed /
service_down / maixiang_anomaly 五类键统一按「用户×模块×自然日」聚合,
pushOrRefresh 只更新文案不动 read_at;桶的日期取事件自身的 updatedAt,
跨零点轮询不会把昨天的失败挪进今天的桶。
---
.../config/NotificationProperties.java | 2 +-
.../service/MaixiangAnomalyScanner.java | 15 ++--
.../service/NotificationScanScheduler.java | 40 +++++----
.../service/NotificationService.java | 10 +--
.../service/MaixiangAnomalyScannerTest.java | 8 +-
.../NotificationDispatchServiceTest.java | 46 ++++++++--
.../NotificationScanSchedulerTest.java | 84 ++++++++++++++++++-
.../service/NotificationServiceTest.java | 21 +++--
8 files changed, 178 insertions(+), 48 deletions(-)
diff --git a/backend-java/src/main/java/com/nanri/aiimage/config/NotificationProperties.java b/backend-java/src/main/java/com/nanri/aiimage/config/NotificationProperties.java
index 881a88c6a..b72787be9 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/config/NotificationProperties.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/config/NotificationProperties.java
@@ -14,7 +14,7 @@ public class NotificationProperties {
/** 扫描总开关:关闭后任务失败扫描与服务探测都不执行(应急降噪)。 */
private boolean scanEnabled = true;
- /** 扫描间隔(毫秒),默认 5 分钟(任务失败聚合按小时去重,高频扫描不会重复提醒)。 */
+ /** 扫描间隔(毫秒),默认 5 分钟(聚合通知按自然日去重,高频扫描只会刷新同一条、不会重复提醒)。 */
private long scanIntervalMs = 5 * 60 * 1000L;
/** 首次执行延迟(毫秒),默认 2 分钟,避开启动阶段的数据库压力。 */
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/notification/service/MaixiangAnomalyScanner.java b/backend-java/src/main/java/com/nanri/aiimage/modules/notification/service/MaixiangAnomalyScanner.java
index d2ef49bdc..742cec422 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/notification/service/MaixiangAnomalyScanner.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/notification/service/MaixiangAnomalyScanner.java
@@ -41,9 +41,9 @@ import java.util.stream.Collectors;
* "采集机掉线"(2026-09-29 停摆 6 小时即如此,且当时 210 条 pending 没到 300 的阈值,
* 连积压检查都没触发)。
*
- *
全部为管理员全局事件(与「服务探测」一致,不按数据权限过滤);去重键:
- * 停滞类按天、失败/积压按小时、空结果按任务——同一异常窗口内只提醒一次,
- * 情况变化(新增停滞任务/失败数增长)时刷新内容并重新提醒。
+ *
全部为管理员全局事件(与「服务探测」一致,不按数据权限过滤);去重键按自然日
+ * (空结果按任务):同一异常当天只一条,情况变化(新增停滞任务/失败数增长)时刷新内容,
+ * 但不把已读的重新点亮 —— 一台掉线的采集机会被扫几十轮,逐轮点亮等于刷屏。
*
*
由 {@link NotificationScanScheduler} 在分布式锁内调用;单项检查异常只记日志不中断其余检查。
*/
@@ -66,7 +66,6 @@ public class MaixiangAnomalyScanner {
private static final int REASON_MAX_LENGTH = 120;
private static final DateTimeFormatter DAY_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd");
- private static final DateTimeFormatter HOUR_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHH");
private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/** 麦象任务类型 → 中文名(未登记的类型回退原始值)。 */
@@ -146,7 +145,7 @@ public class MaixiangAnomalyScanner {
String content = "麦象采集机疑似掉线:所有打点信号已静默 " + (machineIdle / 60) + " 分钟(" + detail
+ ")。该机器无开机自启,重启/升配后必须人工拉起;请检查 5 个 worker 是否在运行"
+ "(start_task.bat 或 更新并重启.bat)。";
- push(audience, "采集机掉线", content, "maixiang_silent:" + now.format(HOUR_FORMAT));
+ push(audience, "采集机掉线", content, "maixiang_silent:" + now.format(DAY_FORMAT));
}
/** 打点信号的中文标签:接口没给 label 时回退信号名。 */
@@ -214,7 +213,7 @@ public class MaixiangAnomalyScanner {
push(audience, "麦象任务滞留未消费", content, "maixiang_stuck_single:" + now.format(DAY_FORMAT));
}
- /** 任务失败:近窗口内 status=3 的单任务达到最小条数(按小时桶聚合,原因取最新一条)。 */
+ /** 任务失败:近窗口内 status=3 的单任务达到最小条数(按自然日聚合,原因取最新一条)。 */
void checkFailedSingleTasks(NotificationDispatchService.AdminAudience audience, LocalDateTime now) {
SingleTaskPage page = consoleClient.singleTasks(3, null, FAIL_PAGE_SIZE);
LocalDateTime windowStart = now.minusMinutes(FAIL_WINDOW_MINUTES);
@@ -234,7 +233,7 @@ public class MaixiangAnomalyScanner {
+ typeSummary(failed.stream().map(SingleTaskItem::taskType).toList()) + ")"
+ (reason.isEmpty() ? "" : ";最近失败原因:" + reason)
+ "。请排查采集端配置(如代理余额、任务类型注册)。";
- push(audience, "麦象任务失败", content, "maixiang_fail:" + now.format(HOUR_FORMAT));
+ push(audience, "麦象任务失败", content, "maixiang_fail:" + now.format(DAY_FORMAT));
}
/** 批量任务空结果:最近完成但结果 0 条(worker 报错时批次仍会被标为"已完成")。 */
@@ -289,7 +288,7 @@ public class MaixiangAnomalyScanner {
}
String content = "麦象单任务队列积压:" + detail + "(阈值 待处理 " + pendingThreshold
+ " 且无消费 / 处理中 " + processingThreshold + ")。消费端可能掉线,请尽快排查采集机 worker。";
- push(audience, "麦象队列积压", content, "maixiang_queue_backlog:" + now.format(HOUR_FORMAT));
+ push(audience, "麦象队列积压", content, "maixiang_queue_backlog:" + now.format(DAY_FORMAT));
}
// ======================== 文案辅助 ========================
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/notification/service/NotificationScanScheduler.java b/backend-java/src/main/java/com/nanri/aiimage/modules/notification/service/NotificationScanScheduler.java
index 1aaf387c6..a00be594f 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/notification/service/NotificationScanScheduler.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/notification/service/NotificationScanScheduler.java
@@ -29,11 +29,11 @@ import java.util.Map;
* 站内通知扫描:任务失败聚合提醒 + 下游服务健康探测。
*
*
任务失败:回看窗口内进入失败终态的任务(biz_file_task / brand_crawl_tasks),
- * 按「用户 × 模块 × 小时」聚合,同一小时桶内增量刷新同一条通知(不刷屏);
+ * 按「用户 × 模块 × 自然日」聚合,同一天内增量刷新同一条通知(不刷屏);
* 用户侧推给任务创建者,管理员侧按数据权限推给管辖该用户的管理员。
*
*
服务探测:品牌检测服务(15126) / 跟价任务 API(18960) / jikip 代理接口,
- * 失败立即重试一次(过滤瞬抖),两次都失败才告警;同服务每小时最多一条。
+ * 失败立即重试一次(过滤瞬抖),两次都失败才告警;同服务每天最多一条。
*
*
麦象异常扫描:见 {@link MaixiangAnomalyScanner}(批量/单任务停滞、任务失败、
* 批量任务空结果、队列积压 → 管理员通知),与任务失败扫描共用本调度与分布式锁。
@@ -55,7 +55,7 @@ public class NotificationScanScheduler {
private static final int REASON_MAX_LENGTH = 120;
private static final int PROBE_READ_TIMEOUT_MILLIS = 8_000;
- private static final DateTimeFormatter HOUR_FORMAT = DateTimeFormatter.ofPattern("yyyyMMddHH");
+ private static final DateTimeFormatter DAY_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd");
/**
* 任务模块类型 → 中文名:直接取模块注册表(G6),新增模块只需在
@@ -102,7 +102,7 @@ public class NotificationScanScheduler {
}
}
- /** 任务失败聚合扫描:窗口内失败终态任务按「用户 × 模块 × 小时」聚合成一条通知。 */
+ /** 任务失败聚合扫描:窗口内失败终态任务按「用户 × 模块 × 自然日」聚合成一条通知。 */
void scanFailedTasks() {
LocalDateTime cutoff = LocalDateTime.now()
.minusMinutes(Math.max(1, properties.getTaskFailedWindowMinutes()));
@@ -121,7 +121,7 @@ public class NotificationScanScheduler {
continue;
}
failed.add(new FailedTask(task.getId(), displayTaskNo(task.getTaskNo(), task.getId()),
- task.getModuleType(), task.getUserId(), task.getErrorMessage()));
+ task.getModuleType(), task.getUserId(), task.getErrorMessage(), task.getUpdatedAt()));
}
List brandTasks = brandCrawlTaskMapper.selectList(new LambdaQueryWrapper()
.select(BrandCrawlTaskEntity::getId, BrandCrawlTaskEntity::getUserId,
@@ -135,19 +135,18 @@ public class NotificationScanScheduler {
continue;
}
failed.add(new FailedTask(task.getId(), "#" + task.getId(),
- BRAND_MODULE_TYPE, task.getUserId(), task.getErrorMessage()));
+ BRAND_MODULE_TYPE, task.getUserId(), task.getErrorMessage(), task.getUpdatedAt()));
}
if (failed.isEmpty()) {
log.info("[notification-scan] 近 {} 分钟无失败任务", properties.getTaskFailedWindowMinutes());
return;
}
- String hour = LocalDateTime.now().format(HOUR_FORMAT);
Map> buckets = new LinkedHashMap<>();
for (FailedTask task : failed) {
String moduleType = normalizeModuleType(task.moduleType());
- buckets.computeIfAbsent(new BucketKey(task.userId(), moduleType, hour), key -> new ArrayList<>())
- .add(task);
+ buckets.computeIfAbsent(new BucketKey(task.userId(), moduleType, dayOf(task.updatedAt())),
+ key -> new ArrayList<>()).add(task);
}
NotificationDispatchService.AdminAudience audience = notificationDispatchService.prepareAdminAudience();
@@ -179,7 +178,7 @@ public class NotificationScanScheduler {
adminPushed += notificationDispatchService.pushToAdmins(audience,
NotificationService.SCENE_TASK_FAILED, NotificationService.LEVEL_WARNING,
"用户任务失败:" + username, adminContent,
- "task_failed_admin:" + key.userId() + ":" + key.moduleType() + ":" + key.hour(),
+ "task_failed_admin:" + key.userId() + ":" + key.moduleType() + ":" + key.day(),
key.userId());
}
log.info("[notification-scan] 任务失败扫描完成 窗口={}分钟 失败任务={} 聚合桶={} 用户通知={} 管理员通知={}",
@@ -255,7 +254,7 @@ public class NotificationScanScheduler {
}
}
- /** 探测结果上报:正常记 info;故障按小时去重推管理员通知;outcome=null 表示跳过。 */
+ /** 探测结果上报:正常记 info;故障按自然日去重推管理员通知;outcome=null 表示跳过。 */
private void reportProbe(String serviceKey, String serviceLabel, ProbeOutcome outcome) {
if (outcome == null) {
return;
@@ -265,12 +264,11 @@ public class NotificationScanScheduler {
return;
}
log.warn("[notification-scan] 服务探测失败 service={} detail={}", serviceLabel, outcome.detail());
- String hour = LocalDateTime.now().format(HOUR_FORMAT);
notificationDispatchService.pushToAdmins(NotificationService.SCENE_SERVICE_DOWN,
NotificationService.LEVEL_ERROR,
serviceLabel + "不可用",
serviceLabel + "探测失败:" + outcome.detail() + "。该服务相关任务可能大面积失败,请尽快排查。",
- "service_down:" + serviceKey + ":" + hour, null);
+ "service_down:" + serviceKey + ":" + dayOf(LocalDateTime.now()), null);
}
/** 通知保留期清理:每天最多一次;已读与未读各按自己的保留天数。 */
@@ -287,7 +285,12 @@ public class NotificationScanScheduler {
}
private String dedupeKeyOf(BucketKey key) {
- return "task_failed:" + key.userId() + ":" + key.moduleType() + ":" + key.hour();
+ return "task_failed:" + key.userId() + ":" + key.moduleType() + ":" + key.day();
+ }
+
+ /** 聚合桶的日期标签:取事件自身所属自然日,跨零点轮询时不会把昨天的失败挪进今天的桶。 */
+ private String dayOf(LocalDateTime at) {
+ return (at == null ? LocalDateTime.now() : at).format(DAY_FORMAT);
}
private String taskNoPreview(List tasks) {
@@ -355,12 +358,13 @@ public class NotificationScanScheduler {
return current.getClass().getSimpleName() + ": " + message;
}
- /** 聚合桶键:用户 × 模块 × 小时。 */
- record BucketKey(Long userId, String moduleType, String hour) {
+ /** 聚合桶键:用户 × 模块 × 自然日。 */
+ record BucketKey(Long userId, String moduleType, String day) {
}
- /** 统一视图的失败任务(两类表归一)。 */
- record FailedTask(Long id, String taskNo, String moduleType, Long userId, String errorMessage) {
+ /** 统一视图的失败任务(两类表归一);updatedAt 即失败终态时间,决定落入哪一天的桶。 */
+ record FailedTask(Long id, String taskNo, String moduleType, Long userId, String errorMessage,
+ LocalDateTime updatedAt) {
}
/** 探测结果。 */
diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/notification/service/NotificationService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/notification/service/NotificationService.java
index 883b6a4f1..bf225beaa 100644
--- a/backend-java/src/main/java/com/nanri/aiimage/modules/notification/service/NotificationService.java
+++ b/backend-java/src/main/java/com/nanri/aiimage/modules/notification/service/NotificationService.java
@@ -107,10 +107,11 @@ public class NotificationService {
}
/**
- * 同键推送或刷新:不存在则新建;已存在且内容有变化时更新内容并重置为未读
- * (用于小时桶聚合的增量更新:同小时内新增失败任务时刷新计数与明细)。
+ * 同键推送或刷新:不存在则新建;已存在且内容有变化时只更新文案,
+ * 不动 read_at(聚合通知的去重键按自然日,同一条一天内会被刷新很多次,
+ * 重新点亮已读等于把红点做成闹钟)。
*
- * @return true=新建或内容有更新(用户有新信息),false=无变化或去重未命中变化
+ * @return true=新建或内容有更新,false=无变化
*/
public boolean pushOrRefresh(Long userId, String audience, String scene, String level,
String title, String content, String dedupeKey) {
@@ -131,8 +132,7 @@ public class NotificationService {
.eq(UserNotificationEntity::getId, existing.getId())
.set(UserNotificationEntity::getTitle, nextTitle)
.set(UserNotificationEntity::getContent, nextContent)
- .set(UserNotificationEntity::getLevel, normalize(level).isEmpty() ? LEVEL_WARNING : level)
- .set(UserNotificationEntity::getReadAt, null));
+ .set(UserNotificationEntity::getLevel, normalize(level).isEmpty() ? LEVEL_WARNING : level));
log.info("[notification] 同键通知已刷新 id={} userId={} scene={} dedupeKey={}",
existing.getId(), userId, scene, key);
return true;
diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/MaixiangAnomalyScannerTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/MaixiangAnomalyScannerTest.java
index 685e8969d..16cf003e5 100644
--- a/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/MaixiangAnomalyScannerTest.java
+++ b/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/MaixiangAnomalyScannerTest.java
@@ -162,7 +162,7 @@ class MaixiangAnomalyScannerTest {
content.capture(), key.capture(), isNull());
assertThat(content.getValue()).contains("1 条任务失败");
assertThat(content.getValue()).contains("未注册的任务类型: price-track-run");
- assertThat(key.getValue()).isEqualTo("maixiang_fail:2026091512");
+ assertThat(key.getValue()).isEqualTo("maixiang_fail:20260915");
}
@Test
@@ -238,7 +238,7 @@ class MaixiangAnomalyScannerTest {
ArgumentCaptor content = ArgumentCaptor.forClass(String.class);
verify(dispatch).pushToAdmins(eq(audience), eq(NotificationService.SCENE_MAIXIANG_ANOMALY),
eq(NotificationService.LEVEL_WARNING), eq("麦象异常:麦象队列积压"),
- content.capture(), eq("maixiang_queue_backlog:2026091512"), isNull());
+ content.capture(), eq("maixiang_queue_backlog:20260915"), isNull());
assertThat(content.getValue()).contains("L1 待处理 210 / 处理中 0").contains("堆积且无人在消费");
}
@@ -263,7 +263,7 @@ class MaixiangAnomalyScannerTest {
newScanner().checkQueueBacklog(audience, NOW);
verify(dispatch).pushToAdmins(any(), anyString(), anyString(), anyString(), anyString(),
- eq("maixiang_queue_backlog:2026091512"), any());
+ eq("maixiang_queue_backlog:20260915"), any());
}
@Test
@@ -292,7 +292,7 @@ class MaixiangAnomalyScannerTest {
ArgumentCaptor content = ArgumentCaptor.forClass(String.class);
verify(dispatch).pushToAdmins(eq(audience), eq(NotificationService.SCENE_MAIXIANG_ANOMALY),
eq(NotificationService.LEVEL_WARNING), eq("麦象异常:采集机掉线"),
- content.capture(), eq("maixiang_silent:2026091512"), isNull());
+ content.capture(), eq("maixiang_silent:20260915"), isNull());
assertThat(content.getValue())
.contains("静默 11 分钟")
.contains("跟价 静默 11 分钟")
diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/NotificationDispatchServiceTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/NotificationDispatchServiceTest.java
index da2cac221..fa77f8f52 100644
--- a/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/NotificationDispatchServiceTest.java
+++ b/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/NotificationDispatchServiceTest.java
@@ -15,6 +15,7 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -64,13 +65,13 @@ class NotificationDispatchServiceTest {
NotificationDispatchService.AdminAudience audience = service.prepareAdminAudience();
int pushed = service.pushToAdmins(audience, NotificationService.SCENE_TASK_FAILED,
- NotificationService.LEVEL_WARNING, "标题", "内容", "task_failed_admin:20:PRICE_TRACK:2026091310", 20L);
+ NotificationService.LEVEL_WARNING, "标题", "内容", "task_failed_admin:20:PRICE_TRACK:20260913", 20L);
// 主管乙不可见用户 20 → 只有超管收到
assertThat(pushed).isEqualTo(1);
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:2026091310:1"));
+ eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:1"));
}
@Test
@@ -89,21 +90,54 @@ class NotificationDispatchServiceTest {
int pushed = service.pushToAdmins(NotificationService.SCENE_TASK_FAILED,
NotificationService.LEVEL_WARNING, "标题", "内容",
- "task_failed_admin:20:PRICE_TRACK:2026091310", 20L);
+ "task_failed_admin:20:PRICE_TRACK:20260913", 20L);
// 超管全量 + 本组主管各落一条,各带自己的 dedupe 后缀(已读状态互不影响)
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:2026091310:1"));
+ eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:1"));
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:2026091310:2"));
+ eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:2"));
// 非本组主管一条都不落
verify(notificationService, never()).pushOrRefresh(eq(3L), anyString(), anyString(),
anyString(), anyString(), anyString(), anyString());
}
+ /**
+ * 合并告警的权限口径:能看到组内任一号的管理员收 1 条,一个都看不到的收不到 —— 每人最多一条。
+ * 逐个主体调用 pushToAdmins 会让同一管理员为 N 个账号收到 N 条同内容通知。
+ */
+ @Test
+ void pushToAdminsAnyOfDeliversAtMostOnePerAdminSeeingAnySubject() {
+ AdminUserEntity superAdmin = admin(1L, "超管甲");
+ AdminUserEntity inScope = admin(2L, "主管乙");
+ AdminUserEntity outOfScope = admin(3L, "主管丙");
+ when(adminUserMapper.selectList(any())).thenReturn(List.of(superAdmin, inScope, outOfScope));
+ when(adminAuthSupport.currentRole(superAdmin)).thenReturn("super_admin");
+ when(adminAuthSupport.currentRole(inScope)).thenReturn("admin");
+ 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);
+
+ int pushed = service.pushToAdminsAnyOf(service.prepareAdminAudience(),
+ NotificationService.SCENE_SECRET_BALANCE, NotificationService.LEVEL_ERROR,
+ "标题", "内容", "secret_balance_admin:group:hash:20261002", List.of(11L, 12L, 20L));
+
+ // 3 个受影响账号 × 2 个可见管理员 = 只落 2 条;非本组主管一条都不落
+ assertThat(pushed).isEqualTo(2);
+ verify(notificationService, times(2)).pushOrRefresh(anyLong(), anyString(), anyString(),
+ anyString(), anyString(), anyString(), anyString());
+ 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"));
+ verify(notificationService, never()).pushOrRefresh(eq(3L), anyString(), anyString(),
+ anyString(), anyString(), anyString(), anyString());
+ }
+
@Test
void globalEventReachesEveryAdminByDesign() {
AdminUserEntity superAdmin = admin(1L, "超管甲");
@@ -120,7 +154,7 @@ class NotificationDispatchServiceTest {
// 服务探测失败这类全局事件(subjectUserId=null)按设计推给所有管理员,不受分组限制
int pushed = service.pushToAdmins(NotificationService.SCENE_SERVICE_DOWN,
NotificationService.LEVEL_ERROR, "品牌检测服务不可用", "探测失败",
- "service_down:brand-service:2026091310", null);
+ "service_down:brand-service:20260913", null);
assertThat(pushed).isEqualTo(3);
}
diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/NotificationScanSchedulerTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/NotificationScanSchedulerTest.java
index 0323a807a..cb95babf7 100644
--- a/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/NotificationScanSchedulerTest.java
+++ b/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/NotificationScanSchedulerTest.java
@@ -117,7 +117,89 @@ class NotificationScanSchedulerTest {
anyString(), anyString(), anyString(), anyString());
}
+ /**
+ * 同一天同模块的失败必须共用一条通知:按「扫描时刻的小时」分桶时,同一个失败任务
+ * 只要还落在 60 分钟回看窗口里,跨过整点就会被塞进新桶,于是每小时重发一条
+ * (2026-10-02 取证:task_failed 管理员侧因此 24 倍放大)。
+ */
+ @Test
+ void failedTasksOfSameDayShareOneDedupeKeyAcrossHours() {
+ when(fileTaskMapper.selectList(any())).thenReturn(List.of(
+ fileTask(101L, "T-101", "PRICE_TRACK", 7L, "浏览器启动失败", LocalDateTime.of(2026, 10, 1, 9, 12)),
+ fileTask(102L, "T-102", "PRICE_TRACK", 7L, "cookie 失效", LocalDateTime.of(2026, 10, 1, 18, 36))));
+ when(brandCrawlTaskMapper.selectList(any())).thenReturn(List.of());
+ stubAdminAudience();
+
+ newScheduler().scanFailedTasks();
+
+ ArgumentCaptor userKey = ArgumentCaptor.forClass(String.class);
+ verify(notificationService, times(1)).pushOrRefresh(eq(7L), eq(NotificationService.AUDIENCE_USER),
+ eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
+ anyString(), anyString(), userKey.capture());
+ assertThat(userKey.getValue()).isEqualTo("task_failed:7:PRICE_TRACK:20261001");
+
+ ArgumentCaptor adminKey = ArgumentCaptor.forClass(String.class);
+ verify(dispatch, times(1)).pushToAdmins(any(NotificationDispatchService.AdminAudience.class),
+ eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
+ anyString(), anyString(), adminKey.capture(), eq(7L));
+ assertThat(adminKey.getValue()).isEqualTo("task_failed_admin:7:PRICE_TRACK:20261001");
+ }
+
+ /** 桶按「任务自身所属自然日」而非扫描时钟:跨零点轮询时,昨晚的失败仍归昨晚那条通知。 */
+ @Test
+ void failedTasksOnDifferentDaysGetSeparateDedupeKeys() {
+ when(fileTaskMapper.selectList(any())).thenReturn(List.of(
+ fileTask(101L, "T-101", "PRICE_TRACK", 7L, "浏览器启动失败", LocalDateTime.of(2026, 10, 1, 23, 50)),
+ fileTask(102L, "T-102", "PRICE_TRACK", 7L, "cookie 失效", LocalDateTime.of(2026, 10, 2, 0, 10))));
+ when(brandCrawlTaskMapper.selectList(any())).thenReturn(List.of());
+ stubAdminAudience();
+
+ newScheduler().scanFailedTasks();
+
+ ArgumentCaptor userKey = ArgumentCaptor.forClass(String.class);
+ verify(notificationService, times(2)).pushOrRefresh(anyLong(), anyString(), anyString(), anyString(),
+ anyString(), anyString(), userKey.capture());
+ assertThat(userKey.getAllValues()).containsExactlyInAnyOrder(
+ "task_failed:7:PRICE_TRACK:20261001", "task_failed:7:PRICE_TRACK:20261002");
+ }
+
+ /**
+ * 服务探测故障:去重键按天,同一天同服务只提醒一次(小时桶时一个持续 503 的上游
+ * 每小时给每位管理员各塞一条)。取精确 8 位日期,多一位小时都不行。
+ */
+ @Test
+ void serviceDownAlertIsDedupedPerCalendarDay() {
+ properties.setBrandServiceUrl("http://127.0.0.1:1");
+ properties.setPriceTrackApiUrl("");
+ properties.setJikipProbeEnabled(false);
+ when(dispatch.pushToAdmins(anyString(), anyString(), anyString(), anyString(), anyString(), any()))
+ .thenReturn(1);
+
+ newScheduler().probeServices();
+
+ ArgumentCaptor keyBase = ArgumentCaptor.forClass(String.class);
+ verify(dispatch).pushToAdmins(eq(NotificationService.SCENE_SERVICE_DOWN),
+ eq(NotificationService.LEVEL_ERROR), eq("品牌检测服务不可用"), anyString(),
+ keyBase.capture(), org.mockito.ArgumentMatchers.isNull());
+ assertThat(keyBase.getValue()).matches("service_down:brand-service:\\d{8}");
+ }
+
+ private void stubAdminAudience() {
+ when(dispatch.prepareAdminAudience()).thenReturn(
+ new NotificationDispatchService.AdminAudience(List.of(), Set.of(), Map.of()));
+ when(dispatch.displayNameOf(anyLong())).thenReturn("张三");
+ when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
+ .thenReturn(true);
+ when(dispatch.pushToAdmins(any(NotificationDispatchService.AdminAudience.class), anyString(), anyString(),
+ anyString(), anyString(), anyString(), any())).thenReturn(1);
+ }
+
private FileTaskEntity fileTask(Long id, String taskNo, String moduleType, Long userId, String errorMessage) {
+ return fileTask(id, taskNo, moduleType, userId, errorMessage, LocalDateTime.of(2026, 10, 1, 18, 36));
+ }
+
+ private FileTaskEntity fileTask(Long id, String taskNo, String moduleType, Long userId, String errorMessage,
+ LocalDateTime updatedAt) {
FileTaskEntity task = new FileTaskEntity();
task.setId(id);
task.setTaskNo(taskNo);
@@ -125,7 +207,7 @@ class NotificationScanSchedulerTest {
task.setUserId(userId);
task.setErrorMessage(errorMessage);
task.setStatus("FAILED");
- task.setUpdatedAt(LocalDateTime.now());
+ task.setUpdatedAt(updatedAt);
return task;
}
}
diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/NotificationServiceTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/NotificationServiceTest.java
index 677f044d8..5303fe119 100644
--- a/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/NotificationServiceTest.java
+++ b/backend-java/src/test/java/com/nanri/aiimage/modules/notification/service/NotificationServiceTest.java
@@ -84,23 +84,34 @@ class NotificationServiceTest {
verify(mapper, never()).insert(any(UserNotificationEntity.class));
}
+ /**
+ * 聚合通知按自然日只有一条,一整天会被反复刷新:内容有变化时只改文案,
+ * 绝不能把 read_at 置空——否则管理员刚读完红点又亮,一天点亮几十次
+ * (2026-10-02 后台超管 582 条未读的主放大器之一)。
+ */
@Test
- void pushOrRefreshUpdatesContentAndResetsUnread() {
+ @SuppressWarnings("unchecked")
+ void pushOrRefreshUpdatesContentButKeepsReadState() {
UserNotificationEntity existing = new UserNotificationEntity();
existing.setId(9L);
existing.setTitle("跟价任务失败");
existing.setContent("最近 60 分钟内有 2 个跟价任务失败");
existing.setLevel("warning");
- existing.setReadAt(LocalDateTime.now());
+ existing.setReadAt(LocalDateTime.of(2026, 9, 13, 10, 0));
when(mapper.selectOne(any())).thenReturn(existing);
boolean refreshed = service.pushOrRefresh(7L, NotificationService.AUDIENCE_ADMIN,
NotificationService.SCENE_TASK_FAILED, NotificationService.LEVEL_WARNING,
- "跟价任务失败", "最近 60 分钟内有 5 个跟价任务失败", "task_failed:7:PRICE_TRACK:2026091310");
+ "跟价任务失败", "最近 60 分钟内有 5 个跟价任务失败", "task_failed:7:PRICE_TRACK:20260913");
assertThat(refreshed).isTrue();
verify(mapper, never()).insert(any(UserNotificationEntity.class));
- verify(mapper, times(1)).update(any(), any());
+ ArgumentCaptor> captor =
+ ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
+ verify(mapper, times(1)).update(any(), captor.capture());
+ String sqlSet = captor.getValue().getSqlSet();
+ assertThat(sqlSet).contains("title").contains("content").contains("level");
+ assertThat(sqlSet).doesNotContain("read_at");
}
@Test
@@ -113,7 +124,7 @@ class NotificationServiceTest {
boolean refreshed = service.pushOrRefresh(7L, NotificationService.AUDIENCE_USER,
NotificationService.SCENE_TASK_FAILED, NotificationService.LEVEL_WARNING,
- "跟价任务失败", "最近 60 分钟内有 2 个跟价任务失败", "task_failed:7:PRICE_TRACK:2026091310");
+ "跟价任务失败", "最近 60 分钟内有 2 个跟价任务失败", "task_failed:7:PRICE_TRACK:20260913");
assertThat(refreshed).isFalse();
verify(mapper, never()).update(any(), any());