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

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

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

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

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

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

已知盲区(下次补,别当已验):①桌面两级只在 happy-dom 跑过真组件,布局与层级没在真浏览器点过
(桌面日期弹层的层级修复本就在 HEAD 里,不是这批引入);②后管 e2e 夹具没有 subjectUserId=null 的行,
「存量自成一组」在后管 UI 层没被点过,只有后端 WHERE 与桌面组件各一条用例钉着。
This commit is contained in:
2026-10-13 08:34:18 +08:00
parent 1e3bcc9688
commit 5d2a1c6974
31 changed files with 1938 additions and 344 deletions
+1
View File
@@ -209,6 +209,7 @@ export const API_ENDPOINTS = {
notification: {
summary: '/api/notifications/summary',
list: '/api/notifications',
groups: '/api/notifications/groups',
read: '/api/notifications/{id}/read',
readAll: '/api/notifications/read-all',
},
@@ -57,9 +57,38 @@ export interface NotificationPage {
export interface NotificationSummary {
unreadCount: number
/** 有未读的聚合组数;徽标用它。unreadCount 仍是"条数",给明细与老客户端用。 */
unreadGroupCount?: number
latestId: number
}
/** 聚合组:一个「场景 × 自然日」折成的一行(桌面端的主体用户就是本人,故不进分组键的可见维度)。 */
export interface NotificationGroup {
latestId: number
scene: string
category: string
day: string
subjectUserId: number | null
rowCount: number
unreadCount: number
level: string
title: string
content: string
createdAt: string | null
}
export interface NotificationGroupPage {
groups: NotificationGroup[]
/** 组数(分页分母)。 */
total: number
/** 折叠前的明细条数——与 total 同屏,否则「共 12 条」会被读成只有 12 条通知。 */
rowCount: number
page: number
pageSize: number
unreadGroupCount: number
unreadCount: number
}
/** 铃铛轮询:未读数 + 最新通知 id(latestId 增大表示有新通知)。 */
export function fetchNotificationSummary() {
return unwrapJavaResponse(
@@ -79,6 +108,13 @@ export interface NotificationListParams {
category?: string
startDate?: string
endDate?: string
/** 展开聚合组:两个条件取自该组自己返回的值,原样回传(空表示不限制)。 */
scene?: string
day?: string
/** 主体用户:同场景同一天可能有好几个用户的事件,展开一组时必须把这一维也带上。 */
subjectUserId?: number | null
/** true 表示展开的是「未标注主体」那一组(改动上线前的存量行),与 subjectUserId 互斥。 */
subjectUnlabelled?: boolean
}
/**
@@ -108,6 +144,18 @@ export function buildNotificationListQuery(
if (params.endDate) {
query.endDate = params.endDate
}
if (params.scene) {
query.scene = params.scene
}
if (params.day) {
query.day = params.day
}
if (params.subjectUserId !== null && params.subjectUserId !== undefined) {
query.subjectUserId = params.subjectUserId
}
if (params.subjectUnlabelled) {
query.subjectUnlabelled = 'true'
}
return query
}
@@ -119,6 +167,15 @@ export function fetchNotificationList(params: NotificationListParams = {}) {
)
}
/** 聚合列表(铃铛默认视图)。分页按组切。 */
export function fetchNotificationGroups(params: NotificationListParams = {}) {
return unwrapJavaResponse(
get<JavaApiResponse<NotificationGroupPage>>(
buildJavaUrl(API_ENDPOINTS.notification.groups, buildNotificationListQuery(params)),
),
)
}
export function markNotificationRead(id: number) {
return unwrapJavaResponse(
post<JavaApiResponse<boolean>>(
@@ -144,7 +144,7 @@
</div>
</div>
<div v-if="loading && !items.length" class="bell-skeleton" aria-label="正在加载">
<div v-if="loading && !groups.length" class="bell-skeleton" aria-label="正在加载">
<div v-for="row in 3" :key="row" class="bell-skeleton-row">
<span class="bell-skeleton-icon"></span>
<span class="bell-skeleton-lines">
@@ -154,7 +154,7 @@
</div>
</div>
<div v-else-if="loadError && !items.length" class="bell-state">
<div v-else-if="loadError && !groups.length" class="bell-state">
<span class="bell-state-icon bell-state-icon--error" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="9" />
@@ -166,7 +166,7 @@
<button type="button" class="bell-state-action" @click="reload">重新加载</button>
</div>
<div v-else-if="!items.length" class="bell-state">
<div v-else-if="!groups.length" class="bell-state">
<span class="bell-state-icon" aria-hidden="true">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
<path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" />
@@ -178,71 +178,62 @@
</div>
<ul v-else class="bell-list">
<template v-for="group in groupedItems" :key="group.day || 'unknown'">
<li class="bell-day-head">{{ group.label }}</li>
<template v-for="(group, index) in groups" :key="notificationGroupKey(group)">
<li v-if="startsNewDay(index)" class="bell-day-head">{{ formatDayLabel(group.day) }}</li>
<li
v-for="item in group.items"
:key="item.id"
class="bell-item"
:class="[`bell-item--${itemLevel(item)}`, { 'bell-item--unread': !item.read }]"
@click="onItemClick(item)"
class="bell-item bell-group"
:class="[`bell-item--${itemLevel(group)}`, { 'bell-group--open': isExpanded(group) }]"
@click="toggleGroup(group)"
>
<span class="bell-item-icon" aria-hidden="true">
<svg
v-if="itemLevel(item) === 'error'"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
<path d="M12 9v4" />
<path d="M12 17h.01" />
</svg>
<svg
v-else-if="itemLevel(item) === 'info'"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="9" />
<path d="M12 11v5" />
<path d="M12 8h.01" />
</svg>
<svg
v-else
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="9" />
<path d="M12 8v4" />
<path d="M12 16h.01" />
</svg>
</span>
<NotificationLevelIcon :level="itemLevel(group)" />
<div class="bell-item-main">
<div class="bell-item-head">
<span class="bell-item-title" :title="item.title">{{ item.title }}</span>
<span class="bell-item-dot" :class="{ 'bell-item-dot--on': !item.read }" aria-hidden="true"></span>
<span class="bell-item-time">{{ formatTime(item.createdAt) }}</span>
<span class="bell-item-title" :title="group.title">{{ group.title }}</span>
<span
class="bell-item-dot"
:class="{ 'bell-item-dot--on': group.unreadCount > 0 }"
aria-hidden="true"
></span>
<span class="bell-item-time">{{ formatTime(group.createdAt) }}</span>
</div>
<p class="bell-item-content" :title="group.content">{{ group.content }}</p>
<div class="bell-group-foot">
<span class="bell-group-count">{{ formatGroupCounts(group.rowCount, group.unreadCount) }}</span>
<span class="bell-group-toggle">{{ isExpanded(group) ? '收起明细' : '展开明细' }}</span>
</div>
<p class="bell-item-content" :title="item.content">{{ item.content }}</p>
</div>
</li>
<!-- 已读只能进明细逐条点:聚合行上的点击只做展开,避免"看一眼顺手把没看过的全标成已读" -->
<template v-if="isExpanded(group)">
<li v-if="detailLoading" class="bell-detail-state">正在加载明细...</li>
<li v-else-if="!details.length" class="bell-detail-state">这一组里没有通知</li>
<li
v-for="item in details"
:key="item.id"
class="bell-item bell-item--detail"
:class="[`bell-item--${itemLevel(item)}`, { 'bell-item--unread': !item.read }]"
@click="onItemClick(item)"
>
<NotificationLevelIcon :level="itemLevel(item)" />
<div class="bell-item-main">
<div class="bell-item-head">
<span class="bell-item-title" :title="item.title">{{ item.title }}</span>
<span class="bell-item-dot" :class="{ 'bell-item-dot--on': !item.read }" aria-hidden="true"></span>
<span class="bell-item-time">{{ formatTime(item.createdAt) }}</span>
</div>
<p class="bell-item-content" :title="item.content">{{ item.content }}</p>
</div>
</li>
<li v-if="!detailLoading && detailTotal > details.length" class="bell-detail-state">
另有 {{ detailTotal - details.length }} 条未列出,可缩小时间范围后查看
</li>
</template>
</template>
</ul>
<footer class="bell-foot">
<div class="bell-foot-meta">
<span class="bell-foot-total">共 {{ total }} 条</span>
<span class="bell-foot-total">共 {{ total }} 组 · 明细 {{ rowCount }} 条</span>
<select
v-model="pageSize"
class="bell-size-select"
@@ -283,25 +274,32 @@ import { ElMessage } from 'element-plus'
import {
NOTIFICATION_CATEGORY_OPTIONS,
fetchNotificationGroups,
fetchNotificationList,
fetchNotificationSummary,
markAllNotificationsRead,
markNotificationRead,
type NotificationGroup,
type NotificationItem,
} from '@/shared/api/types/modules/notification.ts'
import NotificationLevelIcon from './NotificationLevelIcon.vue'
import {
NOTIFICATION_POLL_INTERVAL_MS,
currentNotificationUid,
formatDayLabel,
formatGroupCounts,
formatNotificationTime,
formatUnreadBadge,
groupNotificationsByDay,
hasNewNotification,
notificationGroupKey,
readLastNotifiedId,
writeLastNotifiedId,
} from '@/shared/utils/notification-bell.ts'
const DEFAULT_PAGE_SIZE = 10
const PAGE_SIZES = [10, 20, 50, 100]
/** 展开一组时列出的明细上限:一组可能有几百条,全塞进 DOM 会把面板撑到不可滚动。 */
const DETAIL_LIMIT = 50
/** 顶栏主题:工具页/配置页深色(dark),桌面入口首页浅色(light)。 */
const props = withDefaults(defineProps<{ theme?: 'dark' | 'light' }>(), {
@@ -315,11 +313,17 @@ const panelStyle = ref<Record<string, string>>({})
const uid = currentNotificationUid()
const unreadCount = ref(0)
const items = ref<NotificationItem[]>([])
const unreadGroupCount = ref(0)
const groups = ref<NotificationGroup[]>([])
const total = ref(0)
const rowCount = ref(0)
const page = ref(1)
/** 每页条数(面板底部下拉,取值同后台列表分页 10/20/50/100)。 */
/** 每页组数(面板底部下拉,取值同后台列表分页 10/20/50/100)。 */
const pageSize = ref(DEFAULT_PAGE_SIZE)
const expandedKey = ref('')
const details = ref<NotificationItem[]>([])
const detailTotal = ref(0)
const detailLoading = ref(false)
const panelOpen = ref(false)
const loading = ref(false)
const markingAll = ref(false)
@@ -330,11 +334,12 @@ const dateRange = ref<[string, string] | null>(null)
/** 类型大类(system_error/task_error/config_error/system_notice);空串表示不按类型筛选。 */
const category = ref('')
const badgeText = computed(() => formatUnreadBadge(unreadCount.value))
const unreadChipText = computed(() =>
unreadCount.value > 99 ? '99+ 条未读' : `${unreadCount.value} 条未读`,
)
const groupedItems = computed(() => groupNotificationsByDay(items.value))
/** 徽标按**组数**亮:同类事件一天刷几十条不该把红点做成计数器;后端没给这个字段时退回条数。 */
const badgeText = computed(() => formatUnreadBadge(unreadGroupCount.value || unreadCount.value))
const unreadChipText = computed(() => {
const count = unreadGroupCount.value
return count > 99 ? '99+ 组未读' : `${count} 组未读`
})
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
const hasFilter = computed(() =>
Boolean(keyword.value.trim() || dateRange.value || category.value),
@@ -343,8 +348,9 @@ const hasFilter = computed(() =>
let pollTimer: number | null = null
let searchTimer: number | null = null
/** 通知级别:后端只保证三类,非法值按 warning 兜底(配色与图标按级别区分)。 */
function itemLevel(item: NotificationItem): 'error' | 'warning' | 'info' {
/** 通知级别:后端只保证三类,非法值按 warning 兜底(配色与图标按级别区分)。
* 聚合行与明细行共用——两级的配色必须来自同一条规则,否则同一件事在两处颜色不一样。 */
function itemLevel(item: { level: string }): 'error' | 'warning' | 'info' {
return item.level === 'error' || item.level === 'info' ? item.level : 'warning'
}
@@ -377,6 +383,7 @@ async function refreshSummary() {
try {
const summary = await fetchNotificationSummary()
unreadCount.value = Number(summary?.unreadCount ?? 0)
unreadGroupCount.value = Number(summary?.unreadGroupCount ?? 0)
const latestId = Number(summary?.latestId ?? 0)
if (hasNewNotification(latestId, readLastNotifiedId(uid))) {
ElMessage.warning('收到新的告警通知,请点击右上角铃铛查看')
@@ -393,22 +400,26 @@ async function loadPage(targetPage: number) {
if (loading.value) return
loading.value = true
try {
const result = await fetchNotificationList({
const result = await fetchNotificationGroups({
page: targetPage,
pageSize: pageSize.value,
keyword: keyword.value,
category: category.value,
...normalizedDayRange(),
})
const list = Array.isArray(result?.items) ? result.items : []
items.value = list
const list = Array.isArray(result?.groups) ? result.groups : []
groups.value = list
total.value = Number(result?.total ?? list.length)
rowCount.value = Number(result?.rowCount ?? list.length)
unreadCount.value = Number(result?.unreadCount ?? unreadCount.value)
unreadGroupCount.value = Number(result?.unreadGroupCount ?? unreadGroupCount.value)
page.value = targetPage
loadError.value = ''
// 换页/重查后展开态必须清掉:旧组的明细与新页的组对不上,会串台
collapse()
// 无筛选时首页就是最新数据,顺带记录「已提醒过的最大 id」;有筛选时最新 id 不代表真实最新
if (targetPage <= 1 && !hasFilter.value && list.length) {
const latest = Number(list[0].id)
const latest = Number(list[0].latestId)
if (latest > 0) {
writeLastNotifiedId(uid, Math.max(readLastNotifiedId(uid), latest))
}
@@ -422,6 +433,56 @@ async function loadPage(targetPage: number) {
}
}
function isExpanded(group: NotificationGroup): boolean {
return expandedKey.value === notificationGroupKey(group)
}
/** 日期头只在"与上一组不是同一天"时出现:同一天可能有多个组(多个场景)。 */
function startsNewDay(index: number): boolean {
if (index === 0) return true
return groups.value[index - 1]?.day !== groups.value[index]?.day
}
function collapse() {
expandedKey.value = ''
details.value = []
detailTotal.value = 0
detailLoading.value = false
}
async function toggleGroup(group: NotificationGroup) {
if (isExpanded(group)) {
collapse()
return
}
collapse()
expandedKey.value = notificationGroupKey(group)
detailLoading.value = true
try {
const result = await fetchNotificationList({
page: 1,
pageSize: DETAIL_LIMIT,
scene: group.scene,
day: group.day,
subjectUserId: group.subjectUserId,
subjectUnlabelled: group.subjectUserId === null || group.subjectUserId === undefined,
})
// 请求期间用户可能已经收了另一组:晚到的结果不能盖掉当前展开的那组
if (expandedKey.value !== notificationGroupKey(group)) return
details.value = Array.isArray(result?.items) ? result.items : []
detailTotal.value = Number(result?.total ?? details.value.length)
} catch (error) {
if (expandedKey.value !== notificationGroupKey(group)) return
details.value = []
detailTotal.value = 0
loadError.value = error instanceof Error ? error.message : '明细加载失败'
} finally {
if (expandedKey.value === notificationGroupKey(group)) {
detailLoading.value = false
}
}
}
function goPage(targetPage: number) {
const safe = Math.min(Math.max(1, targetPage), totalPages.value)
if (safe === page.value || loading.value) return
@@ -503,6 +564,14 @@ async function onItemClick(item: NotificationItem) {
await markNotificationRead(item.id)
item.read = true
unreadCount.value = Math.max(0, unreadCount.value - 1)
// 组内未读清零 ⇒ 这一组不再计为未读组,红点(按组数)才会掉一格
const owner = groups.value.find((group) => notificationGroupKey(group) === expandedKey.value)
if (owner && owner.unreadCount > 0) {
owner.unreadCount -= 1
if (owner.unreadCount === 0) {
unreadGroupCount.value = Math.max(0, unreadGroupCount.value - 1)
}
}
} catch (error) {
// 改前只 console.warn:点了通知没反应、行也没转已读,用户只能反复点。
// 失败必须可见,且与 readAll 用同一个出口;不许把失败冒充成已读(那行仍是未读)。
@@ -516,10 +585,14 @@ async function readAll() {
markingAll.value = true
try {
await markAllNotificationsRead()
for (const item of items.value) {
for (const group of groups.value) {
group.unreadCount = 0
}
for (const item of details.value) {
item.read = true
}
unreadCount.value = 0
unreadGroupCount.value = 0
} catch (error) {
console.warn('[notification] 全部已读失败:', error)
ElMessage.error(error instanceof Error ? error.message : '操作失败')
@@ -983,6 +1056,54 @@ onUnmounted(() => {
background: var(--bell-unread-bg);
}
/* ---- 聚合行(一级)与明细行(二级)---- */
.bell-group--open {
background: var(--bell-hover);
}
.bell-group-foot {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-top: 5px;
}
.bell-group-count {
color: var(--bell-text-mute);
font-size: 11px;
}
.bell-group-toggle {
flex: 0 0 auto;
color: var(--bell-accent);
font-size: 11px;
font-weight: 600;
}
/* 明细缩进 + 左侧一道竖线:看得出"这是上面那一组里的东西",而不是又一批同级通知 */
.bell-item--detail {
padding-left: 30px;
}
.bell-item--detail::before {
content: '';
position: absolute;
top: 0;
bottom: 0;
left: 18px;
width: 2px;
border-radius: 2px;
background: var(--bell-border);
}
.bell-detail-state {
padding: 12px 16px;
color: var(--bell-text-mute);
font-size: 12px;
text-align: center;
}
.bell-item-icon {
display: inline-flex;
flex: 0 0 auto;
@@ -0,0 +1,61 @@
<template>
<span class="bell-item-icon" aria-hidden="true">
<svg
v-if="level === 'error'"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
<path d="M12 9v4" />
<path d="M12 17h.01" />
</svg>
<svg
v-else-if="level === 'info'"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="9" />
<path d="M12 11v5" />
<path d="M12 8h.01" />
</svg>
<svg
v-else
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="9" />
<path d="M12 8v4" />
<path d="M12 16h.01" />
</svg>
</span>
</template>
<script setup lang="ts">
/**
* 通知级别图标:聚合行与明细行都要用,抽出来免得同一组 svg 抄两遍
* (抄两遍的结局是以后只改了一处,两类行的图标开始不一致)。
*
* <p>外圈那个圆的底色/描边色由父级按级别给(.bell-item--unread.bell-item--error .bell-item-icon),
* 这里只负责形状与尺寸——父组件的 scoped 属性会落到本组件根节点上,所以那几条配色规则照旧命中。
*/
defineProps<{ level: 'error' | 'warning' | 'info' }>()
</script>
<style scoped>
.bell-item-icon svg {
width: 14px;
height: 14px;
}
</style>
@@ -96,30 +96,28 @@ export function formatDayLabel(day: string, now: Date = new Date()): string {
return `${year}年${month}月${date}日`
}
export interface NotificationDayGroup<T> {
day: string
label: string
items: T[]
/**
* 聚合组的稳定键:场景 × 自然日 × 事件主体用户,与后端 groups 出口的分组键逐字对应。
* 主体为空也要参与拼键,否则两组会撞成同一个 key,展开态串台。
*/
export function notificationGroupKey(group: {
scene?: string | null
day?: string | null
subjectUserId?: number | string | null
}): string {
const subject =
group.subjectUserId === null || group.subjectUserId === undefined ? 'none' : String(group.subjectUserId)
return `${group.scene ?? ''}|${group.day ?? ''}|${subject}`
}
/** 按年月日分组(组内保持入参顺序,列表本身已按 id 倒序)。 */
export function groupNotificationsByDay<T extends { createdAt: string | null }>(
items: T[],
now: Date = new Date(),
): NotificationDayGroup<T>[] {
const groups: NotificationDayGroup<T>[] = []
const indexByDay = new Map<string, NotificationDayGroup<T>>()
for (const item of items ?? []) {
const day = notificationDayKey(item.createdAt)
let group = indexByDay.get(day)
if (!group) {
group = { day, label: formatDayLabel(day, now), items: [] }
indexByDay.set(day, group)
groups.push(group)
}
group.items.push(item)
}
return groups
/** 组行上的计数徽语:折叠前几条、其中几条没读。只报一个数就会被读成"一共就这些通知"。 */
export function formatGroupCounts(
rowCount: number | null | undefined,
unreadCount: number | null | undefined,
): string {
const total = Number(rowCount ?? 0)
const unread = Number(unreadCount ?? 0)
return unread > 0 ? `${total} 条 · ${unread} 未读` : `${total} 条`
}
/** 通知时间展示:今天只显示 HH:mm;昨天显示「昨天 HH:mm」;更早显示 MM-DD HH:mm。 */
@@ -24,7 +24,10 @@ const BASELINE = {
// 同一批另两处(pywebview addEventListener 的外层兜底、isSessionExpiredNav 的外层兜底)挡的是
// 不可能发生的事(内层 lsGet 已自带兜底、URLSearchParams 对字符串永不抛),本轮直接摘掉,
// 所以这里只 +1 而不是 +3。静默数 silent 一格没动(仍 <=84),逐文件台账也对平。
blocks: 298,
// 299 = 298 + 桌面端铃铛 toggleGroup 的一支 try/catch(10-13 通知聚合改造):展开明细要单独发请求,
// 失败写进面板内 loadError(与列表加载同一个可见出口,不弹全局打扰),改前是"点了没反应"。
// silent 一格没涨:该支首条语句不是 console.*,且有可见出口。
blocks: 299,
// 298 = 296 + 全局错误出口 app-error.ts 的两支新 try/catch(10-09 装 app.config.errorHandler /
// window.onerror / unhandledrejection 时引入),两支都不是"吞":
// ① String(reason) 对无 toString 的对象/Symbol 会抛,兜法返回一句中文占位文本,
+1
View File
@@ -317,6 +317,7 @@ test('test_endpoints_frozen_snapshot', () => {
"notification": {
"summary": "/api/notifications/summary",
"list": "/api/notifications",
"groups": "/api/notifications/groups",
"read": "/api/notifications/{id}/read",
"readAll": "/api/notifications/read-all"
},
@@ -1,10 +1,13 @@
/**
* 用户端首批组件挂载用例(四面9分口径 §2「错误静默 …;0 挂载测试」那一半句的执行证据)。
* 用户端铃铛的组件挂载用例(四面9分口径 §2「错误静默 …;0 挂载测试」那一半句的执行证据)。
*
* 为什么是这三个靶子:本面 src 下的 vue 组件里"只 console 不给用户看"的 catch 实测 5 处,
* 其中铃铛占 3 处(未读数轮询、列表加载、点通知标已读)。轮询与列表那两处是**有意**静默
* (源码注释声明"不打扰用户",列表失败改在面板内给文案),所以这里钉的是"声明的意图真兑现";
* 标已读那一处改前是真静默——点了通知没反应、行也没转已读,用户只能反复点,本轮改成可见。
* 两组靶子:
* ① 三处失败的用户可见性——本面 src 下的 vue 组件里"只 console 不给用户看"的 catch 实测 5 处,
* 铃铛占 3 处(未读数轮询、组加载、点明细标已读)。轮询与组加载那两处是**有意**静默
* (源码注释声明"不打扰用户",组加载失败改在面板内给文案),这里钉的是"声明的意图真兑现";
* 标已读那一处改前是真静默——点了通知没反应、行也没转已读,用户只能反复点,本轮改成可见。
* ② 10-13 聚合改造(场景 × 自然日 × 用户)带出来的三条口径:点聚合行只展开不标已读、
* 红点按组数亮、组内没读完红点不许掉。这三条都只能在真组件上验,纯函数用例判不到 DOM 与状态联动。
*
* 跑真组件:真 api 桩、真 ElMessage 出口、真 DOM,判的是运行时行为,
* 不是读源码的形状钉子(那类钉子在本仓已占 25% 用例,见 §2 后管同源问题)。
@@ -12,7 +15,7 @@
* ⚠ 面板是 `<Teleport to="body">`:每支用例都必须 unmount 并清 body,
* 否则上一支留下的 `.bell-item--unread` 会被这一支的 document 查询捡到。
*
* 跑法:`npx vitest run --root frontend-vue`
* 跑法:`npx vitest run --config vitest.config.ts`(在 frontend-vue 目录下)
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
@@ -28,6 +31,7 @@ const message = vi.hoisted(() => ({
}))
const api = vi.hoisted(() => ({
fetchNotificationSummary: vi.fn(),
fetchNotificationGroups: vi.fn(),
fetchNotificationList: vi.fn(),
markNotificationRead: vi.fn(),
markAllNotificationsRead: vi.fn(),
@@ -37,6 +41,7 @@ vi.mock('element-plus', () => ({ ElMessage: message }))
vi.mock('@/shared/api/types/modules/notification.ts', () => ({
NOTIFICATION_CATEGORY_OPTIONS: [],
fetchNotificationSummary: api.fetchNotificationSummary,
fetchNotificationGroups: api.fetchNotificationGroups,
fetchNotificationList: api.fetchNotificationList,
markAllNotificationsRead: api.markAllNotificationsRead,
markNotificationRead: api.markNotificationRead,
@@ -52,6 +57,22 @@ const notification = (over: Record<string, unknown> = {}) => ({
...over,
})
/** 聚合行:一条组 = 场景 × 自然日 × 主体用户,rowCount 是折叠前的明细条数。 */
const group = (over: Record<string, unknown> = {}) => ({
latestId: 7,
scene: 'brand_check_failed',
category: 'task_error',
day: '2026-09-13',
subjectUserId: 1160,
rowCount: 1,
unreadCount: 1,
level: 'error',
title: '品牌检测服务挂了',
content: '上游 503',
createdAt: new Date().toISOString(),
...over,
})
let wrapper: VueWrapper | null = null
/** 打开面板:触发 togglePanel ⇒ 内部 void loadPage(1),靠 flushPromises 等它落地。 */
@@ -63,22 +84,44 @@ async function openPanel() {
}
/**
* 点第一条通知。⚠ 面板是 Teleport 到 body 的,`wrapper.find()` 看不见里面的节点
* (实测 wrapper 查 `.bell-item` 得到空 wrapper 而 document 里那一行确实在)
* ⇒ 一律从 document 取节点、用原生 click 触发,Vue 的 @click 监听挂在元素上,照样生效。
* 从 document 取节点、用原生 click 触发:面板是 Teleport 到 body 的,
* `wrapper.find()` 看不见里面的节点(实测 wrapper 查 `.bell-item` 得到空 wrapper
* 而 document 里那一行确实在),而 Vue 的 @click 监听挂在元素上,原生 click 照样生效。
*/
function clickFirstRow() {
const row = document.querySelector<HTMLElement>('.bell-item')
expect(row, '面板里没有可点的通知行').not.toBeNull()
function clickElement(selector: string) {
const row = document.querySelector<HTMLElement>(selector)
expect(row, `面板里没有可点的 ${selector}`).not.toBeNull()
row!.click()
}
/** 展开第一个聚合行:聚合行上的点击只做展开,明细行才是要点的那些。 */
async function expandFirstGroup() {
clickElement('.bell-group')
await flushPromises()
}
/**
* 红点取自 wrapper 而不是 document:`mount()` 不挂 attachTo,组件自身(含 .bell-trigger 与
* 它里面的 .bell-badge)渲染在游离节点上,只有 Teleport 到 body 的面板才能在 document 里查到。
*/
function badgeText(): string | null {
const badge = wrapper?.find('.bell-badge')
return badge && badge.exists() ? badge.text() : null
}
describe('NotificationBell:三处失败的用户可见性', () => {
beforeEach(() => {
document.body.innerHTML = ''
localStorage.clear()
api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 1, latestId: 7 })
api.fetchNotificationList.mockResolvedValue({ items: [notification()], total: 1, unreadCount: 1 })
api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 1, unreadGroupCount: 1, latestId: 7 })
api.fetchNotificationGroups.mockResolvedValue({
groups: [group()],
total: 1,
rowCount: 1,
unreadGroupCount: 1,
unreadCount: 1,
})
api.fetchNotificationList.mockResolvedValue({ items: [notification()], total: 1 })
api.markNotificationRead.mockResolvedValue(undefined)
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.spyOn(console, 'log').mockImplementation(() => {})
@@ -92,12 +135,13 @@ describe('NotificationBell:三处失败的用户可见性', () => {
vi.clearAllMocks()
})
it('点通知标已读失败:必须给一条带原因的错误提示,且不许把这一行冒充成已读', async () => {
it('点明细标已读失败:必须给一条带原因的错误提示,且不许把这一行冒充成已读', async () => {
api.markNotificationRead.mockRejectedValue(new Error('403 Forbidden'))
await openPanel()
expect(document.querySelectorAll('.bell-item')).toHaveLength(1)
await expandFirstGroup()
expect(document.querySelectorAll('.bell-item--detail')).toHaveLength(1)
clickFirstRow()
clickElement('.bell-item--detail')
await flushPromises()
expect(message.error).toHaveBeenCalledTimes(1)
@@ -108,12 +152,13 @@ describe('NotificationBell:三处失败的用户可见性', () => {
it('反向钉:标已读成功时不产生任何提示,而这一行要真的转为已读', async () => {
await openPanel()
await expandFirstGroup()
// 挂载那一轮 refreshSummary 发现"有新通知"本来就会弹一条 warning(既有设计,不是缺陷),
// 所以先把账清掉——本用例判的是"点成功这个动作"不许再产生提示。
message.error.mockClear()
message.warning.mockClear()
clickFirstRow()
clickElement('.bell-item--detail')
await flushPromises()
expect(message.error).not.toHaveBeenCalled()
@@ -121,8 +166,8 @@ describe('NotificationBell:三处失败的用户可见性', () => {
expect(document.querySelector('.bell-item--unread')).toBeNull()
})
it('列表加载失败:文案进面板本身,而不是弹一条全局消息打扰用户', async () => {
api.fetchNotificationList.mockRejectedValue(new Error('502 Bad Gateway'))
it('组加载失败:文案进面板本身,而不是弹一条全局消息打扰用户', async () => {
api.fetchNotificationGroups.mockRejectedValue(new Error('502 Bad Gateway'))
await openPanel()
expect(document.body.textContent).toContain('502 Bad Gateway')
@@ -130,3 +175,113 @@ describe('NotificationBell:三处失败的用户可见性', () => {
expect(document.querySelectorAll('.bell-item')).toHaveLength(0)
})
})
describe('NotificationBell:聚合两级与红点口径', () => {
beforeEach(() => {
document.body.innerHTML = ''
localStorage.clear()
api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 2, unreadGroupCount: 1, latestId: 7 })
api.fetchNotificationGroups.mockResolvedValue({
groups: [group({ latestId: 13, rowCount: 3, unreadCount: 2 })],
total: 1,
rowCount: 3,
unreadGroupCount: 1,
unreadCount: 2,
})
api.fetchNotificationList.mockResolvedValue({
items: [notification({ id: 11 }), notification({ id: 12 }), notification({ id: 13, read: true })],
total: 3,
})
api.markNotificationRead.mockResolvedValue(undefined)
vi.spyOn(console, 'warn').mockImplementation(() => {})
vi.spyOn(console, 'log').mockImplementation(() => {})
})
afterEach(() => {
wrapper?.unmount()
wrapper = null
document.body.innerHTML = ''
vi.restoreAllMocks()
vi.clearAllMocks()
})
it('点聚合行只展开:一次都不许替用户把通知标成已读', async () => {
await openPanel()
// 折叠态:面板里只有组行,一条明细都不该出现(明细要用户主动展开才拉)
expect(document.querySelectorAll('.bell-group')).toHaveLength(1)
expect(document.querySelectorAll('.bell-item--detail')).toHaveLength(0)
await expandFirstGroup()
expect(api.markNotificationRead).not.toHaveBeenCalled()
expect(api.fetchNotificationList).toHaveBeenCalledTimes(1)
// 下钻必须带上第三维(主体用户):同场景同一天里小魏11 与小魏17 是两组,
// 只按 scene+day 查会把两家的行都捞进同一份明细。
expect(api.fetchNotificationList.mock.calls[0][0]).toMatchObject({
scene: 'brand_check_failed',
day: '2026-09-13',
subjectUserId: 1160,
})
expect(api.fetchNotificationList.mock.calls[0][0].subjectUnlabelled).toBe(false)
expect(document.querySelectorAll('.bell-item--detail')).toHaveLength(3)
})
it('展开「未标注主体」那一组:按 IS NULL 查,不许把有主体的行混进来', async () => {
api.fetchNotificationGroups.mockResolvedValue({
groups: [group({ subjectUserId: null, rowCount: 2, unreadCount: 2 })],
total: 1,
rowCount: 2,
unreadGroupCount: 1,
unreadCount: 2,
})
await openPanel()
await expandFirstGroup()
const sent = api.fetchNotificationList.mock.calls[0][0]
expect(sent.subjectUnlabelled).toBe(true)
expect(sent.subjectUserId).toBeNull()
})
it('红点按组数亮、明细条数同屏:一组两条未读也不会亮成"2"', async () => {
await openPanel()
expect(badgeText()).toBe('1')
expect(document.querySelector('.bell-unread-chip')?.textContent).toContain('1 组未读')
// 组数与条数必须同时在屏上,只给一个数就会被读成"一共就这些通知"
expect(document.querySelector('.bell-foot-total')?.textContent).toContain('共 1 组')
expect(document.querySelector('.bell-foot-total')?.textContent).toContain('明细 3 条')
expect(document.querySelector('.bell-group-count')?.textContent).toBe('3 条 · 2 未读')
})
it('组内还有未读时红点不许掉,读完最后一条才掉', async () => {
await openPanel()
await expandFirstGroup()
clickElement('.bell-item--detail.bell-item--unread')
await flushPromises()
expect(api.markNotificationRead).toHaveBeenCalledTimes(1)
expect(badgeText()).toBe('1')
// 判组数必须看 chip:徽标在 unreadGroupCount 为 0 时会退回条数(兼容没给新字段的旧后端),
// 只钉徽标的话"组内没读完就把组数减掉"这条回归会被那层兜底盖住(变异自证 M2 实测存活过一次)。
expect(document.querySelector('.bell-unread-chip')?.textContent).toContain('1 组未读')
clickElement('.bell-item--detail.bell-item--unread')
await flushPromises()
expect(api.markNotificationRead).toHaveBeenCalledTimes(2)
// 这一组的两条未读都读完了:组数从 1 掉到 0,红点与"组未读"字样一起消失
expect(document.querySelector('.bell-badge')).toBeNull()
expect(document.querySelector('.bell-unread-chip')).toBeNull()
})
it('明细超出上限时说明还剩多少,不许让用户以为这就是全部', async () => {
api.fetchNotificationList.mockResolvedValue({
items: Array.from({ length: 50 }, (_, i) => notification({ id: 100 + i })),
total: 60,
})
await openPanel()
await expandFirstGroup()
expect(document.querySelectorAll('.bell-item--detail')).toHaveLength(50)
expect(document.querySelector('.bell-detail-state')?.textContent).toContain('另有 10 条未列出')
})
})
+35 -47
View File
@@ -3,7 +3,9 @@ import assert from 'node:assert/strict'
import {
formatNotificationTime,
formatUnreadBadge,
groupNotificationsByDay,
formatDayLabel,
formatGroupCounts,
notificationGroupKey,
hasNewNotification,
readLastNotifiedId,
writeLastNotifiedId,
@@ -90,52 +92,6 @@ test('formatNotificationTime 今天/昨天/更早展示', () => {
assert.equal(formatNotificationTime('not-a-date', now), '')
})
test('groupNotificationsByDay 按年月日分组:今天/昨天/更早,组内保持原顺序', () => {
const now = new Date(2026, 8, 13, 15, 30)
const items = [
{ id: 4, createdAt: new Date(2026, 8, 13, 15, 0).toISOString() },
{ id: 3, createdAt: new Date(2026, 8, 13, 9, 0).toISOString() },
{ id: 2, createdAt: new Date(2026, 8, 12, 23, 0).toISOString() },
{ id: 1, createdAt: new Date(2026, 8, 1, 8, 0).toISOString() },
]
const groups = groupNotificationsByDay(items, now)
assert.equal(groups.length, 3)
assert.deepEqual(
groups.map((group) => [group.day, group.label]),
[
['2026-09-13', '今天'],
['2026-09-12', '昨天'],
['2026-09-01', '2026年9月1日'],
],
)
assert.deepEqual(
groups[0].items.map((item) => item.id),
[4, 3],
'同一天的多条合为一组且保持倒序',
)
})
test('groupNotificationsByDay 时间缺失/非法归入未知时间组', () => {
const now = new Date(2026, 8, 13, 15, 30)
const groups = groupNotificationsByDay(
[
{ id: 2, createdAt: null },
{ id: 1, createdAt: 'not-a-date' },
],
now,
)
assert.equal(groups.length, 1)
assert.equal(groups[0].day, '')
assert.equal(groups[0].label, '未知时间')
assert.deepEqual(
groups[0].items.map((item) => item.id),
[2, 1],
)
})
test('buildNotificationListQuery:关键字去空白、空条件不下发、分类与日期原样透传', () => {
assert.deepEqual(buildNotificationListQuery(), { page: 1, pageSize: 20, onlyUnread: 'false' })
@@ -180,3 +136,35 @@ test('类型筛选项覆盖后端四个大类且标签非空', () => {
assert.ok(option.label.trim().length > 0, `分类 ${option.value} 缺中文标签`)
}
})
test('notificationGroupKey 聚合组键:三维各自都能把两组分开', () => {
const base = { scene: 'task_partial', day: '2026-09-13', subjectUserId: 1160 }
assert.notEqual(notificationGroupKey({ ...base, subjectUserId: 1196 }), notificationGroupKey(base))
assert.notEqual(notificationGroupKey({ ...base, scene: 'task_failed' }), notificationGroupKey(base))
assert.notEqual(notificationGroupKey({ ...base, day: '2026-09-12' }), notificationGroupKey(base))
assert.equal(notificationGroupKey({ ...base, subjectUserId: null }),
notificationGroupKey({ ...base, subjectUserId: undefined }))
})
test('formatGroupCounts 组行计数:读完不再挂 0 未读', () => {
assert.equal(formatGroupCounts(12, 3), '12 条 · 3 未读')
assert.equal(formatGroupCounts(12, 0), '12 条')
})
test('formatDayLabel 日期组头:今天/昨天/更早/未知时间', () => {
const now = new Date(2026, 8, 13, 15, 30)
assert.equal(formatDayLabel('2026-09-13', now), '今天')
assert.equal(formatDayLabel('2026-09-12', now), '昨天')
assert.equal(formatDayLabel('2026-09-01', now), '2026年9月1日')
assert.equal(formatDayLabel('', now), '未知时间')
})
test('buildNotificationListQuery 下钻条件:主体用户按值下发、未标注走 IS NULL 旗标', () => {
const labelled = buildNotificationListQuery({ scene: 'task_partial', day: '2026-09-13', subjectUserId: 1160, subjectUnlabelled: false })
assert.equal(labelled.subjectUserId, 1160)
assert.equal('subjectUnlabelled' in labelled, false, '有主体时不下发 IS NULL 旗标,两个条件互斥')
// 存量行没有主体用户:按 null 下发等于把条件丢掉,必须换成旗标,否则展开一组会串进别人那组
const unlabelled = buildNotificationListQuery({ scene: 'task_partial', day: '2026-09-13', subjectUserId: null, subjectUnlabelled: true })
assert.equal('subjectUserId' in unlabelled, false, 'null 主体不下发成空值参数')
assert.equal(unlabelled.subjectUnlabelled, 'true')
})