86d78160fd
通知表新增 severity(紧急/高危/中危/低危,V161),由 scene + level 推导且 不回改 level:老客户端配色不受影响,secret_balance 的余量偏低与欠费也能分档。 列表与聚合接口默认按严重度倒序(同档按时间倒序),sort=time 切纯时间排序; 聚合组取组内最高严重度。两端铃铛加彩色等级标签与排序切换,展开明细沿用 同一排序,严重度排序下隐藏会跨天误导的日期头。
421 lines
15 KiB
TypeScript
421 lines
15 KiB
TypeScript
/**
|
||
* 铃铛面板的状态机(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 {
|
||
ADMIN_NOTIFICATION_SEVERITY_LABELS,
|
||
fetchNotificationGroups,
|
||
fetchNotificationList,
|
||
fetchNotificationSummary,
|
||
markAllNotificationsRead,
|
||
markNotificationRead,
|
||
type AdminNotificationGroup,
|
||
type AdminNotificationItem,
|
||
type AdminNotificationSeverity,
|
||
type AdminNotificationSortMode,
|
||
} 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,
|
||
sort: AdminNotificationSortMode = 'severity',
|
||
) {
|
||
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: 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<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),
|
||
}
|
||
}
|
||
|
||
/** 无筛选的首页就是最新数据,顺带把「已提醒过的最大 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'
|
||
}
|
||
|
||
/** 严重度兜底:新后端直接给 severity;旧后端没这列时按 level 推,绝不让标签空白。 */
|
||
export function itemSeverity(item: {
|
||
severity?: string | null
|
||
level?: string | null
|
||
}): AdminNotificationSeverity {
|
||
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 ADMIN_NOTIFICATION_SEVERITY_LABELS[itemSeverity(item)]
|
||
}
|
||
|
||
export function useNotificationBellPanel(options: NotificationPanelOptions) {
|
||
const uid = options.uid
|
||
const today = options.today
|
||
|
||
const unreadCount = ref(0)
|
||
const unreadGroupCount = ref(0)
|
||
const groups = ref<AdminNotificationGroup[]>([])
|
||
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 sortMode = ref<AdminNotificationSortMode>('severity')
|
||
const expandedKey = ref('')
|
||
const details = ref<AdminNotificationItem[]>([])
|
||
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,
|
||
sort: sortMode.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, 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
|
||
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)
|
||
}
|
||
|
||
/** 排序切换:同一档不重复请求;切换后回到第一页并收起明细。 */
|
||
function setSortMode(value: AdminNotificationSortMode) {
|
||
if (sortMode.value === value) {
|
||
return
|
||
}
|
||
sortMode.value = value
|
||
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<typeof setTimeout> | 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,
|
||
sortMode,
|
||
setSortMode,
|
||
dateRangeValue,
|
||
onDateRangeChange,
|
||
refreshSummary,
|
||
loadPage,
|
||
isExpanded,
|
||
toggleGroup,
|
||
goPage,
|
||
reload,
|
||
onKeywordInput,
|
||
resetFilters,
|
||
onItemClick,
|
||
readAll,
|
||
}
|
||
}
|
||
|
||
export type NotificationPanel = ReturnType<typeof useNotificationBellPanel>
|