From f68d1afecf850bc793218734110a607de190096e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E9=BB=84=E8=87=AA=E8=BE=BE?= <980324341@qq.com>
Date: Tue, 13 Oct 2026 10:38:34 +0800
Subject: [PATCH] =?UTF-8?q?refactor(=E9=80=9A=E7=9F=A5):=20=E9=93=83?=
=?UTF-8?q?=E9=93=9B=E9=9D=A2=E6=9D=BF=E7=8A=B6=E6=80=81=E6=9C=BA=E4=BB=8E?=
=?UTF-8?q?=20SFC=20=E6=8B=86=E6=88=90=E7=8B=AC=E7=AB=8B=E4=B8=80=E5=B1=82?=
=?UTF-8?q?=E2=80=94=E2=80=94=E6=98=AF=E4=B8=8A=E4=B8=80=E7=AC=94=E6=8A=8A?=
=?UTF-8?q?=E4=B8=A4=E4=B8=AA=E7=BB=84=E4=BB=B6=E9=A1=B6=E5=88=B0=E5=8F=AF?=
=?UTF-8?q?=E8=AF=BB=E6=A3=98=E8=BD=AE=20800=20=E8=A1=8C=E4=B8=8A=E9=99=90?=
=?UTF-8?q?=E7=9A=84=E8=B4=A6=EF=BC=8C=E4=B8=8D=E6=98=AF=E6=96=B0=E5=8A=9F?=
=?UTF-8?q?=E8=83=BD?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
上一笔(5d2a1c69 通知聚合)推 origin 时被四面闸门连拒两次,两次都不是回归:
第一次是负载把 score_ratchet 的 py_case 挤成负数超时(单跑那格 18 秒绿,带 capture_output 复跑 24 秒 rc=0,
管道阻塞这条已排除);第二次读数清楚——后管 10 格红、客户端 48 格红,红的都是我这笔造成的:
① 可读棘轮按对象点名:后管 NotificationBell.vue 700→877 是"新增超长文件",用户端 1318→1439 是"比基线更长";
② 后管还有一把 vitest 挂载尺子(tests/mount/**,npm test 那个 glob 不递归 ⇒ 上一笔我漏跑了),
它 mock 的还是单层列表接口,两级改造后 2 条判红——这条是我上一轮汇报里说"后管全绿"的假话,先认。
拆法按尺子自己给的那条路("要么拆,要么逐条点名改基线并写清是谁的哪一笔"):放宽基线要人拍板,所以拆。
只搬 script,样式一行没动——搬模板会把 scoped 样式的后代选择器甩在父作用域外,那是会改画面的拆法。
新层是纯 TS + 一个 composable:后管 src/layout/notification-bell-panel.ts、用户端 src/shared/composables/useNotificationBellPanel.ts,
组件只留面板开合、fixed 定位、外部点击关闭、60s 轮询定时器;行数 后管 877→652、用户端 1439→1213(台账点名的基线是 1318)。
这一层是纯函数,于是判据从"源码里有没有那行字"升级成"喂数据看返回值":
新增 tests/pure/notification-bell-panel.test.ts 两支(后管 9 例 / 用户端 8 例,走 vitest——这层要解析 @ 别名与 vue,
进不了零依赖的 node --test,两面 vitest.config 的 include 因此多收一格,注释同步改掉)。
覆盖:红点按组数、组内没读完不许减组数、下钻三维(主体为空改 IS NULL 旗标)、日期倒挂交换、
聚合页缺字段时的回落、换天才挂日期头、级别兜底、水位只在首页有数据时推进。
变异自证 6 条全 KILLED(A1 组数提前掉/A2 下钻丢主体/A3 天天挂头/D1 组数提前掉/D2 丢 IS NULL 旗标/D3 日期不交换),
还原按注入前内存字节写回并比过(admin 13790 / desktop 13115)。
三处台账跟着实况走,没有一处是放宽:
① 用户端 catch 棘轮 perFile:组件 3→0、新记 useNotificationBellPanel.ts=2,silent 总数 84→83(尺子的注释要求降了就一起改小);
blocks 仍 299(搬动不改分母)。
② 后管 source-pin 台账:notification-bell-failure.test.ts 的钉子从 SFC 复指到新层,
readSource 读点数不变(中途加过一枚"组件确实在用这层"的钉子,实测会把台账读点数抬上去,
而这条已由挂载用例在运行时证 ⇒ 撤掉,不往只许减的台账里添)。
③ 后管挂载用例 4→6 例(补"点聚合行只展开不标已读""红点按组数""下钻带主体")。
验证=后管 node --test 1819/1819、vitest 21/21(12 挂载 + 9 纯函数)、真浏览器 e2e 10/10、vue-tsc rc=0;
用户端 node --test 834/834、vitest 16/16(8 挂载 + 8 纯函数)、vue-tsc rc=0;
ops 侧 test_readability_ratchet 9/9 绿(这条是上一笔红的因,现已解)。
⚠ scripts/tests 整量此刻仍 1 格红,红的不是本笔:scripts/tests/test_无声台账放宽闸.py 于 10-13 09:56 被另一路会话
扩写进 RD2 三记反例(3f55f3b),而配套 app_client/scripts/gen_silent_ledger.py 的 --check 还只判总数轴(那份 10-12 23:12 起没动)
⇒ 逐文件那一条轴此刻必然判不到,本笔不动别人的尺子也不替别人抬基线。
---
.../src/components/NotificationBell.vue | 326 +++------------
.../src/layout/notification-bell-panel.ts | 381 ++++++++++++++++++
.../notification-bell-failure.mount.test.ts | 138 ++++++-
.../tests/notification-bell-failure.test.ts | 18 +-
.../pure/notification-bell-panel.test.ts | 125 ++++++
admin-frontend-vue/vitest.config.ts | 5 +-
.../shared/components/NotificationBell.vue | 346 +++-------------
.../composables/useNotificationBellPanel.ts | 379 +++++++++++++++++
.../tests/catch-silence-ratchet.test.ts | 9 +-
.../pure/notification-bell-panel.test.ts | 115 ++++++
frontend-vue/vitest.config.ts | 5 +-
11 files changed, 1257 insertions(+), 590 deletions(-)
create mode 100644 admin-frontend-vue/src/layout/notification-bell-panel.ts
create mode 100644 admin-frontend-vue/tests/pure/notification-bell-panel.test.ts
create mode 100644 frontend-vue/src/shared/composables/useNotificationBellPanel.ts
create mode 100644 frontend-vue/tests/pure/notification-bell-panel.test.ts
diff --git a/admin-frontend-vue/src/components/NotificationBell.vue b/admin-frontend-vue/src/components/NotificationBell.vue
index b550f2c00..81ff636da 100644
--- a/admin-frontend-vue/src/components/NotificationBell.vue
+++ b/admin-frontend-vue/src/components/NotificationBell.vue
@@ -148,247 +148,71 @@
diff --git a/admin-frontend-vue/src/layout/notification-bell-panel.ts b/admin-frontend-vue/src/layout/notification-bell-panel.ts
new file mode 100644
index 000000000..626b6ac1b
--- /dev/null
+++ b/admin-frontend-vue/src/layout/notification-bell-panel.ts
@@ -0,0 +1,381 @@
+/**
+ * 铃铛面板的状态机(10-13 通知聚合改造从 NotificationBell.vue 拆出)。
+ *
+ * 为什么单独一层:聚合两级(组行 ⇄ 明细行)带来 14 个 ref 与一整条数据流,
+ * 全塞进 SFC 后组件 877 行,撞上可读棘轮 800 行上限。拆出来同时解决另一件事——
+ * 组件在本面只能用 readSource 钉形状(`npm test` 那把尺子),而这一层是真函数,
+ * 能被 node --test 直接跑:红点按组数、组内没读完不许掉、下钻三维、换页清展开态
+ * 这些判据从此判的是行为,不是源码里有没有那行字。
+ *
+ * 组件只留 DOM 相关的那一半:面板开合、fixed 定位、外部点击关闭、60s 轮询定时器。
+ */
+import { computed, onUnmounted, ref } from 'vue'
+import { ElMessage } from 'element-plus'
+
+import {
+ fetchNotificationGroups,
+ fetchNotificationList,
+ fetchNotificationSummary,
+ markAllNotificationsRead,
+ markNotificationRead,
+ type AdminNotificationGroup,
+ type AdminNotificationItem,
+} from '@/api/notifications'
+import { showAdminFeedback } from '@/components/admin-feedback-ui'
+import {
+ createSummaryFailureAlerter,
+ formatUnreadBadge,
+ hasNewNotification,
+ markReadFailureMessage,
+ notificationGroupKey,
+ readLastNotifiedId,
+ writeLastNotifiedId,
+} from '@/layout/notification-bell-model'
+
+/** 聚合行比单条高(多一行计数与展开入口),一页 6 组刚好是面板的高度量级。 */
+export const PANEL_PAGE_SIZE = 6
+/** 展开一组时列出的明细上限:一组最多可能有几百条,全塞进 DOM 会把面板撑到不可滚动。 */
+export const PANEL_DETAIL_LIMIT = 50
+
+/** 关键字输入的防抖:每敲一个字都打一次接口没必要。 */
+const KEYWORD_DEBOUNCE_MS = 300
+
+type Uid = number | string
+
+export interface NotificationPanelOptions {
+ /** 当前管理员 id:已提醒水位按人存,不能按机器存。 */
+ uid: () => Uid
+ /** 「今天」由组件供给:日期控件长在组件上,
+ * 「凡渲染日期筛选的页必须自己接默认值」那把尺子(date-filter-default-today)只走 .vue,
+ * 初值搬进这一层就等于从尺子的视野里消失。 */
+ today: () => string
+}
+
+/** 起止日期倒挂时自动交换,避免用户只看到「没有符合条件的通知」不知原因。 */
+export function normalizedDayRange(startDate: string, endDate: string): { startDate?: string; endDate?: string } {
+ let start = startDate
+ let end = endDate
+ if (start && end && start > end) {
+ const swapped = start
+ start = end
+ end = swapped
+ }
+ return { startDate: start || undefined, endDate: end || undefined }
+}
+
+/** 下钻条件:三维缺一维就会把别的主体的行混进这一组的明细(同场景同一天有好几组)。 */
+export function detailQueryFor(group: AdminNotificationGroup) {
+ return {
+ page: 1,
+ pageSize: PANEL_DETAIL_LIMIT,
+ scene: group.scene,
+ day: group.day,
+ subjectUserId: group.subjectUserId,
+ subjectUnlabelled: group.subjectUserId === null || group.subjectUserId === undefined,
+ }
+}
+
+/** 读完一条后重算两个计数:组内未读清零,红点(按组数)才掉那一格。 */
+export function applyMarkReadToCounts(
+ groups: AdminNotificationGroup[],
+ expandedKey: string,
+ unreadCount: number,
+ unreadGroupCount: number,
+): { unreadCount: number; unreadGroupCount: number } {
+ const owner = groups.find((group) => notificationGroupKey(group) === expandedKey)
+ if (owner && owner.unreadCount > 0) {
+ owner.unreadCount -= 1
+ if (owner.unreadCount === 0) {
+ return { unreadCount: Math.max(0, unreadCount - 1), unreadGroupCount: Math.max(0, unreadGroupCount - 1) }
+ }
+ }
+ return { unreadCount: Math.max(0, unreadCount - 1), unreadGroupCount }
+}
+
+/** 聚合页返回:组数与明细条数两个数都要留,只给一个就会被读成「一共就这些通知」。 */
+export function applyGroupsPage(result: Awaited>, fallback: {
+ unreadCount: number
+ unreadGroupCount: number
+}) {
+ const list = Array.isArray(result?.groups) ? result.groups : []
+ return {
+ groups: list,
+ total: Number(result?.total ?? list.length),
+ rowCount: Number(result?.rowCount ?? list.length),
+ unreadCount: Number(result?.unreadCount ?? fallback.unreadCount),
+ unreadGroupCount: Number(result?.unreadGroupCount ?? fallback.unreadGroupCount),
+ }
+}
+
+/** 无筛选的首页就是最新数据,顺带把「已提醒过的最大 id」推上去;有筛选时最新 id 不代表真实最新。 */
+export function latestIdWorthRecording(list: AdminNotificationGroup[]): number {
+ if (!list.length) return 0
+ const latest = Number(list[0].latestId)
+ return latest > 0 ? latest : 0
+}
+
+/** 日期头只在"与上一组不是同一天"时出现:同一天可能有多个组(多个用户/多个场景)。 */
+export function startsNewDay(groups: AdminNotificationGroup[], index: number): boolean {
+ if (index === 0) return true
+ return groups[index - 1]?.day !== groups[index]?.day
+}
+
+/** 级别:聚合行与明细行共用同一条规则,否则同一件事在两处颜色不一样。 */
+export function itemLevel(item: { level: string }): 'error' | 'warning' | 'info' {
+ return item.level === 'error' || item.level === 'info' ? item.level : 'warning'
+}
+
+export function useNotificationBellPanel(options: NotificationPanelOptions) {
+ const uid = options.uid
+ const today = options.today
+
+ const unreadCount = ref(0)
+ const unreadGroupCount = ref(0)
+ const groups = ref([])
+ const total = ref(0)
+ const rowCount = ref(0)
+ const page = ref(1)
+ const loading = ref(false)
+ const markingAll = ref(false)
+ const loadError = ref('')
+ const keyword = ref('')
+ const startDate = ref(today())
+ const endDate = ref(today())
+ const expandedKey = ref('')
+ const details = ref([])
+ const detailTotal = ref(0)
+ const detailLoading = ref(false)
+
+ /** 徽标按**组数**亮:同类事件一天刷几十条不该把红点做成计数器;后端没给这个字段时退回条数。 */
+ const badgeText = computed(() => formatUnreadBadge(unreadGroupCount.value || unreadCount.value))
+ const totalPages = computed(() => Math.max(1, Math.ceil(total.value / PANEL_PAGE_SIZE)))
+ /** 日期恒为「当天」是默认视图、不算主动筛选:若计入,「无筛选才记录已提醒 id」的分支会永久失效。 */
+ const hasFilter = computed(() => Boolean(keyword.value.trim()))
+ /** el-date-picker 的绑定桥:内部仍用 startDate/endDate 两个 ref,模板 v-model 走这一层。 */
+ const dateRangeValue = computed<[string, string] | null>(() =>
+ startDate.value && endDate.value ? [startDate.value, endDate.value] : null,
+ )
+
+ const summaryFailures = createSummaryFailureAlerter((message, kind) => showAdminFeedback(message, kind))
+
+ function onDateRangeChange(value: [string, string] | null) {
+ const start = value?.[0]
+ const end = value?.[1]
+ startDate.value = start ? String(start) : ''
+ endDate.value = end ? String(end) : ''
+ }
+
+ function collapse() {
+ expandedKey.value = ''
+ details.value = []
+ detailTotal.value = 0
+ detailLoading.value = false
+ }
+
+ function isExpanded(group: AdminNotificationGroup): boolean {
+ return expandedKey.value === notificationGroupKey(group)
+ }
+
+ async function refreshSummary() {
+ try {
+ const summary = await fetchNotificationSummary()
+ summaryFailures.reportSuccess()
+ 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('收到新的告警通知,请点击右上角铃铛查看')
+ writeLastNotifiedId(uid(), latestId)
+ console.log('[admin-notification] 检测到新通知 latestId=', latestId)
+ }
+ } catch (error) {
+ // 接口失败时红点不亮(与改前一致),但要让用户知道「没数」不等于「没通知」:
+ // 同一场故障只提示一次,成功一轮后重新武装(见 createSummaryFailureAlerter)。
+ console.warn('[admin-notification] 未读数刷新失败(静默降级):', error)
+ summaryFailures.reportFailure(error)
+ }
+ }
+
+ async function loadPage(targetPage: number) {
+ if (loading.value) return
+ loading.value = true
+ try {
+ const result = await fetchNotificationGroups({
+ page: targetPage,
+ pageSize: PANEL_PAGE_SIZE,
+ keyword: keyword.value,
+ ...normalizedDayRange(startDate.value, endDate.value),
+ })
+ const applied = applyGroupsPage(result, {
+ unreadCount: unreadCount.value,
+ unreadGroupCount: unreadGroupCount.value,
+ })
+ groups.value = applied.groups
+ total.value = applied.total
+ rowCount.value = applied.rowCount
+ unreadCount.value = applied.unreadCount
+ unreadGroupCount.value = applied.unreadGroupCount
+ page.value = targetPage
+ loadError.value = ''
+ // 换页/重查后展开态必须清掉:旧组的明细列表与新页的组对不上,会串台
+ collapse()
+ if (targetPage <= 1 && !hasFilter.value) {
+ const latest = latestIdWorthRecording(applied.groups)
+ if (latest > 0) {
+ writeLastNotifiedId(uid(), Math.max(readLastNotifiedId(uid()), latest))
+ }
+ }
+ } catch (error) {
+ // 列表加载失败在面板内提示,不弹全局消息打扰用户
+ console.warn('[admin-notification] 通知列表加载失败:', error)
+ loadError.value = error instanceof Error ? error.message : '通知加载失败'
+ } finally {
+ loading.value = false
+ }
+ }
+
+ async function toggleGroup(group: AdminNotificationGroup) {
+ if (isExpanded(group)) {
+ collapse()
+ return
+ }
+ collapse()
+ const key = notificationGroupKey(group)
+ expandedKey.value = key
+ detailLoading.value = true
+ try {
+ const result = await fetchNotificationList(detailQueryFor(group))
+ // 请求期间用户可能已经收起了另一组:晚到的结果不能盖掉当前展开的那组
+ if (expandedKey.value !== key) return
+ details.value = Array.isArray(result?.items) ? result.items : []
+ detailTotal.value = Number(result?.total ?? details.value.length)
+ } catch (error) {
+ if (expandedKey.value !== key) return
+ details.value = []
+ detailTotal.value = 0
+ showAdminFeedback(error instanceof Error ? error.message : '明细加载失败', 'error')
+ } finally {
+ if (expandedKey.value === key) {
+ detailLoading.value = false
+ }
+ }
+ }
+
+ function goPage(targetPage: number) {
+ const safe = Math.min(Math.max(1, targetPage), totalPages.value)
+ if (safe === page.value || loading.value) return
+ void loadPage(safe)
+ }
+
+ /** 搜索/日期变化后回到第一页重新查询。 */
+ function reload() {
+ void loadPage(1)
+ }
+
+ function resetFilters() {
+ keyword.value = ''
+ startDate.value = today()
+ endDate.value = today()
+ void loadPage(1)
+ }
+
+ async function onItemClick(item: AdminNotificationItem) {
+ if (item.read) return
+ try {
+ await markNotificationRead(item.id)
+ item.read = true
+ const next = applyMarkReadToCounts(
+ groups.value,
+ expandedKey.value,
+ unreadCount.value,
+ unreadGroupCount.value,
+ )
+ unreadCount.value = next.unreadCount
+ unreadGroupCount.value = next.unreadGroupCount
+ } catch (error) {
+ // 改前只 console.warn:点了通知没反应,用户只能反复点。失败必须可见(统一出口)。
+ console.warn('[admin-notification] 标记已读失败:', error)
+ showAdminFeedback(markReadFailureMessage(error), 'error')
+ }
+ }
+
+ async function readAll() {
+ if (markingAll.value || unreadCount.value === 0) return
+ markingAll.value = true
+ try {
+ await markAllNotificationsRead()
+ 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('[admin-notification] 全部已读失败:', error)
+ showAdminFeedback(error instanceof Error ? error.message : '操作失败', 'error')
+ } finally {
+ markingAll.value = false
+ }
+ }
+
+ let searchTimer: ReturnType | null = null
+
+ onUnmounted(dispose)
+
+ function onKeywordInput() {
+ if (searchTimer != null) {
+ clearTimeout(searchTimer)
+ }
+ searchTimer = setTimeout(() => {
+ searchTimer = null
+ void loadPage(1)
+ }, KEYWORD_DEBOUNCE_MS)
+ }
+
+ /** 防抖里那次没发出去的请求不许在面板关掉后落地:钩子挂在 composable 自己身上,
+ * "有 setTimeout 的文件必须也有卸载钩子"这条配对判据因此由构造成立,不靠调用方记得清。 */
+ function dispose() {
+ if (searchTimer != null) {
+ clearTimeout(searchTimer)
+ searchTimer = null
+ }
+ }
+
+ return {
+ unreadCount,
+ unreadGroupCount,
+ groups,
+ total,
+ rowCount,
+ page,
+ loading,
+ markingAll,
+ loadError,
+ keyword,
+ startDate,
+ endDate,
+ expandedKey,
+ details,
+ detailTotal,
+ detailLoading,
+ badgeText,
+ totalPages,
+ hasFilter,
+ dateRangeValue,
+ onDateRangeChange,
+ refreshSummary,
+ loadPage,
+ isExpanded,
+ toggleGroup,
+ goPage,
+ reload,
+ onKeywordInput,
+ resetFilters,
+ onItemClick,
+ readAll,
+ }
+}
+
+export type NotificationPanel = ReturnType
diff --git a/admin-frontend-vue/tests/mount/notification-bell-failure.mount.test.ts b/admin-frontend-vue/tests/mount/notification-bell-failure.mount.test.ts
index 4398d3ba7..ead205f24 100644
--- a/admin-frontend-vue/tests/mount/notification-bell-failure.mount.test.ts
+++ b/admin-frontend-vue/tests/mount/notification-bell-failure.mount.test.ts
@@ -1,15 +1,19 @@
/**
* 首批组件挂载用例之二(四面9分口径 §2 后管「0 组件挂载测试」)。
*
- * 靶子是 NotificationBell.vue 的两处静默 catch(未读数轮询、点通知标已读)。
+ * 靶子是 NotificationBell.vue 的两处静默 catch(未读数轮询、点明细标已读)。
* 这里跑真组件:真 pinia 会话、真 `notification-bell-model` 里的提示闸门、真定时器
* (用 vi 的假时钟推进 60s 轮询),只把两个出口(api 与 admin-feedback-ui)换成可断言的假件
* ⇒ 判的是运行时行为,不是读源码的形状钉子。
*
+ * 10-13 聚合改造(场景 × 自然日 × 主体用户)后,面板默认视图拿的是 `fetchNotificationGroups`,
+ * 明细要展开聚合行才由 `fetchNotificationList` 取 ⇒ 点已读那两支都先展开再点明细行;
+ * 顺带钉住「聚合行点击只展开、不替用户标已读」与「红点按组数、组内没读完不许掉」。
+ *
* ⚠ 面板是 ``:每支用例都必须 unmount 并清空 body,
* 否则上一支留下的那一行 `.bell-item--unread` 会被这一支的 document 查询捡到(实测会串味)。
- *
- * 跑法:`npm run test:mount`。
+ * ⚠ 这面还有一支 `npm run test:mount`(vitest,只收 tests/mount/**),
+ * 与 `npm test`(node --test,glob 不递归)互不抓取 ⇒ 改铃铛必须两把都跑,只跑一把就是没验。
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
@@ -22,6 +26,7 @@ import { NOTIFICATION_POLL_INTERVAL_MS } from '@/layout/notification-bell-model'
const feedback = vi.hoisted(() => ({ showAdminFeedback: vi.fn(), runBusy: vi.fn() }))
const api = vi.hoisted(() => ({
fetchNotificationSummary: vi.fn(),
+ fetchNotificationGroups: vi.fn(),
fetchNotificationList: vi.fn(),
markNotificationRead: vi.fn(),
markAllNotificationsRead: vi.fn(),
@@ -42,6 +47,33 @@ const notification = (over: Record = {}) => ({
...over,
})
+/** 聚合行:一条组 = 场景 × 自然日 × 主体用户,rowCount 是折叠前的明细条数。 */
+const group = (over: Record = {}) => ({
+ latestId: 7,
+ scene: 'service_down',
+ category: 'system_error',
+ day: '2026-09-13',
+ subjectUserId: 1160,
+ rowCount: 1,
+ unreadCount: 1,
+ level: 'error',
+ title: '品牌检测服务挂了',
+ content: '上游 503',
+ createdAt: new Date().toISOString(),
+ ...over,
+})
+
+const groupPage = (rows: unknown[], over: Record = {}) => ({
+ groups: rows,
+ total: rows.length,
+ rowCount: rows.length,
+ page: 1,
+ pageSize: 6,
+ unreadGroupCount: rows.filter((g) => (g as { unreadCount: number }).unreadCount > 0).length,
+ unreadCount: rows.reduce((sum, g) => sum + (g as { unreadCount: number }).unreadCount, 0),
+ ...over,
+})
+
describe('NotificationBell:两处失败必须可见', () => {
let pinia: Pinia
let wrapper: VueWrapper | null = null
@@ -52,8 +84,16 @@ describe('NotificationBell:两处失败必须可见', () => {
}
/** 只看当前这一棵树里的面板:Teleport 出去的内容挂在 document.body 上。 */
- function panelRow(): HTMLElement | null {
- return document.body.querySelector('.bell-item') as HTMLElement | null
+ function panelRow(selector: string): HTMLElement | null {
+ return document.body.querySelector(selector) as HTMLElement | null
+ }
+
+ /** 展开第一个聚合行(聚合行点击只展开,明细行才是能标已读的那一层)。 */
+ async function expandFirstGroup() {
+ const row = panelRow('.bell-group')
+ if (!row) throw new Error('面板 Teleport 到 body 后没渲染出聚合行')
+ row.click()
+ await flushPromises()
}
beforeEach(() => {
@@ -61,8 +101,9 @@ describe('NotificationBell:两处失败必须可见', () => {
pinia = createPinia()
setActivePinia(pinia)
useAdminSessionStore().user = { id: 9, username: 'root', role: 'super_admin' }
- api.fetchNotificationList.mockResolvedValue({ items: [], total: 0, page: 1, pageSize: 10, unreadCount: 0 })
- api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 0, latestId: 0 })
+ api.fetchNotificationGroups.mockResolvedValue(groupPage([]))
+ api.fetchNotificationList.mockResolvedValue({ items: [], total: 0, page: 1, pageSize: 50, unreadCount: 0 })
+ api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 0, unreadGroupCount: 0, latestId: 0 })
api.markNotificationRead.mockResolvedValue(true)
vi.spyOn(console, 'warn').mockImplementation(() => {})
})
@@ -95,7 +136,7 @@ describe('NotificationBell:两处失败必须可见', () => {
await vi.advanceTimersByTimeAsync(NOTIFICATION_POLL_INTERVAL_MS * 3)
expect(feedback.showAdminFeedback).toHaveBeenCalledTimes(1)
- api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 2, latestId: 11 })
+ api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 2, unreadGroupCount: 1, latestId: 11 })
await vi.advanceTimersByTimeAsync(NOTIFICATION_POLL_INTERVAL_MS)
api.fetchNotificationSummary.mockRejectedValue(new Error('503'))
await vi.advanceTimersByTimeAsync(NOTIFICATION_POLL_INTERVAL_MS)
@@ -105,11 +146,12 @@ describe('NotificationBell:两处失败必须可见', () => {
})
it('点通知标已读失败:提示带原因,且这条不许被前端冒充成"已读"', async () => {
+ api.fetchNotificationGroups.mockResolvedValue(groupPage([group({ latestId: 21 })]))
api.fetchNotificationList.mockResolvedValue({
items: [notification({ id: 21 })],
total: 1,
page: 1,
- pageSize: 10,
+ pageSize: 50,
unreadCount: 1,
})
api.markNotificationRead.mockRejectedValue(new Error('403 Forbidden'))
@@ -119,23 +161,28 @@ describe('NotificationBell:两处失败必须可见', () => {
await bell.find('button.bell-trigger').trigger('click')
await flushPromises()
- const row = panelRow()
- if (!row) throw new Error('面板 Teleport 到 body 后没渲染出那一行通知')
+ // 展开这一步本身不许标已读:口径是"聚合行只展开,已读进明细逐条点"
+ expect(api.markNotificationRead).not.toHaveBeenCalled()
+ await expandFirstGroup()
+
+ const row = panelRow('.bell-item--detail')
+ if (!row) throw new Error('展开聚合行后没渲染出明细行')
row.click()
await flushPromises()
expect(feedback.showAdminFeedback).toHaveBeenCalledWith('这条通知没能标记为已读:403 Forbidden', 'error')
// 前端不许替后端宣布已读:行仍是未读态、徽标还在
- expect(panelRow()?.className).toContain('bell-item--unread')
+ expect(panelRow('.bell-item--detail')?.className).toContain('bell-item--unread')
expect(bell.find('.bell-badge').exists()).toBe(true)
})
it('反向钉:标已读成功时一句提示都不许有,行也要真的转为已读', async () => {
+ api.fetchNotificationGroups.mockResolvedValue(groupPage([group({ latestId: 22 })]))
api.fetchNotificationList.mockResolvedValue({
items: [notification({ id: 22 })],
total: 1,
page: 1,
- pageSize: 10,
+ pageSize: 50,
unreadCount: 1,
})
api.markNotificationRead.mockResolvedValue(true)
@@ -144,14 +191,73 @@ describe('NotificationBell:两处失败必须可见', () => {
await flushPromises()
await bell.find('button.bell-trigger').trigger('click')
await flushPromises()
+ await expandFirstGroup()
- const row = panelRow()
- if (!row) throw new Error('面板 Teleport 到 body 后没渲染出那一行通知')
+ const row = panelRow('.bell-item--detail')
+ if (!row) throw new Error('展开聚合行后没渲染出明细行')
row.click()
await flushPromises()
expect(feedback.showAdminFeedback).not.toHaveBeenCalled()
- expect(panelRow()?.className).not.toContain('bell-item--unread')
+ expect(panelRow('.bell-item--detail')?.className).not.toContain('bell-item--unread')
expect(bell.find('.bell-badge').exists()).toBe(false)
})
+
+ it('组内还有未读时红点不许掉,读完最后一条才掉', async () => {
+ api.fetchNotificationGroups.mockResolvedValue(
+ groupPage([group({ latestId: 32, rowCount: 2, unreadCount: 2 })], { unreadCount: 2, unreadGroupCount: 1 }),
+ )
+ api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 2, unreadGroupCount: 1, latestId: 32 })
+ api.fetchNotificationList.mockResolvedValue({
+ items: [notification({ id: 31 }), notification({ id: 32 })],
+ total: 2,
+ page: 1,
+ pageSize: 50,
+ unreadCount: 2,
+ })
+
+ const bell = mountBell()
+ await flushPromises()
+ await bell.find('button.bell-trigger').trigger('click')
+ await flushPromises()
+ await expandFirstGroup()
+
+ panelRow('.bell-item--detail.bell-item--unread')!.click()
+ await flushPromises()
+ expect(api.markNotificationRead).toHaveBeenCalledTimes(1)
+ expect(bell.find('.bell-badge').exists()).toBe(true, '这一组还剩一条没读,红点不许先掉')
+
+ panelRow('.bell-item--detail.bell-item--unread')!.click()
+ await flushPromises()
+ expect(api.markNotificationRead).toHaveBeenCalledTimes(2)
+ expect(bell.find('.bell-badge').exists()).toBe(false)
+ })
+
+ it('下钻带上主体用户:同场景同一天是好几组,少一维就把别的主体的行混进来', async () => {
+ api.fetchNotificationGroups.mockResolvedValue(
+ groupPage([group({ subjectUserId: 1196, latestId: 41 }), group({ subjectUserId: 1160, latestId: 42 })]),
+ )
+ api.fetchNotificationList.mockResolvedValue({
+ items: [notification({ id: 41 })],
+ total: 1,
+ page: 1,
+ pageSize: 50,
+ unreadCount: 1,
+ })
+
+ const bell = mountBell()
+ await flushPromises()
+ await bell.find('button.bell-trigger').trigger('click')
+ await flushPromises()
+
+ expect(document.body.querySelectorAll('.bell-group')).toHaveLength(2)
+ await expandFirstGroup()
+
+ expect(api.fetchNotificationList.mock.calls[0][0]).toMatchObject({
+ scene: 'service_down',
+ day: '2026-09-13',
+ subjectUserId: 1196,
+ })
+ expect(api.fetchNotificationList.mock.calls[0][0].subjectUnlabelled).toBe(false)
+ })
})
diff --git a/admin-frontend-vue/tests/notification-bell-failure.test.ts b/admin-frontend-vue/tests/notification-bell-failure.test.ts
index 0442e3491..92a7dd23e 100644
--- a/admin-frontend-vue/tests/notification-bell-failure.test.ts
+++ b/admin-frontend-vue/tests/notification-bell-failure.test.ts
@@ -3,7 +3,8 @@
*
* 前 4 支是**行为断言**:直接 import `src/layout/notification-bell-model.ts` 跑真函数,
* 提示出口是注入进去的假 sink——不挂载组件也测得到运行时行为。
- * 第 5 支是**源码钉子**(readSource):钉的是「组件那两处 catch 接的是这条出口」这个形状,
+ * 第 5 支是**源码钉子**(readSource):钉的是「面板层那两处 catch 接的是这条出口」这个形状,
+ * (10-13 起 catch 在 notification-bell-panel.ts,同支还钉住组件确实 import 了这层。)
* 不是运行时行为;运行时那一面由 `tests/mount/notification-bell-failure.mount.test.ts`
* (`npm run test:mount`,vitest + @vue/test-utils + jsdom)覆盖。
* 两者都要:钉子跑在零依赖的 `node --test` 里,挂载例要装 node_modules。
@@ -21,6 +22,7 @@ import {
} from '../src/layout/notification-bell-model.ts'
const BELL = 'src/components/NotificationBell.vue'
+const PANEL = 'src/layout/notification-bell-panel.ts'
/** 钉子判据:两处失败路径的 console.warn 之后 160 字符窗口里必须有用户可见出口。 */
function bellFailureExits(src: string): string[] {
@@ -84,21 +86,23 @@ test('闸门不会把成功当失败:reportSuccess 之后再报错误仍是可
})
test('源码钉子(非行为断言):两处 catch 都接到 admin-feedback-ui 的统一出口', () => {
- const src = readSource(BELL)
- assert.ok(src.length > 0, '取样集非空自检:NotificationBell.vue 读到了')
+ // 10-13 两级改造后这两处 catch 长在面板模块里(SFC 顶到可读棘轮的 800 行上限,状态机整块拆出);
+ // 钉子跟着搬;「组件在用这一层」由 tests/mount 那支挂载用例在运行时证(这里再加一枚 readSource 就是往只许减的台账里添读点)。
+ const src = readSource(PANEL)
+ assert.ok(src.length > 0, '取样集非空自检:notification-bell-panel.ts 读到了')
assert.ok(src.includes(`import { showAdminFeedback } from '@/components/admin-feedback-ui'`),
'铃铛没接 admin-feedback-ui 的统一出口')
- assert.ok(src.includes('createSummaryFailureAlerter'), '轮询闸门没在组件里实例化')
+ assert.ok(src.includes('createSummaryFailureAlerter'), '轮询闸门没在面板层实例化')
assert.deepEqual(bellFailureExits(src), [], '两处静默 catch 里有一处又退回只 console 了')
})
test('判据自证(内存变异):摘掉提示出口,上面那枚钉子必须变红', () => {
- const src = readSource(BELL)
+ const src = readSource(PANEL)
assert.deepEqual(bellFailureExits(src), [], '基线就该是干净的,否则这条自证测不出任何东西')
const variants: Array<[string, string]> = [
- ['摘掉轮询提示', " summaryFailures.reportFailure(error)\n"],
- ['摘掉标记已读提示', " showAdminFeedback(markReadFailureMessage(error), 'error')\n"],
+ ['摘掉轮询提示', " summaryFailures.reportFailure(error)\n"],
+ ['摘掉标记已读提示', " showAdminFeedback(markReadFailureMessage(error), 'error')\n"],
]
for (const [label, dropped] of variants) {
assert.equal(src.split(dropped).length - 1, 1, `「${label}」的锚串在源码里不唯一,变异不作数`)
diff --git a/admin-frontend-vue/tests/pure/notification-bell-panel.test.ts b/admin-frontend-vue/tests/pure/notification-bell-panel.test.ts
new file mode 100644
index 000000000..88b7a2f38
--- /dev/null
+++ b/admin-frontend-vue/tests/pure/notification-bell-panel.test.ts
@@ -0,0 +1,125 @@
+/**
+ * 面板层纯函数的行为用例(10-13 从 NotificationBell.vue 拆出这一层的唯一目的就在这)。
+ *
+ * 组件那一层在本面只能挂载跑(vitest+jsdom),而"红点按组数、组内没读完不许掉、
+ * 下钻三维、换页清展开态"这几条口径其实都是纯计算——放这一层就能逐条喂数据判它,
+ * 不必退化成 readSource 钉源码字形(那种钉子在这仓已被记进只许减的台账)。
+ *
+ * 跑法:`npx vitest run --config vitest.config.ts`(`npm test` 那把 node --test 零依赖,
+ * 解析不了 @ 别名与 vue,所以这一支走 vitest 的 tests/pure/**)。
+ */
+import { describe, expect, it } from 'vitest'
+
+import {
+ PANEL_DETAIL_LIMIT,
+ applyGroupsPage,
+ applyMarkReadToCounts,
+ detailQueryFor,
+ itemLevel,
+ latestIdWorthRecording,
+ normalizedDayRange,
+ startsNewDay,
+} from '@/layout/notification-bell-panel'
+
+const group = (over: Record = {}) => ({
+ latestId: 7,
+ scene: 'service_down',
+ category: 'system_error',
+ day: '2026-09-13',
+ subjectUserId: 1160,
+ rowCount: 1,
+ unreadCount: 1,
+ level: 'error',
+ title: '品牌检测服务挂了',
+ content: '上游 503',
+ createdAt: '2026-09-13T09:00:00.000Z',
+ ...over,
+})
+
+describe('通知面板层纯函数', () => {
+ it('起止日期倒挂自动交换;单边留空不下发该条件', () => {
+ expect(normalizedDayRange('2026-09-14', '2026-09-13')).toEqual({
+ startDate: '2026-09-13',
+ endDate: '2026-09-14',
+ })
+ expect(normalizedDayRange('', '')).toEqual({ startDate: undefined, endDate: undefined })
+ expect(normalizedDayRange('2026-09-13', '')).toEqual({ startDate: '2026-09-13', endDate: undefined })
+ })
+
+ it('下钻条件带满三维,主体为空改走 IS NULL 旗标', () => {
+ const labelled = detailQueryFor(group({ subjectUserId: 1196 }) as never)
+ expect(labelled.scene).toBe('service_down')
+ expect(labelled.day).toBe('2026-09-13')
+ expect(labelled.subjectUserId).toBe(1196)
+ expect(labelled.subjectUnlabelled).toBe(false)
+ expect(labelled.pageSize).toBe(PANEL_DETAIL_LIMIT)
+
+ // 改动上线前的存量行没有主体用户:按 null 下发等于把条件丢掉,必须换成旗标
+ const unlabelled = detailQueryFor(group({ subjectUserId: null }) as never)
+ expect(unlabelled.subjectUserId).toBeNull()
+ expect(unlabelled.subjectUnlabelled).toBe(true)
+ })
+
+ it('组内还有未读时组数不许减,读完最后一条才减', () => {
+ const groups = [group({ unreadCount: 2 }), group({ subjectUserId: 1196, unreadCount: 1 })]
+ const key = 'service_down|2026-09-13|1160'
+
+ const first = applyMarkReadToCounts(groups, key, 3, 2)
+ expect(groups[0].unreadCount).toBe(1, '第一条读完,组内还剩一条')
+ expect(first.unreadCount).toBe(2, '明细条数照实减')
+ expect(first.unreadGroupCount).toBe(2, '这一组还没读完,未读组数不许动')
+
+ const last = applyMarkReadToCounts(groups, key, 2, 2)
+ expect(groups[0].unreadCount).toBe(0)
+ expect(last.unreadGroupCount).toBe(1, '组内清零,红点(按组数)才掉这一格')
+ })
+
+ it('没展开任何一组时只减明细数,不减组数', () => {
+ const groups = [group({ unreadCount: 1 })]
+ const next = applyMarkReadToCounts(groups, '', 1, 1)
+ expect(groups[0].unreadCount).toBe(1, '找不到归属组就不该改组内计数')
+ expect(next.unreadCount).toBe(0)
+ expect(next.unreadGroupCount).toBe(1)
+ })
+
+ it('两个计数不许越界成负数', () => {
+ const next = applyMarkReadToCounts([], 'nothing-expanded', 0, 0)
+ expect(next).toEqual({ unreadCount: 0, unreadGroupCount: 0 })
+ })
+
+ it('聚合页缺字段时回落:组数按实收、明细条数按清单长度', () => {
+ const applied = applyGroupsPage(
+ { groups: [group(), group({ subjectUserId: 1196 })] } as never,
+ { unreadCount: 5, unreadGroupCount: 3 },
+ )
+ expect(applied.total).toBe(2)
+ expect(applied.rowCount).toBe(2)
+ expect(applied.unreadCount).toBe(5, '后端没给这一格就保留上一次读数,别凭空归零')
+ expect(applied.unreadGroupCount).toBe(3)
+
+ const empty = applyGroupsPage({ groups: null } as never, { unreadCount: 1, unreadGroupCount: 1 })
+ expect(empty.groups).toEqual([])
+ expect(empty.total).toBe(0)
+ })
+
+ it('日期头只在换天时出现:同一天多组(多用户/多场景)不重复挂头', () => {
+ const list = [group(), group({ subjectUserId: 1196 }), group({ day: '2026-09-12' })]
+ expect(startsNewDay(list, 0)).toBe(true)
+ expect(startsNewDay(list, 1)).toBe(false)
+ expect(startsNewDay(list, 2)).toBe(true)
+ })
+
+ it('级别兜底:非法/缺失都按 warning,组行与明细行不会配色分家', () => {
+ expect(itemLevel({ level: 'error' })).toBe('error')
+ expect(itemLevel({ level: 'info' })).toBe('info')
+ expect(itemLevel({ level: 'fatal' })).toBe('warning')
+ expect(itemLevel({ level: '' })).toBe('warning')
+ })
+
+ it('已提醒水位只在首页真有数据时推进,取不到 id 就什么也不写', () => {
+ expect(latestIdWorthRecording([])).toBe(0)
+ expect(latestIdWorthRecording([group({ latestId: 0 })])).toBe(0)
+ expect(latestIdWorthRecording([group({ latestId: 'x' })])).toBe(0)
+ expect(latestIdWorthRecording([group({ latestId: 88 })])).toBe(88)
+ })
+})
diff --git a/admin-frontend-vue/vitest.config.ts b/admin-frontend-vue/vitest.config.ts
index c0673410f..b2642bff6 100644
--- a/admin-frontend-vue/vitest.config.ts
+++ b/admin-frontend-vue/vitest.config.ts
@@ -8,7 +8,8 @@ import vue from '@vitejs/plugin-vue'
* 与 vite.config.ts 分家:那份管生产构建,这里只服务 `npm run test:mount`,
* 动它不会改变 `npm run build` 的产物(也不在 tsconfig 的 include 里,vue-tsc 不检它)。
*
- * include 只收 `tests/mount/**`:本仓其余判据走 `node --test tests/*.test.ts`,
+ * include 收 `tests/mount/**`(组件挂载)与 `tests/pure/**`(面板层纯函数:那层要解析 @ 别名
+ * 与 vue/element-plus,进不了零依赖的 `node --test`):本仓其余判据走 `node --test tests/*.test.ts`,
* 那支 glob 不递归 ⇒ 两套 runner 不会互相抓到对方的文件。
*/
export default defineConfig({
@@ -20,6 +21,6 @@ export default defineConfig({
},
test: {
environment: 'jsdom',
- include: ['tests/mount/**/*.test.ts'],
+ include: ['tests/mount/**/*.test.ts', 'tests/pure/**/*.test.ts'],
},
})
diff --git a/frontend-vue/src/shared/components/NotificationBell.vue b/frontend-vue/src/shared/components/NotificationBell.vue
index 20dc57642..5d090d618 100644
--- a/frontend-vue/src/shared/components/NotificationBell.vue
+++ b/frontend-vue/src/shared/components/NotificationBell.vue
@@ -270,19 +270,14 @@
diff --git a/frontend-vue/src/shared/composables/useNotificationBellPanel.ts b/frontend-vue/src/shared/composables/useNotificationBellPanel.ts
new file mode 100644
index 000000000..12115cbda
--- /dev/null
+++ b/frontend-vue/src/shared/composables/useNotificationBellPanel.ts
@@ -0,0 +1,379 @@
+/**
+ * 铃铛面板的状态机(10-13 通知聚合改造从 NotificationBell.vue 拆出,与后管同一形状各一份)。
+ *
+ * 为什么单独一层:聚合两级(组行 ⇄ 明细行)带来十几个 ref 与一整条数据流,留在 SFC 里
+ * 组件 1439 行,比可读棘轮台账里已点名的基线(1318 行)还长。拆出来同时解决另一件事——
+ * 组件在这一面只能用 readSource 钉形状,而这一层是真函数,能被 `node --test` 直接跑:
+ * 红点按组数、组内没读完不许掉、下钻三维、换页清展开态,判的从此是行为不是源码字形。
+ *
+ * 组件只留 DOM 相关的那一半:面板开合、fixed 定位与窄窗回让、外部点击关闭、60s 轮询定时器。
+ */
+import { computed, onUnmounted, ref } from 'vue'
+import { ElMessage } from 'element-plus'
+
+import {
+ fetchNotificationGroups,
+ fetchNotificationList,
+ fetchNotificationSummary,
+ markAllNotificationsRead,
+ markNotificationRead,
+ type NotificationGroup,
+ type NotificationItem,
+ type NotificationListParams,
+} from '@/shared/api/types/modules/notification'
+import {
+ hasNewNotification,
+ notificationGroupKey,
+ readLastNotifiedId,
+ writeLastNotifiedId,
+} from '@/shared/utils/notification-bell'
+
+/** 聚合行比单条高(多一行计数与展开入口),默认一页 10 组。 */
+export const PANEL_PAGE_SIZE = 10
+export const PANEL_PAGE_SIZES = [10, 20, 50, 100]
+/** 展开一组时列出的明细上限:一组可能有几百条,全塞进 DOM 会把面板撑到不可滚动。 */
+export const PANEL_DETAIL_LIMIT = 50
+/** 关键字输入的防抖。 */
+const KEYWORD_DEBOUNCE_MS = 300
+
+/** 起止日期倒挂时自动交换,避免用户只看到「没有符合条件的通知」不知原因。 */
+export function normalizedDayRange(range: [string, string] | null): { startDate?: string; endDate?: string } {
+ if (!range) {
+ return {}
+ }
+ let [start, end] = range
+ if (start && end && start > end) {
+ const swapped = start
+ start = end
+ end = swapped
+ }
+ return { startDate: start || undefined, endDate: end || undefined }
+}
+
+/** 下钻条件:三维缺一维就会把别的主体的行混进这一组的明细(同场景同一天有好几组)。 */
+export function detailQueryFor(group: NotificationGroup): NotificationListParams {
+ return {
+ page: 1,
+ pageSize: PANEL_DETAIL_LIMIT,
+ scene: group.scene,
+ day: group.day,
+ subjectUserId: group.subjectUserId,
+ subjectUnlabelled: group.subjectUserId === null || group.subjectUserId === undefined,
+ }
+}
+
+/** 读完一条后重算两个计数:组内未读清零,红点(按组数)才掉那一格。 */
+export function applyMarkReadToCounts(
+ groups: NotificationGroup[],
+ expandedKey: string,
+ unreadCount: number,
+ unreadGroupCount: number,
+): { unreadCount: number; unreadGroupCount: number } {
+ const nextUnread = Math.max(0, unreadCount - 1)
+ const owner = groups.find((group) => notificationGroupKey(group) === expandedKey)
+ if (owner && owner.unreadCount > 0) {
+ owner.unreadCount -= 1
+ if (owner.unreadCount === 0) {
+ return { unreadCount: nextUnread, unreadGroupCount: Math.max(0, unreadGroupCount - 1) }
+ }
+ }
+ return { unreadCount: nextUnread, unreadGroupCount }
+}
+
+/** 聚合页返回:组数与明细条数两个数都要留,只给一个就会被读成「一共就这些通知」。 */
+export function applyGroupsPage(
+ result: Awaited>,
+ fallback: { unreadCount: number; unreadGroupCount: number },
+) {
+ const list = Array.isArray(result?.groups) ? result.groups : []
+ return {
+ groups: list,
+ total: Number(result?.total ?? list.length),
+ rowCount: Number(result?.rowCount ?? list.length),
+ unreadCount: Number(result?.unreadCount ?? fallback.unreadCount),
+ unreadGroupCount: Number(result?.unreadGroupCount ?? fallback.unreadGroupCount),
+ }
+}
+
+/** 日期头只在"与上一组不是同一天"时出现:同一天可能有多个组(多个用户/多个场景)。 */
+export function startsNewDay(groups: NotificationGroup[], index: number): boolean {
+ if (index === 0) return true
+ return groups[index - 1]?.day !== groups[index]?.day
+}
+
+/** 通知级别:聚合行与明细行共用同一条规则,否则同一件事在两处颜色不一样。 */
+export function itemLevel(item: { level: string }): 'error' | 'warning' | 'info' {
+ return item.level === 'error' || item.level === 'info' ? item.level : 'warning'
+}
+
+export function useNotificationBellPanel(options: { uid: () => string }) {
+ const uid = options.uid
+
+ const unreadCount = ref(0)
+ const unreadGroupCount = ref(0)
+ const groups = ref([])
+ const total = ref(0)
+ const rowCount = ref(0)
+ const page = ref(1)
+ const pageSize = ref(PANEL_PAGE_SIZE)
+ const loading = ref(false)
+ const markingAll = ref(false)
+ const loadError = ref('')
+ const keyword = ref('')
+ const dateRange = ref<[string, string] | null>(null)
+ const category = ref('')
+ const expandedKey = ref('')
+ const details = ref([])
+ const detailTotal = ref(0)
+ const detailLoading = ref(false)
+
+ /** 徽标按**组数**亮:同类事件一天刷几十条不该把红点做成计数器;后端没给这个字段时退回条数。 */
+ const badgeCount = computed(() => unreadGroupCount.value || unreadCount.value)
+ const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
+ const hasFilter = computed(() =>
+ Boolean(keyword.value.trim() || dateRange.value || category.value),
+ )
+
+ /** 日期区间变化(选择完成/清空都会触发):只保留「两端齐全」的区间。 */
+ function onDateRangeChange(value: unknown) {
+ if (Array.isArray(value) && value.length === 2 && value[0] && value[1]) {
+ dateRange.value = [String(value[0]), String(value[1])]
+ return
+ }
+ dateRange.value = null
+ }
+
+ function collapse() {
+ expandedKey.value = ''
+ details.value = []
+ detailTotal.value = 0
+ detailLoading.value = false
+ }
+
+ function isExpanded(group: NotificationGroup): boolean {
+ return expandedKey.value === notificationGroupKey(group)
+ }
+
+ 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('收到新的告警通知,请点击右上角铃铛查看')
+ writeLastNotifiedId(uid(), latestId)
+ console.log('[notification] 检测到新通知 latestId=', latestId)
+ }
+ } catch (error) {
+ // 通知接口失败静默降级:不显示红点、不打扰用户
+ console.warn('[notification] 未读数刷新失败(静默降级):', error)
+ }
+ }
+
+ async function loadPage(targetPage: number) {
+ if (loading.value) return
+ loading.value = true
+ try {
+ const result = await fetchNotificationGroups({
+ page: targetPage,
+ pageSize: pageSize.value,
+ keyword: keyword.value,
+ category: category.value,
+ ...normalizedDayRange(dateRange.value),
+ })
+ const applied = applyGroupsPage(result, {
+ unreadCount: unreadCount.value,
+ unreadGroupCount: unreadGroupCount.value,
+ })
+ groups.value = applied.groups
+ total.value = applied.total
+ rowCount.value = applied.rowCount
+ unreadCount.value = applied.unreadCount
+ unreadGroupCount.value = applied.unreadGroupCount
+ page.value = targetPage
+ loadError.value = ''
+ // 换页/重查后展开态必须清掉:旧组的明细与新页的组对不上,会串台
+ collapse()
+ // 无筛选时首页就是最新数据,顺带记录「已提醒过的最大 id」;有筛选时最新 id 不代表真实最新
+ if (targetPage <= 1 && !hasFilter.value && applied.groups.length) {
+ const latest = Number(applied.groups[0].latestId)
+ if (latest > 0) {
+ writeLastNotifiedId(uid(), Math.max(readLastNotifiedId(uid()), latest))
+ }
+ }
+ } catch (error) {
+ // 列表加载失败在面板内提示,不弹全局消息打扰用户
+ console.warn('[notification] 通知列表加载失败:', error)
+ loadError.value = error instanceof Error ? error.message : '通知加载失败'
+ } finally {
+ loading.value = false
+ }
+ }
+
+ async function toggleGroup(group: NotificationGroup) {
+ if (isExpanded(group)) {
+ collapse()
+ return
+ }
+ collapse()
+ const key = notificationGroupKey(group)
+ expandedKey.value = key
+ detailLoading.value = true
+ try {
+ const result = await fetchNotificationList(detailQueryFor(group))
+ // 请求期间用户可能已经收了另一组:晚到的结果不能盖掉当前展开的那组
+ if (expandedKey.value !== key) return
+ details.value = Array.isArray(result?.items) ? result.items : []
+ detailTotal.value = Number(result?.total ?? details.value.length)
+ } catch (error) {
+ if (expandedKey.value !== key) return
+ details.value = []
+ detailTotal.value = 0
+ loadError.value = error instanceof Error ? error.message : '明细加载失败'
+ } finally {
+ if (expandedKey.value === key) {
+ detailLoading.value = false
+ }
+ }
+ }
+
+ function goPage(targetPage: number) {
+ const safe = Math.min(Math.max(1, targetPage), totalPages.value)
+ if (safe === page.value || loading.value) return
+ void loadPage(safe)
+ }
+
+ /** 搜索/日期/类型变化后回到第一页重新查询。 */
+ function reload() {
+ void loadPage(1)
+ }
+
+ /** 切换每页组数:回到第一页重新查询。 */
+ function onPageSizeChange() {
+ console.log('[notification] 每页条数切换为', pageSize.value)
+ void loadPage(1)
+ }
+
+ /** 类型筛选:重复点同一个不重复请求;切换后回到第一页。 */
+ function selectCategory(value: string) {
+ if (category.value === value) {
+ return
+ }
+ category.value = value
+ console.log('[notification] 类型筛选切换为', value || '全部')
+ void loadPage(1)
+ }
+
+ function clearKeyword() {
+ keyword.value = ''
+ void loadPage(1)
+ }
+
+ function resetFilters() {
+ keyword.value = ''
+ dateRange.value = null
+ category.value = ''
+ void loadPage(1)
+ }
+
+ async function onItemClick(item: NotificationItem) {
+ if (item.read) return
+ try {
+ await markNotificationRead(item.id)
+ item.read = true
+ const next = applyMarkReadToCounts(
+ groups.value,
+ expandedKey.value,
+ unreadCount.value,
+ unreadGroupCount.value,
+ )
+ unreadCount.value = next.unreadCount
+ unreadGroupCount.value = next.unreadGroupCount
+ } catch (error) {
+ // 改前只 console.warn:点了通知没反应、行也没转已读,用户只能反复点。
+ // 失败必须可见,且与 readAll 用同一个出口;不许把失败冒充成已读(那行仍是未读)。
+ console.warn('[notification] 标记已读失败:', error)
+ ElMessage.error('这条通知没能标记为已读:' + (error instanceof Error ? error.message : String(error)))
+ }
+ }
+
+ async function readAll() {
+ if (markingAll.value || unreadCount.value === 0) return
+ markingAll.value = true
+ try {
+ await markAllNotificationsRead()
+ 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 : '操作失败')
+ } finally {
+ markingAll.value = false
+ }
+ }
+
+ let searchTimer: ReturnType | null = null
+
+ /** 关键字输入防抖,避免每敲一个字都打一次接口。 */
+ function onKeywordInput() {
+ if (searchTimer != null) {
+ clearTimeout(searchTimer)
+ }
+ searchTimer = setTimeout(() => {
+ searchTimer = null
+ void loadPage(1)
+ }, KEYWORD_DEBOUNCE_MS)
+ }
+
+ /** 防抖里那次没发出去的请求不许在面板关掉后落地:钩子挂在这一层,配对由构造成立。 */
+ function dispose() {
+ if (searchTimer != null) {
+ clearTimeout(searchTimer)
+ searchTimer = null
+ }
+ }
+
+ onUnmounted(dispose)
+
+ return {
+ badgeCount,
+ category,
+ clearKeyword,
+ dateRange,
+ detailLoading,
+ detailTotal,
+ details,
+ goPage,
+ groups,
+ hasFilter,
+ isExpanded,
+ keyword,
+ loadError,
+ loading,
+ markingAll,
+ onDateRangeChange,
+ onItemClick,
+ onKeywordInput,
+ onPageSizeChange,
+ page,
+ pageSize,
+ readAll,
+ refreshSummary,
+ reload,
+ resetFilters,
+ rowCount,
+ selectCategory,
+ toggleGroup,
+ total,
+ totalPages,
+ unreadCount,
+ unreadGroupCount,
+ }
+}
diff --git a/frontend-vue/tests/catch-silence-ratchet.test.ts b/frontend-vue/tests/catch-silence-ratchet.test.ts
index ae7ed729f..8841fe935 100644
--- a/frontend-vue/tests/catch-silence-ratchet.test.ts
+++ b/frontend-vue/tests/catch-silence-ratchet.test.ts
@@ -35,7 +35,11 @@ const BASELINE = {
// ② guardRun 挡的是"处理器自己崩了把页面带白屏",兜法是 console.error + 一次中文提示,
// 且刻意不向上重抛(重抛会让 Vue 再进一次同一个处理器)。
// silent 一格没涨(两支都有用户可见出口),台账无需新增条目。
- silent: 84,
+ // 83 = 10-13 面板状态机拆进 useNotificationBellPanel.ts 后的实扫值(原 84)。
+ // 拆分是为了 SFC 顶到可读棘轮的 800 行上限(1439 行 > 台账点名的 1318),不是冲静默来的:
+ // 铃铛那两处"有意静默降级"(轮询失败不亮红点、列表失败在面板内给文案)整块搬进了新文件,
+ // 逐文件台账跟着实况走——组件 3→0、新记 useNotificationBellPanel.ts=2,总数还比基线少 1。
+ silent: 83,
/** 逐文件台账:只钉总数与文件数两个标量的棘轮,会被「A 加一条 + B 减一条」整段绕过。 */
perFile: {
'src/pages/brand/components/BrandCollectDataTab.vue': 4,
@@ -64,8 +68,9 @@ const BASELINE = {
'src/shared/bridges/web-fallback.ts': 2,
'src/shared/components/ApiSecretSettingsPanel.vue': 1,
'src/shared/components/ExpiryNotice.vue': 2,
- 'src/shared/components/NotificationBell.vue': 3,
+ 'src/shared/components/NotificationBell.vue': 0,
'src/shared/composables/useLiveTaskBoard.ts': 1,
+ 'src/shared/composables/useNotificationBellPanel.ts': 2,
'src/shared/composables/useTaskProgressLoop.ts': 3,
'src/shared/composables/useVersionUpdate.ts': 1,
'src/shared/dispatch-guard-ui.ts': 1,
diff --git a/frontend-vue/tests/pure/notification-bell-panel.test.ts b/frontend-vue/tests/pure/notification-bell-panel.test.ts
new file mode 100644
index 000000000..ae5af8ccb
--- /dev/null
+++ b/frontend-vue/tests/pure/notification-bell-panel.test.ts
@@ -0,0 +1,115 @@
+/**
+ * 面板层纯函数的行为用例(10-13 从 NotificationBell.vue 拆出这一层的唯一目的就在这)。
+ *
+ * 与后管同一形状各一份(两端是两个 app,没有共享包):这里判的是聚合两级的口径本身——
+ * 红点按组数、组内没读完不许掉、下钻三维、日期倒挂交换、换天挂组头。
+ * 组件那一面由 tests/mount 的挂载用例跑真 DOM,两边不重复。
+ *
+ * 跑法:`npx vitest run --config vitest.config.ts`(`npm test` 那把 node --test 零依赖,
+ * 解析不了 @ 别名与 vue,所以这一支走 vitest 的 tests/pure/**)。
+ */
+import { describe, expect, it } from 'vitest'
+
+import {
+ PANEL_DETAIL_LIMIT,
+ PANEL_PAGE_SIZES,
+ PANEL_PAGE_SIZE,
+ applyGroupsPage,
+ applyMarkReadToCounts,
+ detailQueryFor,
+ itemLevel,
+ normalizedDayRange,
+ startsNewDay,
+} from '@/shared/composables/useNotificationBellPanel'
+
+const group = (over: Record = {}) => ({
+ latestId: 7,
+ scene: 'task_partial',
+ category: 'task_error',
+ day: '2026-09-13',
+ subjectUserId: 1160,
+ rowCount: 1,
+ unreadCount: 1,
+ level: 'error',
+ title: '用户采集数据任务部分结果缺失',
+ content: '缺 6 行',
+ createdAt: '2026-09-13T09:00:00.000Z',
+ ...over,
+})
+
+describe('用户端通知面板层纯函数', () => {
+ it('分页档位与默认每页组数:面板高度按量级设计,别把组数默认成明细数', () => {
+ expect(PANEL_PAGE_SIZE).toBe(10)
+ expect(PANEL_PAGE_SIZES).toEqual([10, 20, 50, 100])
+ })
+
+ it('未选日期时不下发日期条件;倒挂自动交换', () => {
+ expect(normalizedDayRange(null)).toEqual({})
+ expect(normalizedDayRange(['2026-09-14', '2026-09-13'])).toEqual({
+ startDate: '2026-09-13',
+ endDate: '2026-09-14',
+ })
+ })
+
+ it('下钻条件带满三维,主体为空改走 IS NULL 旗标', () => {
+ const labelled = detailQueryFor(group({ subjectUserId: 1196 }) as never)
+ expect(labelled.scene).toBe('task_partial')
+ expect(labelled.day).toBe('2026-09-13')
+ expect(labelled.subjectUserId).toBe(1196)
+ expect(labelled.subjectUnlabelled).toBe(false)
+ expect(labelled.pageSize).toBe(PANEL_DETAIL_LIMIT)
+
+ const unlabelled = detailQueryFor(group({ subjectUserId: null }) as never)
+ expect(unlabelled.subjectUserId).toBeNull()
+ expect(unlabelled.subjectUnlabelled).toBe(true)
+ })
+
+ it('组内还有未读时组数不许减,读完最后一条才减', () => {
+ const groups = [group({ unreadCount: 2 })]
+ const key = 'task_partial|2026-09-13|1160'
+
+ const first = applyMarkReadToCounts(groups, key, 2, 1)
+ expect(groups[0].unreadCount).toBe(1)
+ expect(first.unreadCount).toBe(1)
+ expect(first.unreadGroupCount).toBe(1, '这一组还剩一条没读,红点不许先掉')
+
+ const last = applyMarkReadToCounts(groups, key, 1, 1)
+ expect(groups[0].unreadCount).toBe(0)
+ expect(last.unreadGroupCount).toBe(0)
+ })
+
+ it('没展开任何一组时只减明细数;两个计数都不许越界成负数', () => {
+ const groups = [group({ unreadCount: 1 })]
+ expect(applyMarkReadToCounts(groups, '', 1, 1)).toEqual({ unreadCount: 0, unreadGroupCount: 1 })
+ expect(applyMarkReadToCounts([], '', 0, 0)).toEqual({ unreadCount: 0, unreadGroupCount: 0 })
+ })
+
+ it('聚合页缺字段时回落:组数按实收、明细条数按清单长度', () => {
+ const applied = applyGroupsPage(
+ { groups: [group(), group({ subjectUserId: 1196, day: '2026-09-12' })] } as never,
+ { unreadCount: 4, unreadGroupCount: 2 },
+ )
+ expect(applied.total).toBe(2)
+ expect(applied.rowCount).toBe(2)
+ expect(applied.unreadCount).toBe(4)
+ expect(applied.unreadGroupCount).toBe(2)
+
+ const empty = applyGroupsPage({ groups: null } as never, { unreadCount: 1, unreadGroupCount: 1 })
+ expect(empty.groups).toEqual([])
+ expect(empty.total).toBe(0)
+ })
+
+ it('日期头只在换天时出现:同一天多组(多用户/多场景)不重复挂头', () => {
+ const list = [group(), group({ subjectUserId: 1196 }), group({ scene: 'task_failed' })]
+ expect(startsNewDay(list, 0)).toBe(true)
+ expect(startsNewDay(list, 1)).toBe(false)
+ expect(startsNewDay(list, 2)).toBe(false, '同一天不同场景仍是两组,但不重复挂日期头')
+ })
+
+ it('级别兜底:非法/缺失都按 warning,组行与明细行配色不分家', () => {
+ expect(itemLevel({ level: 'error' })).toBe('error')
+ expect(itemLevel({ level: 'info' })).toBe('info')
+ expect(itemLevel({ level: 'warn' })).toBe('warning')
+ expect(itemLevel({ level: '' })).toBe('warning')
+ })
+})
diff --git a/frontend-vue/vitest.config.ts b/frontend-vue/vitest.config.ts
index 9158f364d..15e927300 100644
--- a/frontend-vue/vitest.config.ts
+++ b/frontend-vue/vitest.config.ts
@@ -7,7 +7,8 @@ import vue from '@vitejs/plugin-vue'
*
* 与 vite.config.ts 分家:那份管生产构建,这里只服务挂载用例,
* 动它不改变 `npm run build` 的产物,也不在 tsconfig include 里(vue-tsc 不检它)。
- * include 只收 `tests/mount/**`——本仓其余判据走 `node --test tests/*.test.ts`,
+ * include 收 `tests/mount/**`(组件挂载)与 `tests/pure/**`(面板层纯函数:那层要解析 @ 别名
+ * 与 vue/element-plus,进不了零依赖的 `node --test`)——本仓其余判据走 `node --test tests/*.test.ts`,
* 那支 glob 不递归,两套 runner 抓不到对方的文件(后管同款分法,已验证互不串)。
*/
export default defineConfig({
@@ -21,6 +22,6 @@ export default defineConfig({
// 本面装的是 happy-dom(后管那份用 jsdom):环境名写错时 vitest 直接 MISSING DEPENDENCY,
// 一支用例都跑不起来还报 "no tests"——所以这条与 devDependencies 必须同处对账。
environment: 'happy-dom',
- include: ['tests/mount/**/*.test.ts'],
+ include: ['tests/mount/**/*.test.ts', 'tests/pure/**/*.test.ts'],
},
})