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:
@@ -148,247 +148,71 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { onMounted, onUnmounted, ref } from 'vue'
|
||||
|
||||
import {
|
||||
fetchNotificationGroups,
|
||||
fetchNotificationList,
|
||||
fetchNotificationSummary,
|
||||
markAllNotificationsRead,
|
||||
markNotificationRead,
|
||||
type AdminNotificationGroup,
|
||||
type AdminNotificationItem,
|
||||
} from '@/api/notifications'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import {
|
||||
NOTIFICATION_POLL_INTERVAL_MS,
|
||||
createSummaryFailureAlerter,
|
||||
formatDayLabel,
|
||||
formatGroupCounts,
|
||||
formatNotificationTime,
|
||||
formatUnreadBadge,
|
||||
hasNewNotification,
|
||||
markReadFailureMessage,
|
||||
notificationGroupKey,
|
||||
readLastNotifiedId,
|
||||
writeLastNotifiedId,
|
||||
} from '@/layout/notification-bell-model'
|
||||
import { todayDateInput } from '@/utils/datetime'
|
||||
|
||||
/** 聚合行比单条高(多一行计数与展开入口),一页 6 组刚好是面板的高度量级。 */
|
||||
const PAGE_SIZE = 6
|
||||
/** 展开一组时列出的明细上限:一组最多可能有几百条,全塞进 DOM 会把面板撑到不可滚动。 */
|
||||
const DETAIL_LIMIT = 50
|
||||
import {
|
||||
itemLevel,
|
||||
startsNewDay as groupStartsNewDay,
|
||||
useNotificationBellPanel,
|
||||
} from '@/layout/notification-bell-panel'
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
|
||||
/**
|
||||
* 面板的数据流(聚合组、明细、两个计数、防抖与取数)整块在 notification-bell-panel.ts。
|
||||
* 那一层是真函数,`npm test` 能直接跑判据;组件只留 DOM 相关的一半:
|
||||
* 面板开合、fixed 定位、外部点击关闭、60s 轮询定时器。
|
||||
*/
|
||||
const {
|
||||
badgeText,
|
||||
dateRangeValue,
|
||||
detailLoading,
|
||||
detailTotal,
|
||||
details,
|
||||
goPage,
|
||||
groups,
|
||||
hasFilter,
|
||||
isExpanded,
|
||||
keyword,
|
||||
loadError,
|
||||
loading,
|
||||
markingAll,
|
||||
onItemClick,
|
||||
onDateRangeChange,
|
||||
onKeywordInput,
|
||||
page,
|
||||
readAll,
|
||||
refreshSummary,
|
||||
reload,
|
||||
resetFilters,
|
||||
rowCount,
|
||||
toggleGroup,
|
||||
total,
|
||||
totalPages,
|
||||
unreadCount,
|
||||
} = useNotificationBellPanel({ uid: () => session.user?.id ?? 0, today: () => todayDateInput() })
|
||||
|
||||
const rootRef = ref<HTMLElement | null>(null)
|
||||
const panelRef = ref<HTMLElement | null>(null)
|
||||
const panelStyle = ref<Record<string, string>>({})
|
||||
|
||||
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 panelOpen = ref(false)
|
||||
const loading = ref(false)
|
||||
const markingAll = ref(false)
|
||||
const loadError = ref('')
|
||||
const keyword = ref('')
|
||||
const startDate = ref(todayDateInput())
|
||||
const endDate = ref(todayDateInput())
|
||||
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 / PAGE_SIZE)))
|
||||
/** 日期恒为「当天」是默认视图、不算主动筛选:若计入,下方「无筛选才记录已提醒 id」的分支会永久失效。 */
|
||||
const hasFilter = computed(() => Boolean(keyword.value.trim()))
|
||||
|
||||
/**
|
||||
* el-date-picker 的绑定桥:日期区间在内部仍用 startDate/endDate 两个 ref 表示
|
||||
* (hasFilter/normalizedDayRange/resetFilters 都基于它们)。
|
||||
* 此前模板写的是 v-model="dateRange",而 dateRange 从未声明 → vue-tsc 直接报 TS2339 构建失败,
|
||||
* 且日期筛选完全不下发参数。
|
||||
*/
|
||||
const dateRangeValue = computed<[string, string] | null>(() =>
|
||||
startDate.value && endDate.value ? [startDate.value, endDate.value] : null
|
||||
)
|
||||
|
||||
function onDateRangeChange(value: [string, string] | null) {
|
||||
const start = value?.[0]
|
||||
const end = value?.[1]
|
||||
startDate.value = start ? String(start) : ''
|
||||
endDate.value = end ? String(end) : ''
|
||||
}
|
||||
|
||||
let pollTimer: number | null = null
|
||||
let searchTimer: number | null = null
|
||||
|
||||
function currentUid(): number | string {
|
||||
return session.user?.id ?? 0
|
||||
}
|
||||
|
||||
/** 起止日期倒挂时自动交换,避免用户只看到「没有符合条件的通知」不知原因。 */
|
||||
function normalizedDayRange(): { startDate?: string; endDate?: string } {
|
||||
let start = startDate.value
|
||||
let end = endDate.value
|
||||
if (start && end && start > end) {
|
||||
const swapped = start
|
||||
start = end
|
||||
end = swapped
|
||||
}
|
||||
return { startDate: start || undefined, endDate: end || undefined }
|
||||
}
|
||||
|
||||
/**
|
||||
* 未读数轮询失败的可见提示闸门(同场故障只提示一次,轮询 60s 一轮)。
|
||||
* 出口只走 admin-feedback-ui 的 showAdminFeedback,不在组件里另起一层提示。
|
||||
*/
|
||||
const summaryFailures = createSummaryFailureAlerter((message, kind) => showAdminFeedback(message, kind))
|
||||
|
||||
/** 拉未读数:发现新通知提醒一次(localStorage 记录已提醒过的最大 id,避免重复弹)。 */
|
||||
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(currentUid()))) {
|
||||
ElMessage.warning('收到新的告警通知,请点击右上角铃铛查看')
|
||||
writeLastNotifiedId(currentUid(), 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: PAGE_SIZE,
|
||||
keyword: keyword.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(currentUid(), Math.max(readLastNotifiedId(currentUid()), latest))
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// 列表加载失败在面板内提示,不弹全局消息打扰用户
|
||||
console.warn('[admin-notification] 通知列表加载失败:', error)
|
||||
loadError.value = error instanceof Error ? error.message : '通知加载失败'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function isExpanded(group: AdminNotificationGroup): 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: AdminNotificationGroup) {
|
||||
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
|
||||
showAdminFeedback(error instanceof Error ? error.message : '明细加载失败', 'error')
|
||||
} 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 reload() {
|
||||
void loadPage(1)
|
||||
}
|
||||
|
||||
/** 关键字输入防抖 300ms,避免每敲一个字都打一次接口。 */
|
||||
function onKeywordInput() {
|
||||
if (searchTimer != null) {
|
||||
window.clearTimeout(searchTimer)
|
||||
}
|
||||
searchTimer = window.setTimeout(() => {
|
||||
searchTimer = null
|
||||
void loadPage(1)
|
||||
}, 300)
|
||||
}
|
||||
|
||||
function resetFilters() {
|
||||
keyword.value = ''
|
||||
startDate.value = todayDateInput()
|
||||
endDate.value = todayDateInput()
|
||||
void loadPage(1)
|
||||
function formatTime(value: string | null) {
|
||||
return formatNotificationTime(value)
|
||||
}
|
||||
|
||||
/** 面板挂到 body 后用 fixed 定位,位置按触发器实时算(右对齐在铃铛下方)。 */
|
||||
@@ -406,56 +230,10 @@ function togglePanel() {
|
||||
panelOpen.value = !panelOpen.value
|
||||
if (panelOpen.value) {
|
||||
syncPanelPosition()
|
||||
void loadPage(1)
|
||||
reload()
|
||||
}
|
||||
}
|
||||
|
||||
async function onItemClick(item: AdminNotificationItem) {
|
||||
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:点了通知没反应,用户只能反复点。失败必须可见(统一出口)。
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
function formatTime(value: string | null) {
|
||||
return formatNotificationTime(value)
|
||||
}
|
||||
|
||||
/** 点击组件外部关闭面板(面板已 Teleport 到 body,需连同面板自身一起判断)。 */
|
||||
function onDocumentMouseDown(event: MouseEvent) {
|
||||
if (!panelOpen.value) return
|
||||
@@ -475,20 +253,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)
|
||||
})
|
||||
|
||||
@@ -500,10 +280,6 @@ onUnmounted(() => {
|
||||
window.clearInterval(pollTimer)
|
||||
pollTimer = null
|
||||
}
|
||||
if (searchTimer != null) {
|
||||
window.clearTimeout(searchTimer)
|
||||
searchTimer = null
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
@@ -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<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'
|
||||
}
|
||||
|
||||
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 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,
|
||||
...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<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,
|
||||
dateRangeValue,
|
||||
onDateRangeChange,
|
||||
refreshSummary,
|
||||
loadPage,
|
||||
isExpanded,
|
||||
toggleGroup,
|
||||
goPage,
|
||||
reload,
|
||||
onKeywordInput,
|
||||
resetFilters,
|
||||
onItemClick,
|
||||
readAll,
|
||||
}
|
||||
}
|
||||
|
||||
export type NotificationPanel = ReturnType<typeof useNotificationBellPanel>
|
||||
Reference in New Issue
Block a user