refactor(通知): 铃铛面板状态机从 SFC 拆成独立一层——是上一笔把两个组件顶到可读棘轮 800 行上限的账,不是新功能

上一笔(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 起没动)
⇒ 逐文件那一条轴此刻必然判不到,本笔不动别人的尺子也不替别人抬基线。
This commit is contained in:
2026-10-13 10:38:34 +08:00
parent 5d2a1c6974
commit f68d1afecf
11 changed files with 1257 additions and 590 deletions
@@ -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<ReturnType<typeof fetchNotificationGroups>>,
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<NotificationGroup[]>([])
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<NotificationItem[]>([])
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<typeof setTimeout> | 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,
}
}