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:
@@ -270,19 +270,14 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
import { NOTIFICATION_CATEGORY_OPTIONS } from '@/shared/api/types/modules/notification'
|
||||
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'
|
||||
PANEL_PAGE_SIZES as PAGE_SIZES,
|
||||
itemLevel,
|
||||
startsNewDay as groupStartsNewDay,
|
||||
useNotificationBellPanel,
|
||||
} from '@/shared/composables/useNotificationBellPanel'
|
||||
import {
|
||||
NOTIFICATION_POLL_INTERVAL_MS,
|
||||
currentNotificationUid,
|
||||
@@ -290,16 +285,8 @@ import {
|
||||
formatGroupCounts,
|
||||
formatNotificationTime,
|
||||
formatUnreadBadge,
|
||||
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
|
||||
} from '@/shared/utils/notification-bell'
|
||||
|
||||
/** 顶栏主题:工具页/配置页深色(dark),桌面入口首页浅色(light)。 */
|
||||
const props = withDefaults(defineProps<{ theme?: 'dark' | 'light' }>(), {
|
||||
@@ -307,230 +294,66 @@ const props = withDefaults(defineProps<{ theme?: 'dark' | 'light' }>(), {
|
||||
})
|
||||
const theme = computed(() => props.theme)
|
||||
|
||||
const uid = currentNotificationUid()
|
||||
|
||||
/**
|
||||
* 面板的数据流(聚合组、明细、两个计数、筛选与防抖)整块在 useNotificationBellPanel.ts。
|
||||
* 那一层是真函数,`npm test` 能直接跑判据;组件只留 DOM 相关的一半:
|
||||
* 面板开合、fixed 定位与窄窗回让、外部点击关闭、60s 轮询定时器。
|
||||
*/
|
||||
const {
|
||||
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,
|
||||
} = useNotificationBellPanel({ uid: () => uid })
|
||||
|
||||
const rootRef = ref<HTMLElement | null>(null)
|
||||
const panelRef = ref<HTMLElement | null>(null)
|
||||
const panelStyle = ref<Record<string, string>>({})
|
||||
const uid = currentNotificationUid()
|
||||
|
||||
const unreadCount = ref(0)
|
||||
const unreadGroupCount = ref(0)
|
||||
const groups = ref<NotificationGroup[]>([])
|
||||
const total = ref(0)
|
||||
const rowCount = ref(0)
|
||||
const page = ref(1)
|
||||
/** 每页组数(面板底部下拉,取值同后台列表分页 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)
|
||||
const loadError = ref('')
|
||||
const keyword = ref('')
|
||||
/** 日期区间(el-date-picker daterange,YYYY-MM-DD 字符串;未选为 null)。 */
|
||||
const dateRange = ref<[string, string] | null>(null)
|
||||
/** 类型大类(system_error/task_error/config_error/system_notice);空串表示不按类型筛选。 */
|
||||
const category = ref('')
|
||||
|
||||
/** 徽标按**组数**亮:同类事件一天刷几十条不该把红点做成计数器;后端没给这个字段时退回条数。 */
|
||||
const badgeText = computed(() => formatUnreadBadge(unreadGroupCount.value || unreadCount.value))
|
||||
const badgeText = computed(() => formatUnreadBadge(badgeCount.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),
|
||||
)
|
||||
|
||||
let pollTimer: number | null = null
|
||||
let searchTimer: number | null = null
|
||||
|
||||
/** 通知级别:后端只保证三类,非法值按 warning 兜底(配色与图标按级别区分)。
|
||||
* 聚合行与明细行共用——两级的配色必须来自同一条规则,否则同一件事在两处颜色不一样。 */
|
||||
function itemLevel(item: { level: string }): 'error' | 'warning' | 'info' {
|
||||
return item.level === 'error' || item.level === 'info' ? item.level : 'warning'
|
||||
}
|
||||
|
||||
/** 起止日期倒挂时自动交换,避免用户只看到「没有符合条件的通知」不知原因。 */
|
||||
function normalizedDayRange(): { startDate?: string; endDate?: string } {
|
||||
const range = dateRange.value
|
||||
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 }
|
||||
}
|
||||
|
||||
/** 日期区间变化(选择完成/清空都会触发):只保留「两端齐全」的区间。 */
|
||||
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
|
||||
}
|
||||
|
||||
/** 拉未读数:发现新通知提醒一次(localStorage 记录已提醒过的最大 id,避免重复弹)。 */
|
||||
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(),
|
||||
})
|
||||
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].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
|
||||
}
|
||||
}
|
||||
|
||||
function isExpanded(group: NotificationGroup): boolean {
|
||||
return expandedKey.value === notificationGroupKey(group)
|
||||
}
|
||||
|
||||
/** 日期头只在"与上一组不是同一天"时出现:同一天可能有多个组(多个场景)。 */
|
||||
/** 模板里仍是 startsNewDay(index):组序列在面板层,这里只补一次取值。 */
|
||||
function startsNewDay(index: number): boolean {
|
||||
if (index === 0) return true
|
||||
return groups.value[index - 1]?.day !== groups.value[index]?.day
|
||||
return groupStartsNewDay(groups.value, index)
|
||||
}
|
||||
|
||||
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
|
||||
void loadPage(safe)
|
||||
}
|
||||
|
||||
/** 切换每页条数:回到第一页重新查询。 */
|
||||
function onPageSizeChange() {
|
||||
console.log('[notification] 每页条数切换为', pageSize.value)
|
||||
void loadPage(1)
|
||||
}
|
||||
|
||||
/** 搜索/日期变化后回到第一页重新查询。 */
|
||||
function reload() {
|
||||
void loadPage(1)
|
||||
}
|
||||
|
||||
/** 关键字输入防抖 300ms,避免每敲一个字都打一次接口。 */
|
||||
function onKeywordInput() {
|
||||
if (searchTimer != null) {
|
||||
window.clearTimeout(searchTimer)
|
||||
}
|
||||
searchTimer = window.setTimeout(() => {
|
||||
searchTimer = null
|
||||
void loadPage(1)
|
||||
}, 300)
|
||||
}
|
||||
|
||||
function clearKeyword() {
|
||||
keyword.value = ''
|
||||
void loadPage(1)
|
||||
}
|
||||
|
||||
/** 类型筛选:重复点同一个不重复请求;切换后回到第一页。 */
|
||||
function selectCategory(value: string) {
|
||||
if (category.value === value) {
|
||||
return
|
||||
}
|
||||
category.value = value
|
||||
console.log('[notification] 类型筛选切换为', value || '全部')
|
||||
void loadPage(1)
|
||||
}
|
||||
|
||||
function resetFilters() {
|
||||
keyword.value = ''
|
||||
dateRange.value = null
|
||||
category.value = ''
|
||||
void loadPage(1)
|
||||
function formatTime(value: string | null) {
|
||||
return formatNotificationTime(value)
|
||||
}
|
||||
|
||||
/** 面板挂到 body 后用 fixed 定位,位置按触发器实时算(右对齐在铃铛下方)。 */
|
||||
@@ -554,57 +377,10 @@ function togglePanel() {
|
||||
panelOpen.value = !panelOpen.value
|
||||
if (panelOpen.value) {
|
||||
syncPanelPosition()
|
||||
void loadPage(1)
|
||||
reload()
|
||||
}
|
||||
}
|
||||
|
||||
async function onItemClick(item: NotificationItem) {
|
||||
if (item.read) return
|
||||
try {
|
||||
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 用同一个出口;不许把失败冒充成已读(那行仍是未读)。
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
function formatTime(value: string | null) {
|
||||
return formatNotificationTime(value)
|
||||
}
|
||||
|
||||
/** 点击组件外部关闭面板(面板已 Teleport 到 body,需连同面板自身一起判断)。 */
|
||||
function onDocumentMouseDown(event: MouseEvent) {
|
||||
if (!panelOpen.value) return
|
||||
@@ -626,20 +402,22 @@ function onWindowResize() {
|
||||
/** 页面回到前台时立即刷新一次未读数。 */
|
||||
function onVisibilityChange() {
|
||||
if (typeof document !== 'undefined' && document.visibilityState === 'visible') {
|
||||
void refreshSummary()
|
||||
refreshSummary()
|
||||
}
|
||||
}
|
||||
|
||||
let pollTimer: number | null = null
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('mousedown', onDocumentMouseDown)
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
window.addEventListener('resize', onWindowResize)
|
||||
void refreshSummary()
|
||||
refreshSummary()
|
||||
pollTimer = window.setInterval(() => {
|
||||
if (typeof document !== 'undefined' && document.visibilityState !== 'visible') {
|
||||
return
|
||||
}
|
||||
void refreshSummary()
|
||||
refreshSummary()
|
||||
}, NOTIFICATION_POLL_INTERVAL_MS)
|
||||
})
|
||||
|
||||
@@ -651,10 +429,6 @@ onUnmounted(() => {
|
||||
window.clearInterval(pollTimer)
|
||||
pollTimer = null
|
||||
}
|
||||
if (searchTimer != null) {
|
||||
window.clearTimeout(searchTimer)
|
||||
searchTimer = null
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user