feat(通知): task_failed 带 ref_json 定位锚点,明细可点直达任务详情

用户原话「都没体现哪个任务id/店铺/用户,咋排查」:通知表只有 title/content,
失败任务又按「用户×模块×自然日」聚合成一条,明细被 5 个 taskNo 预览 + 512 字截断吃掉。

- V162 给 biz_user_notification 加 ref_json(TEXT,可重跑迁移,存量不回填)
- 扫描器把桶内每个失败任务写成锚点(taskId/taskNo/moduleType/reason/updatedAt/
  deviceId),上限 20 条;品牌任务无 task_no 用 #<id> 兜底,保证至少一条可定位
- 详情接口回传 refs;同键刷新时锚点变化也更新,且不重新点亮已读
- 后台铃铛「展开明细」渲染成可点行,跳任务中心 ?taskNo= 自动开详情抽屉
- 新增判据 taskFailedAdminNotificationCarriesUidAndTaskNoAnchor:管理端正文必须含
  uid、每个桶的 ref_json 至少一条非空 taskNo
This commit is contained in:
2026-10-22 10:28:12 +08:00
parent 78be0f02e2
commit d268ecdf6b
15 changed files with 361 additions and 36 deletions
@@ -13,6 +13,17 @@ export const ADMIN_NOTIFICATION_SEVERITY_LABELS: Readonly<Record<AdminNotificati
low: '低危',
}
/** 通知里的结构化定位锚点(当前只有 task_failed 使用:桶内每个失败任务一项)。 */
export interface AdminNotificationRef {
taskId: number | null
/** 任务号;品牌任务为 #<id>。任务详情接口按它查。 */
taskNo: string
moduleType?: string | null
reason?: string | null
updatedAt?: string | null
deviceId?: string | null
}
/** 单条通知(后台铃铛)。 */
export interface AdminNotificationItem {
id: number
@@ -22,6 +33,8 @@ export interface AdminNotificationItem {
severity?: string
title: string
content: string
/** 可点的定位锚点;旧后端/历史行没有这一列时为空。 */
refs?: AdminNotificationRef[] | null
read: boolean
readAt: string | null
createdAt: string | null
@@ -140,6 +140,18 @@
<span class="bell-item-time">{{ formatTime(item.createdAt) }}</span>
</div>
<div class="bell-item-content">{{ item.content }}</div>
<div v-if="item.refs && item.refs.length" class="bell-ref-list">
<button
v-for="ref in item.refs"
:key="`${item.id}-${ref.taskNo}`"
type="button"
class="bell-ref-link"
:title="ref.reason || `查看任务 ${ref.taskNo}`"
@click.stop="openTaskRef(item, ref)"
>
{{ ref.taskNo }}<span v-if="ref.reason" class="bell-ref-reason">:{{ ref.reason }}</span>
</button>
</div>
</li>
<li v-if="!detailLoading && detailTotal > details.length" class="bell-detail-more">
另有 {{ detailTotal - details.length }} 条未列出,可缩小日期范围后查看
@@ -175,14 +187,17 @@
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAdminSessionStore } from '@/stores/admin-session'
import type { AdminNotificationItem, AdminNotificationRef } from '@/api/notifications'
import {
NOTIFICATION_POLL_INTERVAL_MS,
formatDayLabel,
formatGroupCounts,
formatNotificationTime,
notificationGroupKey,
taskCenterRouteForRef,
} from '@/layout/notification-bell-model'
import { todayDateInput } from '@/utils/datetime'
import {
@@ -194,6 +209,7 @@ import {
} from '@/layout/notification-bell-panel'
const session = useAdminSessionStore()
const router = useRouter()
/**
* 面板的数据流(聚合组、明细、两个计数、防抖与取数)整块在 notification-bell-panel.ts。
@@ -231,6 +247,16 @@ const {
unreadCount,
} = useNotificationBellPanel({ uid: () => session.user?.id ?? 0, today: () => todayDateInput() })
/** 点锚点:先按原逻辑标已读,再跳任务中心(路由带 taskNo,页面进来自动开详情抽屉)。 */
function openTaskRef(item: AdminNotificationItem, ref: AdminNotificationRef): void {
const target = taskCenterRouteForRef(ref)
if (!target) {
return
}
void onItemClick(item)
void router.push(target)
}
const rootRef = ref<HTMLElement | null>(null)
const panelRef = ref<HTMLElement | null>(null)
const panelStyle = ref<Record<string, string>>({})
@@ -592,6 +618,12 @@ onUnmounted(() => {
word-break: break-all;
}
/* 定位锚点:任务号可点,直达任务详情。压低视觉权重,不与正文抢注意力。 */
.bell-ref-list { display: flex; flex-direction: column; gap: 2px; margin-top: 6px; }
.bell-ref-link { padding: 0; border: none; background: none; color: var(--admin-primary, #2f5d8b); font-family: inherit; font-size: 12px; line-height: 1.5; text-align: left; word-break: break-all; cursor: pointer; }
.bell-ref-link:hover { text-decoration: underline; }
.bell-ref-reason { color: #8a94a6; }
.bell-search {
display: flex;
flex-direction: column;
@@ -201,3 +201,22 @@ export function createSummaryFailureAlerter(feedback: BellFeedbackSink): {
},
}
}
/** 通知锚点的最小形状(与 AdminNotificationRef 对齐);不 import api 类型,保持本模块可被 node --test 直接跑。 */
export interface NotificationTaskRef {
taskNo?: string | null
}
/**
* 任务锚点 → 任务中心深链。taskNo 是任务详情接口的唯一入参,空值不给链接
* (宁可只显示文本,也不跳到一个必然查不到的任务上)。
*/
export function taskCenterRouteForRef(
ref: NotificationTaskRef | null | undefined,
): { path: string; query: { taskNo: string } } | null {
const taskNo = String(ref?.taskNo ?? '').trim()
if (!taskNo) {
return null
}
return { path: '/task-center/board', query: { taskNo } }
}
@@ -4,6 +4,7 @@
* 页签二「变体采集」= 麦象批量任务(variant-collection),数据口径与列不同故独立页签。
* 30s 轮询:页面隐藏暂停、回前台立即刷新、卸载清理;另有手动刷新。 */
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { userNotice } from '@/api/user-notice'
import { ElMessage } from 'element-plus'
import OldPagination from '@/components/OldPagination.vue'
@@ -51,6 +52,7 @@ const POLL_INTERVAL_MS = 30_000
/** 公司 tab 的唯一取值出口:非超管恒 null(store 里 companyIdForRequest 已经把它算成 null),
* 所以这里不需要再判一次角色——第二把尺子就是第二个口径。 */
const companyTab = useCompanyTabStore()
const route = useRoute()
type BoardTab = 'tasks' | 'variant'
const activeTab = ref<BoardTab>('tasks')
@@ -251,12 +253,12 @@ function changeVariantSize(size: number) {
// ---------------------------------------------------------------- 详情
async function openDetail(row: TaskCenterTaskRow) {
async function openDetailByTaskNo(taskNo: string, companyId: number | null = companyTab.requestCompanyId) {
detailVisible.value = true
detailLoading.value = true
detail.value = null
try {
detail.value = await fetchTaskCenterTaskDetail(row.taskNo, companyTab.requestCompanyId)
detail.value = await fetchTaskCenterTaskDetail(taskNo, companyId)
if (!detail.value) ElMessage.warning('任务不存在或无权查看')
} catch (error) {
showAdminFeedback(errorText(error, '任务详情加载失败'), 'error')
@@ -266,6 +268,10 @@ async function openDetail(row: TaskCenterTaskRow) {
}
}
async function openDetail(row: TaskCenterTaskRow) {
await openDetailByTaskNo(row.taskNo)
}
function accountOf(row: TaskCenterTaskRow): string {
return row.username || (row.userId != null ? `UID ${row.userId}` : '—')
}
@@ -291,6 +297,11 @@ function onVisibilityChange() {
onMounted(() => {
void refreshAll()
void loadInactiveTabTotal()
// 通知明细里的 taskNo 深链:进页直接开抽屉;不锁当前公司 tab(通知可能来自另一家,后端仍按数据权限收口)。
const linkedTaskNo = typeof route.query.taskNo === 'string' ? route.query.taskNo.trim() : ''
if (linkedTaskNo) {
void openDetailByTaskNo(linkedTaskNo, null)
}
document.addEventListener('visibilitychange', onVisibilityChange)
pollTimer = setInterval(() => {
if (typeof document !== 'undefined' && document.visibilityState !== 'visible') return
@@ -2,7 +2,7 @@
"note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。",
"totals": {
"files": 244,
"cases": 1727,
"cases": 1728,
"pins": 448,
"reads": 639
},
@@ -303,7 +303,7 @@
"reads": 2
},
"notification-bell.test.ts": {
"cases": 7,
"cases": 8,
"pins": 0,
"reads": 0
},
@@ -9,6 +9,7 @@ import {
hasNewNotification,
readLastNotifiedId,
writeLastNotifiedId,
taskCenterRouteForRef,
} from '../src/layout/notification-bell-model.ts'
function createStorage() {
@@ -110,3 +111,18 @@ test('test_组行计数文案:读完不再挂 0 未读', () => {
assert.equal(formatGroupCounts(12, 0), '12 条')
assert.equal(formatGroupCounts(1, null), '1 条')
})
test('test_任务锚点深链:按 taskNo 跳任务中心,空锚点不给链接', () => {
assert.deepEqual(taskCenterRouteForRef({ taskNo: 'DELETE_BRAND-101' }), {
path: '/task-center/board',
query: { taskNo: 'DELETE_BRAND-101' },
})
assert.deepEqual(taskCenterRouteForRef({ taskNo: ' #201 ' }), {
path: '/task-center/board',
query: { taskNo: '#201' },
})
assert.equal(taskCenterRouteForRef({ taskNo: '' }), null)
assert.equal(taskCenterRouteForRef({ taskNo: ' ' }), null)
assert.equal(taskCenterRouteForRef(null), null)
assert.equal(taskCenterRouteForRef(undefined), null)
})
@@ -23,6 +23,8 @@ public class UserNotificationEntity {
private String severity;
private String title;
private String content;
/** 结构化定位锚点 JSON(V162);null=该通知没有可点对象(存量行、服务级告警)。 */
private String refJson;
private String dedupeKey;
private LocalDateTime readAt;
private LocalDateTime createdAt;
@@ -3,6 +3,7 @@ package com.nanri.aiimage.modules.notification.model.vo;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/** 单条通知(桌面端与后台共用结构)。 */
@Data
@@ -19,6 +20,8 @@ public class NotificationItemVo {
private String severity;
private String title;
private String content;
/** 可点击的定位锚点(task_failed=桶内失败任务);null/空=该条没有可点对象。 */
private List<NotificationRefVo> refs;
/** 是否已读(前端展示用,等价于 readAt 非空) */
private Boolean read;
private LocalDateTime readAt;
@@ -0,0 +1,29 @@
package com.nanri.aiimage.modules.notification.model.vo;
import lombok.Data;
/**
* 通知的结构化定位锚点(ref_json 里的一项)。
*
* <p>当前只有 task_failed 使用:桶内每个失败任务一项。它是「点一下能跳到任务详情」
* 的唯一依据,正文里的自然语言只负责让人看懂,不承担定位职责。
*
* <p>字段全部按 JSON 原样回给前端;不认识的字段由反序列化层忽略——后续加锚点类型时
* 不至于让老 jar 读不出来。
*/
@Data
public class NotificationRefVo {
/** 失败任务主键(biz_file_task.id / brand_crawl_tasks.id)。 */
private Long taskId;
/** 任务号(品牌任务无 task_no 列,用 #&lt;id&gt; 兜底),任务详情接口按它查。 */
private String taskNo;
/** 模块类型原码(DELETE_BRAND / PRICE_TRACK / BRAND …)。 */
private String moduleType;
/** 该任务的失败原因(已压缩空白,最长 120 字)。 */
private String reason;
/** 任务进入失败终态的时间(yyyy-MM-dd HH:mm:ss)。 */
private String updatedAt;
/** 执行任务的客户端设备 id(历史任务为空)。 */
private String deviceId;
}
@@ -57,6 +57,15 @@ public class NotificationDispatchService {
*/
public int pushToAdmins(AdminAudience audience, String scene, String level, String title, String content,
String dedupeKeyBase, Long subjectUserId) {
return pushToAdmins(audience, scene, level, title, content, dedupeKeyBase, subjectUserId, null);
}
/**
* 同 {@link #pushToAdmins(AdminAudience, String, String, String, String, String, Long)},
* 额外带一份结构化定位锚点(任务失败桶的明细),供后台「展开明细」渲染成可点行。
*/
public int pushToAdmins(AdminAudience audience, String scene, String level, String title, String content,
String dedupeKeyBase, Long subjectUserId, String refJson) {
int pushed = 0;
int filtered = 0;
for (AdminUserEntity admin : audience.admins()) {
@@ -66,7 +75,7 @@ public class NotificationDispatchService {
}
String key = dedupeKeyBase + ":" + admin.getId();
if (notificationService.pushOrRefresh(admin.getId(), NotificationService.AUDIENCE_ADMIN,
scene, level, title, content, key, subjectUserId)) {
scene, level, title, content, key, subjectUserId, refJson)) {
pushed++;
}
}
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.notification.service;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.config.HttpClientPool;
import com.nanri.aiimage.config.NotificationProperties;
@@ -51,8 +52,11 @@ public class NotificationScanScheduler {
private static final String BRAND_MODULE_TYPE = "BRAND";
private static final int MAX_TASK_NO_PREVIEW = 5;
/** 锚点条数上限:正文只放 5 个任务号,结构化锚点要能覆盖同桶多数失败,但不能让积压把行撑爆。 */
private static final int MAX_TASK_REF = 20;
private static final int REASON_MAX_LENGTH = 120;
private static final int PROBE_READ_TIMEOUT_MILLIS = 8_000;
private static final DateTimeFormatter REF_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
/**
* 18960 的探针路径。根路径没有路由,恒 404 ⇒ 这一格只能读成「未验证」,
@@ -117,7 +121,8 @@ public class NotificationScanScheduler {
List<FailedTask> failed = new ArrayList<>();
List<FileTaskEntity> fileTasks = fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
.select(FileTaskEntity::getId, FileTaskEntity::getTaskNo, FileTaskEntity::getModuleType,
FileTaskEntity::getUserId, FileTaskEntity::getErrorMessage, FileTaskEntity::getUpdatedAt)
FileTaskEntity::getUserId, FileTaskEntity::getErrorMessage, FileTaskEntity::getUpdatedAt,
FileTaskEntity::getDeviceId)
.eq(FileTaskEntity::getStatus, STATUS_FAILED)
.gt(FileTaskEntity::getUpdatedAt, cutoff)
.orderByDesc(FileTaskEntity::getId)
@@ -127,7 +132,8 @@ public class NotificationScanScheduler {
continue;
}
failed.add(new FailedTask(task.getId(), displayTaskNo(task.getTaskNo(), task.getId()),
task.getModuleType(), task.getUserId(), task.getErrorMessage(), task.getUpdatedAt()));
task.getModuleType(), task.getUserId(), task.getErrorMessage(), task.getUpdatedAt(),
task.getDeviceId()));
}
List<BrandCrawlTaskEntity> brandTasks = brandCrawlTaskMapper.selectList(new LambdaQueryWrapper<BrandCrawlTaskEntity>()
.select(BrandCrawlTaskEntity::getId, BrandCrawlTaskEntity::getUserId,
@@ -141,7 +147,7 @@ public class NotificationScanScheduler {
continue;
}
failed.add(new FailedTask(task.getId(), "#" + task.getId(),
BRAND_MODULE_TYPE, task.getUserId(), task.getErrorMessage(), task.getUpdatedAt()));
BRAND_MODULE_TYPE, task.getUserId(), task.getErrorMessage(), task.getUpdatedAt(), null));
}
if (failed.isEmpty()) {
log.info("[notification-scan] 近 {} 分钟无失败任务", properties.getTaskFailedWindowMinutes());
@@ -170,9 +176,10 @@ public class NotificationScanScheduler {
+ (preview.isEmpty() ? "" : "(" + preview + ")")
+ (reason.isEmpty() ? "" : ";最近失败原因:" + reason)
+ ",详情请查看对应工具页的「历史任务」。";
String refJson = refJsonOf(tasks);
if (notificationService.pushOrRefresh(key.userId(), NotificationService.AUDIENCE_USER,
NotificationService.SCENE_TASK_FAILED, NotificationService.LEVEL_WARNING,
label + "任务失败", userContent, dedupeKeyOf(key))) {
label + "任务失败", userContent, dedupeKeyOf(key), null, refJson)) {
userPushed++;
}
@@ -185,7 +192,7 @@ public class NotificationScanScheduler {
NotificationService.SCENE_TASK_FAILED, NotificationService.LEVEL_WARNING,
"用户任务失败:" + username, adminContent,
"task_failed_admin:" + key.userId() + ":" + key.moduleType() + ":" + key.day(),
key.userId());
key.userId(), refJson);
}
log.info("[notification-scan] 任务失败扫描完成 窗口={}分钟 失败任务={} 聚合桶={} 用户通知={} 管理员通知={}",
properties.getTaskFailedWindowMinutes(), failed.size(), buckets.size(), userPushed, adminPushed);
@@ -390,14 +397,45 @@ public class NotificationScanScheduler {
private String latestReason(List<FailedTask> tasks) {
for (FailedTask task : tasks) {
if (task.errorMessage() != null && !task.errorMessage().isBlank()) {
String reason = task.errorMessage().trim().replaceAll("\\s+", " ");
return reason.length() <= REASON_MAX_LENGTH ? reason : reason.substring(0, REASON_MAX_LENGTH) + "…";
String reason = shortReason(task.errorMessage());
if (reason != null) {
return reason;
}
}
return "";
}
/**
* 桶内失败任务的结构化锚点(ref_json):每个任务一项,最多 {@link #MAX_TASK_REF} 条。
* 正文里的 taskNo 预览只有 5 个且会被 512 字截断,锚点是「点一下到任务详情」的唯一依据,
* 所以 taskNo 必须非空——fileTask 由 displayTaskNo 兜底,品牌任务用 #&lt;id&gt;。
*/
String refJsonOf(List<FailedTask> tasks) {
List<Map<String, Object>> refs = new ArrayList<>(Math.min(tasks.size(), MAX_TASK_REF));
for (FailedTask task : tasks) {
if (refs.size() >= MAX_TASK_REF) {
break;
}
Map<String, Object> ref = new LinkedHashMap<>();
ref.put("taskId", task.id());
ref.put("taskNo", task.taskNo());
ref.put("moduleType", task.moduleType());
ref.put("reason", shortReason(task.errorMessage()));
ref.put("updatedAt", task.updatedAt() == null ? null : task.updatedAt().format(REF_TIME_FORMAT));
ref.put("deviceId", task.deviceId());
refs.add(ref);
}
return JSONUtil.toJsonStr(refs);
}
private String shortReason(String raw) {
if (raw == null || raw.isBlank()) {
return null;
}
String reason = raw.trim().replaceAll("\\s+", " ");
return reason.length() <= REASON_MAX_LENGTH ? reason : reason.substring(0, REASON_MAX_LENGTH) + "…";
}
private String displayTaskNo(String taskNo, Long id) {
return taskNo == null || taskNo.isBlank() ? "#" + id : taskNo;
}
@@ -446,7 +484,7 @@ public class NotificationScanScheduler {
/** 统一视图的失败任务(两类表归一);updatedAt 即失败终态时间,决定落入哪一天的桶。 */
record FailedTask(Long id, String taskNo, String moduleType, Long userId, String errorMessage,
LocalDateTime updatedAt) {
LocalDateTime updatedAt, String deviceId) {
}
/** 探测三态:ALIVE=业务可用;UNVERIFIED=服务回了话但证不了业务可用;DOWN=故障。 */
@@ -1,5 +1,6 @@
package com.nanri.aiimage.modules.notification.service;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
@@ -10,6 +11,7 @@ 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.NotificationRefVo;
import com.nanri.aiimage.modules.notification.model.vo.NotificationSummaryVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -86,6 +88,8 @@ public class NotificationService {
private static final int TITLE_MAX_LENGTH = 128;
private static final int CONTENT_MAX_LENGTH = 512;
private static final int DEDUPE_KEY_MAX_LENGTH = 160;
/** ref_json 的安全上限:TEXT 能装 64KB,但一条通知的锚点超过这个量级说明聚合失控,整条丢弃。 */
private static final int REF_JSON_MAX_LENGTH = 4000;
/** 严重度排序表达式:与 {@link #severityRank} 同一口径,数据库侧分页必须同序。 */
private static final String SEVERITY_ORDER_SQL =
@@ -111,6 +115,18 @@ public class NotificationService {
*/
public boolean push(Long userId, String audience, String scene, String level,
String title, String content, String dedupeKey, Long subjectUserId) {
return push(userId, audience, scene, level, title, content, dedupeKey, subjectUserId, null);
}
/**
* 推送一条通知(带结构化定位锚点)。
*
* @param refJson 可点的定位对象(JSON 数组字符串,见 {@link NotificationRefVo});null=没有。
* 超长时整条丢弃而不是截断:截断后的 JSON 前端解析不出来,比没有更糟。
*/
public boolean push(Long userId, String audience, String scene, String level,
String title, String content, String dedupeKey, Long subjectUserId,
String refJson) {
if (userId == null || userId <= 0) {
log.warn("[notification] 推送被跳过:接收者无效 userId={} scene={}", userId, scene);
return false;
@@ -133,6 +149,7 @@ public class NotificationService {
row.setSeverity(severityOf(normalizedScene, normalizedLevel));
row.setTitle(truncate(title, TITLE_MAX_LENGTH));
row.setContent(truncate(content == null ? "" : content, CONTENT_MAX_LENGTH));
row.setRefJson(normalizeRefJson(refJson));
row.setDedupeKey(truncate(key, DEDUPE_KEY_MAX_LENGTH));
row.setCreatedAt(LocalDateTime.now());
try {
@@ -162,17 +179,25 @@ public class NotificationService {
public boolean pushOrRefresh(Long userId, String audience, String scene, String level,
String title, String content, String dedupeKey, Long subjectUserId) {
return pushOrRefresh(userId, audience, scene, level, title, content, dedupeKey, subjectUserId, null);
}
public boolean pushOrRefresh(Long userId, String audience, String scene, String level,
String title, String content, String dedupeKey, Long subjectUserId,
String refJson) {
String key = normalize(dedupeKey);
if (key.isEmpty()) {
return push(userId, audience, scene, level, title, content, key, subjectUserId);
return push(userId, audience, scene, level, title, content, key, subjectUserId, refJson);
}
UserNotificationEntity existing = selectByDedupeKey(key);
if (existing == null) {
return push(userId, audience, scene, level, title, content, key, subjectUserId);
return push(userId, audience, scene, level, title, content, key, subjectUserId, refJson);
}
String nextTitle = truncate(title, TITLE_MAX_LENGTH);
String nextContent = truncate(content == null ? "" : content, CONTENT_MAX_LENGTH);
if (nextContent.equals(existing.getContent()) && nextTitle.equals(existing.getTitle())) {
String nextRefJson = normalizeRefJson(refJson);
if (nextContent.equals(existing.getContent()) && nextTitle.equals(existing.getTitle())
&& java.util.Objects.equals(nextRefJson, existing.getRefJson())) {
return false;
}
String normalizedScene = normalize(scene).isEmpty() ? SCENE_SYSTEM : normalize(scene);
@@ -181,6 +206,7 @@ public class NotificationService {
.eq(UserNotificationEntity::getId, existing.getId())
.set(UserNotificationEntity::getTitle, nextTitle)
.set(UserNotificationEntity::getContent, nextContent)
.set(UserNotificationEntity::getRefJson, nextRefJson)
.set(UserNotificationEntity::getLevel, normalizedLevel)
.set(UserNotificationEntity::getSeverity, severityOf(normalizedScene, normalizedLevel)));
log.info("[notification] 同键通知已刷新 id={} userId={} scene={} dedupeKey={}",
@@ -623,6 +649,7 @@ public class NotificationService {
vo.setSeverity(normalizeSeverity(row.getSeverity(), row.getScene(), row.getLevel()));
vo.setTitle(row.getTitle());
vo.setContent(row.getContent());
vo.setRefs(parseRefs(row.getRefJson()));
vo.setRead(row.getReadAt() != null);
vo.setReadAt(row.getReadAt());
vo.setCreatedAt(row.getCreatedAt());
@@ -637,4 +664,26 @@ public class NotificationService {
String normalized = value == null ? "" : value.trim();
return normalized.length() <= maxLength ? normalized : normalized.substring(0, maxLength);
}
/** 锚点落库前的唯一口径:空串归一成 NULL,超长整条丢弃(截断会产出不可解析的 JSON)。 */
private static String normalizeRefJson(String refJson) {
String value = normalize(refJson);
if (value.isEmpty()) {
return null;
}
if (value.length() > REF_JSON_MAX_LENGTH) {
log.warn("[notification] 定位锚点超长已丢弃 长度={} 上限={}", value.length(), REF_JSON_MAX_LENGTH);
return null;
}
return value;
}
/** 读取时解析锚点:ref_json 只由本服务写入(且超长整条丢弃),不存在解析失败的分支。 */
private List<NotificationRefVo> parseRefs(String refJson) {
String value = normalize(refJson);
if (value.isEmpty()) {
return null;
}
return JSONUtil.toList(value, NotificationRefVo.class);
}
}
@@ -0,0 +1,51 @@
-- =============================================================
-- 迁移 V162__notification_ref_json
--
-- 1. 变更目的:给站内通知补「结构化定位锚点」列(2026-10-21 需求)。
-- 用户原话:「都没体现 哪个任务id 或者 店铺 或用户啥的关键信息 咋排查」。
-- 现状:biz_user_notification 只有 title(128)/content(512),task_failed 又按
-- 「用户 × 模块 × 自然日」聚合成一条,明细被 taskNoPreview(最多 5 个) + 最近
-- 一条原因(截 120) 压缩,且 content 再截 512 ⇒ 同桶其余任务连任务号都看不到。
-- 加这一列后,扫描器把桶内每个失败任务写成 JSON(taskId/taskNo/moduleType/
-- reason/updatedAt/deviceId),后台「展开明细」渲染成可点行、直达任务详情。
--
-- 2. 为什么不是把正文放宽:content 是给桌面用户看的自然语言,长度由 UI 决定;
-- 结构化定位信息要能被程序消费(跳转、对齐),混在一段文本里只能靠正则捞。
--
-- 3. 为什么用 TEXT 不用 JSON 类型:MySQL JSON 列在 JDBC 侧同样回字符串,
-- 但会给「老的 jar 不认识这一列」的回滚场景多绑一个数据库版本前提;
-- TEXT 与 V116 既有风格一致,可重跑、可直接 SHOW。
--
-- 4. 存量行:ref_json 保持 NULL(不回填)。历史 task_failed 通知的明细在聚合时
-- 就已丢弃,回填只能靠正则解析文案,正是本项目一直拒绝的做法。
--
-- 5. 锁表风险:低。TEXT NULL ADD COLUMN 在 MySQL 8 走 INSTANT(不重建表)。
-- 刻意不加索引:这一列只随明细行整体读出,从不做条件筛选。
--
-- 6. 验证 SQL(迁移后跑):
-- SHOW COLUMNS FROM `biz_user_notification` LIKE 'ref_json';
-- -> 期望 1 行:Type=text,Null=YES
-- SELECT id, scene, LEFT(ref_json, 120) FROM biz_user_notification
-- WHERE scene='task_failed' ORDER BY id DESC LIMIT 3;
-- -> 新产生的行应能看到 [{"taskId":...,"taskNo":"...
--
-- 7. 可重跑性:照 V146/V155/V157/V158/V161 惯例,加列前先查 information_schema;
-- 迁移中途失败时 flyway repair + 重启会从第一条语句重跑,裸 ADD COLUMN 会撞 1060。
--
-- 8. 回滚(人工补丁,写成注释以免被 Flyway 当迁移执行):
-- ALTER TABLE `biz_user_notification` DROP COLUMN `ref_json`;
-- 仅回滚 jar 不需要 DROP:旧 jar 的实体没有这一列,INSERT 不会写它。
-- =============================================================
SET @has_col := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_user_notification'
AND COLUMN_NAME = 'ref_json'
);
SET @ddl := IF(@has_col = 0,
'ALTER TABLE `biz_user_notification` ADD COLUMN `ref_json` TEXT NULL COMMENT ''结构化定位锚点 JSON(task_failed=桶内失败任务清单)'' AFTER `content`',
'SELECT ''biz_user_notification.ref_json already exists, skipped'' AS note');
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -73,7 +73,7 @@ class NotificationDispatchServiceTest {
// 第 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(20L));
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:1"), eq(20L), isNull());
}
@Test
@@ -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(20L));
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:1"), eq(20L), isNull());
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(20L));
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:2"), eq(20L), isNull());
// 非本组主管一条都不落
verify(notificationService, never()).pushOrRefresh(eq(3L), anyString(), anyString(),
anyString(), anyString(), anyString(), anyString(), any());
anyString(), anyString(), anyString(), anyString(), any(), anyString());
}
/**
@@ -179,7 +179,7 @@ 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"), eq(20L));
contains("用户"), anyString(), eq("task_partial_admin:3301:1"), eq(20L), isNull());
}
@Test
@@ -216,6 +216,8 @@ class NotificationDispatchServiceTest {
anyString(), anyString(), anyString())).thenReturn(true);
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(),
anyString(), anyString(), anyString(), any())).thenReturn(true);
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(),
anyString(), anyString(), anyString(), any(), any())).thenReturn(true);
}
private AdminUserEntity admin(Long id, String username) {
@@ -68,18 +68,19 @@ class NotificationScanSchedulerTest {
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(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(),
anyString(), anyString(), anyString(), any(), anyString())).thenReturn(true);
when(dispatch.pushToAdmins(any(NotificationDispatchService.AdminAudience.class), anyString(), anyString(),
anyString(), anyString(), anyString(), any())).thenReturn(1);
anyString(), anyString(), anyString(), any(), anyString())).thenReturn(1);
newScheduler().scanFailedTasks();
// 三个桶:用户7×跟价、用户7×品牌检测、用户8×货源查询
ArgumentCaptor<String> contentCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> refCaptor = ArgumentCaptor.forClass(String.class);
verify(notificationService, times(3)).pushOrRefresh(anyLong(), eq(NotificationService.AUDIENCE_USER),
eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
anyString(), contentCaptor.capture(), anyString());
anyString(), contentCaptor.capture(), anyString(), any(), refCaptor.capture());
List<String> contents = contentCaptor.getAllValues();
assertThat(contents).anySatisfy(text -> {
assertThat(text).contains("2 个跟价任务失败");
@@ -88,9 +89,57 @@ class NotificationScanSchedulerTest {
});
assertThat(contents).anySatisfy(text -> assertThat(text).contains("1 个货源查询任务失败"));
assertThat(contents).anySatisfy(text -> assertThat(text).contains("1 个品牌检测任务失败"));
assertThat(refCaptor.getAllValues()).hasSize(3).allSatisfy(json ->
assertThat(readRefs(json)).isNotEmpty());
verify(dispatch, times(3)).pushToAdmins(any(NotificationDispatchService.AdminAudience.class),
eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
anyString(), anyString(), anyString(), anyLong());
anyString(), anyString(), anyString(), anyLong(), anyString());
}
/**
* 用户口径(2026-10-21):「通知里都没体现哪个任务 id / 店铺 / 用户,咋排查」。
* 管理端 task_failed 通知的可执行判据:正文必须带 uid,ref_json 必须至少有一条非空
* taskNo(品牌任务无 task_no 列,用 #&lt;id&gt; 兜底)。只断言标题字面量的测试对此完全无感。
*/
@Test
void taskFailedAdminNotificationCarriesUidAndTaskNoAnchor() {
when(fileTaskMapper.selectList(any())).thenReturn(List.of(
fileTask(101L, "DELETE_BRAND-101", "DELETE_BRAND", 1208L, "店铺打不开")));
BrandCrawlTaskEntity brandTask = new BrandCrawlTaskEntity();
brandTask.setId(201L);
brandTask.setUserId(1208L);
brandTask.setErrorMessage("品牌检测服务不可达");
when(brandCrawlTaskMapper.selectList(any())).thenReturn(List.of(brandTask));
stubAdminAudience();
newScheduler().scanFailedTasks();
ArgumentCaptor<String> contentCaptor = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> refCaptor = ArgumentCaptor.forClass(String.class);
verify(dispatch, times(2)).pushToAdmins(any(NotificationDispatchService.AdminAudience.class),
eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
anyString(), contentCaptor.capture(), anyString(), eq(1208L), refCaptor.capture());
assertThat(contentCaptor.getAllValues()).allSatisfy(text -> assertThat(text).contains("uid=1208"));
assertThat(refCaptor.getAllValues()).allSatisfy(json -> {
List<Map<String, Object>> refs = readRefs(json);
assertThat(refs).as("task_failed 通知必须带定位锚点").isNotEmpty();
assertThat(refs.get(0).get("taskNo")).as("锚点必须能定位任务").isNotNull();
});
assertThat(refCaptor.getAllValues()).anySatisfy(json -> assertThat(readRefs(json))
.anySatisfy(ref -> assertThat(ref.get("taskNo")).isEqualTo("DELETE_BRAND-101")));
assertThat(refCaptor.getAllValues()).anySatisfy(json -> assertThat(readRefs(json))
.anySatisfy(ref -> assertThat(ref.get("taskNo")).isEqualTo("#201")));
}
private static List<Map<String, Object>> readRefs(String json) {
try {
return new com.fasterxml.jackson.databind.ObjectMapper()
.readValue(json, new com.fasterxml.jackson.core.type.TypeReference<>() {
});
} catch (Exception ex) {
throw new AssertionError("ref_json 不是合法 JSON: " + json, ex);
}
}
@Test
@@ -101,9 +150,9 @@ class NotificationScanSchedulerTest {
newScheduler().scanFailedTasks();
verify(notificationService, org.mockito.Mockito.never()).pushOrRefresh(anyLong(), anyString(), anyString(),
anyString(), anyString(), anyString(), anyString());
anyString(), anyString(), anyString(), anyString(), any(), anyString());
verify(dispatch, org.mockito.Mockito.never()).pushToAdmins(any(), anyString(), anyString(),
anyString(), anyString(), anyString(), any());
anyString(), anyString(), anyString(), any(), anyString());
}
@Test
@@ -115,7 +164,7 @@ class NotificationScanSchedulerTest {
newScheduler().scanFailedTasks();
verify(notificationService, org.mockito.Mockito.never()).pushOrRefresh(anyLong(), anyString(), anyString(),
anyString(), anyString(), anyString(), anyString());
anyString(), anyString(), anyString(), anyString(), any(), anyString());
}
/**
@@ -136,13 +185,14 @@ class NotificationScanSchedulerTest {
ArgumentCaptor<String> 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());
anyString(), anyString(), userKey.capture(),
org.mockito.ArgumentMatchers.<Long>isNull(), anyString());
assertThat(userKey.getValue()).isEqualTo("task_failed:7:PRICE_TRACK:20261001");
ArgumentCaptor<String> 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));
anyString(), anyString(), adminKey.capture(), eq(7L), anyString());
assertThat(adminKey.getValue()).isEqualTo("task_failed_admin:7:PRICE_TRACK:20261001");
}
@@ -159,7 +209,8 @@ class NotificationScanSchedulerTest {
ArgumentCaptor<String> userKey = ArgumentCaptor.forClass(String.class);
verify(notificationService, times(2)).pushOrRefresh(anyLong(), anyString(), anyString(), anyString(),
anyString(), anyString(), userKey.capture());
anyString(), anyString(), userKey.capture(),
org.mockito.ArgumentMatchers.<Long>isNull(), anyString());
assertThat(userKey.getAllValues()).containsExactlyInAnyOrder(
"task_failed:7:PRICE_TRACK:20261001", "task_failed:7:PRICE_TRACK:20261002");
}
@@ -473,10 +524,10 @@ class NotificationScanSchedulerTest {
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(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(), anyString(),
anyString(), anyString(), any(), anyString())).thenReturn(true);
when(dispatch.pushToAdmins(any(NotificationDispatchService.AdminAudience.class), anyString(), anyString(),
anyString(), anyString(), anyString(), any())).thenReturn(1);
anyString(), anyString(), anyString(), any(), anyString())).thenReturn(1);
}
private FileTaskEntity fileTask(Long id, String taskNo, String moduleType, Long userId, String errorMessage) {