/** * 铃铛面板的状态机(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 { NOTIFICATION_SEVERITY_LABELS, fetchNotificationGroups, fetchNotificationList, fetchNotificationSummary, markAllNotificationsRead, markNotificationRead, type NotificationGroup, type NotificationItem, type NotificationListParams, type NotificationSeverity, type NotificationSortMode, } 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, sort: NotificationSortMode = 'severity', ): NotificationListParams { return { page: 1, pageSize: PANEL_DETAIL_LIMIT, sort, 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' } /** 严重度兜底:新后端直接给 severity;旧后端没这列时按 level 推,绝不让标签空白。 */ export function itemSeverity(item: { severity?: string | null; level?: string | null }): NotificationSeverity { const value = item.severity if (value === 'urgent' || value === 'high' || value === 'medium' || value === 'low') { return value } if (item.level === 'error') return 'urgent' if (item.level === 'info') return 'low' return 'high' } /** 中文标签:紧急/高危/中危/低危。 */ export function severityLabel(item: { severity?: string | null; level?: string | null }): string { return NOTIFICATION_SEVERITY_LABELS[itemSeverity(item)] } 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 sortMode = ref('severity') 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, sort: sortMode.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, sortMode.value)) // 请求期间用户可能已经收了另一组:晚到的结果不能盖掉当前展开的那组 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 setSortMode(value: NotificationSortMode) { if (sortMode.value === value) { return } sortMode.value = value console.log('[notification] 排序切换为', value === 'time' ? '按时间' : '按严重度') 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, setSortMode, sortMode, toggleGroup, total, totalPages, unreadCount, unreadGroupCount, } }