Compare commits
3 Commits
eb0824aeba
...
713cef4be1
| Author | SHA1 | Date | |
|---|---|---|---|
| 713cef4be1 | |||
| eacc3ed4c4 | |||
| 1a486617b5 |
@@ -1,38 +1,78 @@
|
||||
import { expect, test, type Page } from '@playwright/test'
|
||||
|
||||
// 站内通知铃铛面板验收:关键字/年月日区间搜索、按天分组、分页。
|
||||
// 依赖 scripts/mock-admin-server.mjs 的通知夹具(14 条:09-13 六条、09-12 四条、09-10 四条)。
|
||||
// 站内通知铃铛面板验收:聚合视图(场景 × 自然日 × 事件主体用户)、展开明细、
|
||||
// 关键字/年月日区间搜索、按组分页、红点按组数。
|
||||
// 依赖 scripts/mock-admin-server.mjs 的通知夹具:14 行折成 10 组、2 组未读、3 行未读。
|
||||
// 夹具的 id 与 createdAt 同为插入时单调(与真库一致),场景显式写在夹具里而不是从 id 推。
|
||||
|
||||
// 夹具会被"标记已读"改写,而 mock 服务在 reuseExistingServer 下跨轮存活 ⇒ 每条用例前重置,
|
||||
// 否则第二遍跑会带着上一遍的已读态,绝对计数断言全漂。
|
||||
test.beforeEach(async ({ request }) => {
|
||||
await request.post('/api/admin/notifications/__reset')
|
||||
})
|
||||
|
||||
async function clearDateFilter(page: Page) {
|
||||
const picker = page.locator('.bell-panel .bell-date-picker')
|
||||
await picker.hover()
|
||||
await picker.locator('.el-range__close-icon').click()
|
||||
await expect(page.locator('.bell-page-total')).toHaveText('共 10 组 · 明细 14 条')
|
||||
}
|
||||
|
||||
async function openBell(page: Page) {
|
||||
await page.goto('/admin-vue/')
|
||||
await expect(page.locator('.admin-topbar h1')).toHaveText('用户管理')
|
||||
await page.locator('.admin-notification-bell .bell-trigger').click()
|
||||
await expect(page.locator('.bell-panel')).toBeVisible()
|
||||
await expect(page.locator('.bell-item').first()).toBeVisible()
|
||||
// 面板默认按「当天」过滤,夹具是 09-10~09-13:先清空日期才能拿到全量
|
||||
await clearDateFilter(page)
|
||||
await expect(page.locator('.bell-group').first()).toBeVisible()
|
||||
}
|
||||
|
||||
test('test_notification_panel_day_group_and_pagination', async ({ page }) => {
|
||||
/**
|
||||
* 打开日历并等入场动画落定。
|
||||
*
|
||||
* 两件事必须先做对,否则读数全是假的:
|
||||
* ① 弹层节点是常驻的(Element 用 v-show),未打开时它也在 DOM 里、rect 全 0,
|
||||
* 所以 `toBeAttached()` 不能当「已打开」的判据;
|
||||
* ② 打开瞬间 el-zoom-in-top 把弹层 scaleY 压到 0,格子坐标整体贴到面板顶部,
|
||||
* 此时做命中测试会把「动画中」读成「被面板遮挡」。
|
||||
*/
|
||||
async function openCalendar(page: Page) {
|
||||
await page.locator('.bell-panel .bell-date-picker').click()
|
||||
const popper = page.locator('.bell-date-popper')
|
||||
await expect(popper).toBeVisible()
|
||||
await page.waitForFunction(() => {
|
||||
const pop = document.querySelector('.bell-date-popper')
|
||||
if (!pop) return false
|
||||
const style = getComputedStyle(pop)
|
||||
return style.transform === 'none' && style.opacity === '1' && pop.getBoundingClientRect().height > 0
|
||||
})
|
||||
return popper
|
||||
}
|
||||
|
||||
test('test_notification_panel_groups_and_pagination', async ({ page }) => {
|
||||
await openBell(page)
|
||||
|
||||
const panel = page.locator('.bell-panel')
|
||||
const nextPage = panel.getByRole('button', { name: '下一页' })
|
||||
|
||||
// 每页 10 条,跨两个日期分组,页脚显示页码与总数
|
||||
await expect(page.locator('.bell-item')).toHaveCount(10)
|
||||
// 一页 6 组:09-13 的 4 组 + 09-12 的 2 组 ⇒ 日期头 2 个(同一天可以多组)
|
||||
await expect(page.locator('.bell-group')).toHaveCount(6)
|
||||
await expect(page.locator('.bell-day-head')).toHaveCount(2)
|
||||
await expect(page.locator('.bell-page-info')).toHaveText('1 / 2')
|
||||
await expect(page.locator('.bell-page-total')).toHaveText('共 14 条')
|
||||
await expect(page.locator('.bell-day-head').first()).toHaveText(/^(今天|昨天|\d{4}年\d{1,2}月\d{1,2}日)$/)
|
||||
await expect(page.locator('.bell-page-info')).toHaveText('1 / 2')
|
||||
await expect(page.locator('.bell-page-total')).toHaveText('共 10 组 · 明细 14 条')
|
||||
// 聚合行必须把"折叠前几条、其中几条没读"写在行上
|
||||
await expect(page.locator('.bell-group-count').first()).toHaveText('1 条 · 1 未读')
|
||||
|
||||
const page2Request = page.waitForRequest(
|
||||
(request) => request.url().includes('/api/admin/notifications?') && request.url().includes('page=2'),
|
||||
(request) => request.url().includes('/api/admin/notifications/groups?') && request.url().includes('page=2'),
|
||||
)
|
||||
await nextPage.click()
|
||||
await page2Request
|
||||
|
||||
await expect(page.locator('.bell-item')).toHaveCount(4)
|
||||
await expect(page.locator('.bell-group')).toHaveCount(4)
|
||||
await expect(page.locator('.bell-page-info')).toHaveText('2 / 2')
|
||||
await expect(page.locator('.bell-day-head')).toHaveCount(1)
|
||||
await expect(nextPage).toBeDisabled()
|
||||
})
|
||||
|
||||
@@ -45,37 +85,129 @@ test('test_notification_panel_search_by_keyword', async ({ page }) => {
|
||||
await page.locator('.bell-search-input').fill('余额不足')
|
||||
await keywordRequest
|
||||
|
||||
// 关键字命中标题/内容:夹具里 5 条含「余额不足」
|
||||
await expect(page.locator('.bell-item')).toHaveCount(5)
|
||||
await expect(page.locator('.bell-page-total')).toHaveText('共 5 条')
|
||||
// 关键字命中标题/内容:夹具里 5 条含「余额不足」,且分属 5 个不同的组
|
||||
await expect(page.locator('.bell-group')).toHaveCount(5)
|
||||
await expect(page.locator('.bell-page-total')).toHaveText('共 5 组 · 明细 5 条')
|
||||
await expect(page.locator('.bell-search-reset')).toBeVisible()
|
||||
|
||||
await page.locator('.bell-search-reset').click()
|
||||
await expect(page.locator('.bell-item')).toHaveCount(10)
|
||||
// 重置回到面板的默认视图:清空关键字、日期恢复「当天」(当天不是清空日期)
|
||||
await expect(page.locator('.bell-search-input')).toHaveValue('')
|
||||
await expect(page.locator('.bell-search-reset')).toBeHidden()
|
||||
await expect(page.locator('.bell-empty')).toHaveText('暂无通知')
|
||||
})
|
||||
|
||||
/** 红点按**组数**亮:3 条未读落在 2 个组里,徽标就是 2 而不是 3。 */
|
||||
test('test_notification_panel_badge_counts_groups_not_rows', async ({ page }) => {
|
||||
await page.goto('/admin-vue/')
|
||||
await expect(page.locator('.admin-notification-bell .bell-badge')).toHaveText('2')
|
||||
})
|
||||
|
||||
test('test_notification_panel_expand_group_loads_that_group_only', async ({ page }) => {
|
||||
await openBell(page)
|
||||
|
||||
const groups = page.locator('.bell-group')
|
||||
await expect(groups).toHaveCount(6)
|
||||
|
||||
const firstDetailRequest = page.waitForRequest((request) => {
|
||||
const url = new URL(request.url())
|
||||
return (
|
||||
url.pathname.endsWith('/api/admin/notifications') &&
|
||||
url.searchParams.get('scene') === 'secret_balance' &&
|
||||
url.searchParams.get('day') === '2026-09-13' &&
|
||||
url.searchParams.get('subjectUserId') === '1196'
|
||||
)
|
||||
})
|
||||
await groups.first().click()
|
||||
await firstDetailRequest
|
||||
await expect(page.locator('.bell-item--detail')).toHaveCount(1)
|
||||
await expect(page.locator('.bell-group--open')).toHaveCount(1)
|
||||
|
||||
// 换一组展开:上一组的明细必须收掉,不能两组明细叠在一起
|
||||
const secondDetailRequest = page.waitForRequest((request) => {
|
||||
const url = new URL(request.url())
|
||||
return (
|
||||
url.pathname.endsWith('/api/admin/notifications') &&
|
||||
url.searchParams.get('scene') === 'task_failed' &&
|
||||
url.searchParams.get('subjectUserId') === '1196'
|
||||
)
|
||||
})
|
||||
await groups.nth(1).click()
|
||||
await secondDetailRequest
|
||||
await expect(page.locator('.bell-item--detail')).toHaveCount(2)
|
||||
await expect(page.locator('.bell-group--open')).toHaveCount(1)
|
||||
|
||||
// 再点一次收起
|
||||
await groups.nth(1).click()
|
||||
await expect(page.locator('.bell-item--detail')).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('test_notification_panel_date_popper_not_covered_by_panel', async ({ page }) => {
|
||||
await openBell(page)
|
||||
await openCalendar(page)
|
||||
|
||||
// 日历与通知面板同为挂在 body 上的浮层:逐格做命中测试,最上层必须还是日历自己。
|
||||
// 通知面板 z-index 3200 高于 Element 默认弹层段(自 2000 递增)时,日历整块被压在
|
||||
// 面板底下,用户看到的就是「日期点不动」——这里必须判红而不是靠肉眼发现。
|
||||
const covered = await page.evaluate(() => {
|
||||
const pop = document.querySelector('.bell-date-popper') as HTMLElement
|
||||
const panel = document.querySelector('.bell-panel') as HTMLElement
|
||||
const blocked: string[] = []
|
||||
for (const cell of Array.from(pop.querySelectorAll<HTMLTableCellElement>('td.available'))) {
|
||||
const rect = cell.getBoundingClientRect()
|
||||
if (rect.bottom > window.innerHeight || rect.right > window.innerWidth) continue
|
||||
const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2)
|
||||
if (!hit || !pop.contains(hit)) blocked.push(String(hit?.className ?? hit?.tagName ?? 'null'))
|
||||
}
|
||||
return { blocked, popperZ: getComputedStyle(pop).zIndex, panelZ: getComputedStyle(panel).zIndex }
|
||||
})
|
||||
expect(covered.blocked, `日历被通知面板遮挡(popper=${covered.popperZ},panel=${covered.panelZ})`).toEqual([])
|
||||
})
|
||||
|
||||
/** 把左栏翻到 2026 年 9 月,返回按日取格的点击器(夹具:09-10 四条、09-12 四条、09-13 六条)。 */
|
||||
async function openRangeOnSeptember(page: Page) {
|
||||
const popper = await openCalendar(page)
|
||||
await popper.locator('.el-picker-panel__icon-btn.arrow-left').click()
|
||||
const leftPanel = popper.locator('.el-date-range-picker__content').first()
|
||||
const day = (text: string) =>
|
||||
leftPanel.locator('td.available .el-date-table-cell__text', { hasText: new RegExp(`^${text}$`) })
|
||||
await expect(day('10')).toBeVisible()
|
||||
return day
|
||||
}
|
||||
|
||||
test('test_notification_panel_search_by_day_range', async ({ page }) => {
|
||||
await openBell(page)
|
||||
const day = await openRangeOnSeptember(page)
|
||||
|
||||
// 09-10 四条折成 3 组(两个用户 × 两个场景组合)
|
||||
const rangeRequest = page.waitForRequest(
|
||||
(request) =>
|
||||
request.url().includes('startDate=2026-09-12') && request.url().includes('endDate=2026-09-12'),
|
||||
request.url().includes('startDate=2026-09-10') && request.url().includes('endDate=2026-09-12'),
|
||||
)
|
||||
await page.locator('.bell-date-input').first().fill('2026-09-12')
|
||||
await page.locator('.bell-date-input').nth(1).fill('2026-09-12')
|
||||
await day('10').click()
|
||||
await day('12').click()
|
||||
await rangeRequest
|
||||
|
||||
await expect(page.locator('.bell-item')).toHaveCount(4)
|
||||
await expect(page.locator('.bell-day-head')).toHaveCount(1)
|
||||
await expect(page.locator('.bell-page-total')).toHaveText('共 4 条')
|
||||
await expect(page.locator('.bell-page-total')).toHaveText('共 6 组 · 明细 8 条')
|
||||
await expect(page.locator('.bell-day-head')).toHaveCount(2)
|
||||
await expect(page.locator('.bell-empty')).toHaveCount(0)
|
||||
// 选完区间后面板必须还开着:日历挂在 body 上,不能被「点击外部关闭」当成面板外
|
||||
await expect(page.locator('.bell-panel')).toBeVisible()
|
||||
})
|
||||
|
||||
// 起止倒挂自动交换:09-13 起 / 09-10 止 → 实际按 09-10 ~ 09-13 查询(全量 14 条)
|
||||
await page.locator('.bell-date-input').first().fill('2026-09-13')
|
||||
await page.locator('.bell-date-input').nth(1).fill('2026-09-10')
|
||||
await expect(page.locator('.bell-page-total')).toHaveText('共 14 条')
|
||||
await expect(page.locator('.bell-item')).toHaveCount(10)
|
||||
test('test_notification_panel_day_range_picked_backwards', async ({ page }) => {
|
||||
await openBell(page)
|
||||
const day = await openRangeOnSeptember(page)
|
||||
|
||||
// 先点 13 再点 10:控件自己保证起 ≤ 止,落到 09-10 ~ 09-13(全量 14 条 / 10 组)
|
||||
const swappedRequest = page.waitForRequest(
|
||||
(request) =>
|
||||
request.url().includes('startDate=2026-09-10') && request.url().includes('endDate=2026-09-13'),
|
||||
)
|
||||
await day('13').click()
|
||||
await day('10').click()
|
||||
await swappedRequest
|
||||
await expect(page.locator('.bell-page-total')).toHaveText('共 10 组 · 明细 14 条')
|
||||
})
|
||||
|
||||
test('test_notification_panel_not_covered_by_page_content', async ({ page }) => {
|
||||
@@ -102,21 +234,47 @@ test('test_notification_panel_not_covered_by_page_content', async ({ page }) =>
|
||||
test('test_notification_panel_reference_screenshot', async ({ page }) => {
|
||||
await openBell(page)
|
||||
|
||||
// 同日多条不得重叠:逐条校验纵向排布严格递增(截图伪影与真实布局问题的分界)
|
||||
const tops = await page
|
||||
.locator('.bell-item')
|
||||
.locator('.bell-group')
|
||||
.evaluateAll((els) => els.map((el) => el.getBoundingClientRect().top))
|
||||
for (let i = 1; i < tops.length; i += 1) {
|
||||
expect(tops[i], `第 ${i + 1} 条应排在第 ${i} 条下方`).toBeGreaterThan(tops[i - 1])
|
||||
expect(tops[i], `第 ${i + 1} 组应排在第 ${i} 组下方`).toBeGreaterThan(tops[i - 1])
|
||||
}
|
||||
|
||||
await page.screenshot({ path: 'test-results/notification-panel-admin-page.jpg', animations: 'disabled' })
|
||||
await page.locator('.bell-panel').screenshot({ path: 'test-results/notification-panel-admin.jpg', animations: 'disabled' })
|
||||
|
||||
await page.locator('.bell-search-input').fill('余额不足')
|
||||
await expect(page.locator('.bell-item')).toHaveCount(5)
|
||||
await page.locator('.bell-panel').screenshot({
|
||||
path: 'test-results/notification-panel-admin-search.jpg',
|
||||
path: 'test-results/notification-panel-admin-groups.jpg',
|
||||
animations: 'disabled',
|
||||
})
|
||||
await page.locator('.bell-group').first().click()
|
||||
await expect(page.locator('.bell-item--detail')).toHaveCount(1)
|
||||
await page.locator('.bell-panel').screenshot({
|
||||
path: 'test-results/notification-panel-admin-expanded.jpg',
|
||||
animations: 'disabled',
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* 已读只能进明细逐条点(口径见设计):组内未读清零,红点才掉一格。
|
||||
*/
|
||||
test('test_notification_panel_mark_read_from_detail_drops_group_last', async ({ page }) => {
|
||||
await openBell(page)
|
||||
|
||||
const group = page.locator('.bell-group').nth(1)
|
||||
await expect(group.locator('.bell-group-count')).toHaveText('2 条 · 2 未读')
|
||||
await group.click()
|
||||
await expect(page.locator('.bell-item--detail')).toHaveCount(2)
|
||||
// 每次点的都必须是「还红着」的那条:已读行点了不做事(onItemClick 直接 return),
|
||||
// 拿 .first() 连点两次会第二次点到刚读过的那条,看着像"没扣数"。
|
||||
const unread = page.locator('.bell-item--detail.bell-item--unread')
|
||||
|
||||
await unread.first().click()
|
||||
await expect(unread).toHaveCount(1)
|
||||
await expect(group.locator('.bell-group-count')).toHaveText('2 条 · 1 未读')
|
||||
// 还剩一条未读 ⇒ 这一组仍计为一个未读组,红点不动
|
||||
await expect(page.locator('.admin-notification-bell .bell-badge')).toHaveText('2')
|
||||
|
||||
await unread.first().click()
|
||||
await expect(unread).toHaveCount(0)
|
||||
await expect(group.locator('.bell-group-count')).toHaveText('2 条')
|
||||
await expect(page.locator('.admin-notification-bell .bell-badge')).toHaveText('1')
|
||||
})
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import { defineConfig } from '@playwright/test'
|
||||
|
||||
/**
|
||||
* 浏览器验收:起 mock admin API(18100) + vite dev(5174, /api 代理到 mock)。
|
||||
* 浏览器验收:起 mock admin API(18100) + vite dev(E2E_PORT,默认 5174, /api 代理到 mock)。
|
||||
* 本地用已安装的 MS Edge(channel: msedge)运行,无需下载 Chromium。
|
||||
*
|
||||
* 端口必须可改:5174 被别的项目占用时 vite 会顺延到别的端口,而 reuseExistingServer
|
||||
* 会让 playwright 直接连上那个「不是本站」的服务,整份验收测的是别人的页面。
|
||||
*/
|
||||
const PORT = Number(process.env.E2E_PORT || 5174)
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
timeout: 45_000,
|
||||
@@ -13,7 +18,7 @@ export default defineConfig({
|
||||
retries: 0,
|
||||
reporter: [['list']],
|
||||
use: {
|
||||
baseURL: 'http://127.0.0.1:5174',
|
||||
baseURL: `http://127.0.0.1:${PORT}`,
|
||||
channel: 'msedge',
|
||||
headless: true,
|
||||
viewport: { width: 1440, height: 900 },
|
||||
@@ -26,8 +31,8 @@ export default defineConfig({
|
||||
reuseExistingServer: true,
|
||||
},
|
||||
{
|
||||
command: 'set VITE_API_TARGET=http://127.0.0.1:18100&& npm run dev',
|
||||
port: 5174,
|
||||
command: `set VITE_API_TARGET=http://127.0.0.1:18100&& npm run dev -- --port ${PORT} --strictPort`,
|
||||
port: PORT,
|
||||
reuseExistingServer: true,
|
||||
timeout: 120_000,
|
||||
},
|
||||
|
||||
@@ -152,33 +152,93 @@ const TUTORIAL_PACKAGES = [
|
||||
]
|
||||
|
||||
/* ===================== 站内通知夹具(铃铛面板:搜索/按天分组/分页验收用) ===================== */
|
||||
/**
|
||||
* 通知夹具。两条约定不能破:
|
||||
* ① id 与 createdAt 同为插入时单调(09-10 最早 ⇒ id 最小)——与真库一致;倒挂会让
|
||||
* "按 id 倒序即按天倒序"这种隐藏假设在 mock 里成立、上线就翻车。
|
||||
* ② 场景显式给,不从 id 取模推——否则换一批 id,「余额不足」命中数与聚合组数一起漂,
|
||||
* 用例断言就成了跟着夹具跑的活字。
|
||||
* 共 14 行、5 行密钥告警;按 场景×自然日×主体用户 折成 10 组,其中 2 组未读、3 行未读。
|
||||
*/
|
||||
const NOTIFICATIONS = [
|
||||
...[6, 5, 4, 3, 2, 1].map((seq) => notif(seq, '2026-09-13', 22, seq, seq <= 3)),
|
||||
...[4, 3, 2, 1].map((seq) => notif(20 + seq, '2026-09-12', 20, seq, true)),
|
||||
...[4, 3, 2, 1].map((seq) => notif(30 + seq, '2026-09-10', 18, seq, true)),
|
||||
]
|
||||
['2026-09-10', 18, 1, true, 'task_failed'],
|
||||
['2026-09-10', 18, 2, true, 'task_failed'],
|
||||
['2026-09-10', 18, 3, true, 'secret_balance'],
|
||||
['2026-09-10', 18, 4, true, 'task_failed'],
|
||||
['2026-09-12', 20, 1, true, 'secret_balance'],
|
||||
['2026-09-12', 20, 2, true, 'task_failed'],
|
||||
['2026-09-12', 20, 3, true, 'task_failed'],
|
||||
['2026-09-12', 20, 4, true, 'secret_balance'],
|
||||
['2026-09-13', 22, 1, true, 'task_failed'],
|
||||
['2026-09-13', 22, 2, true, 'task_failed'],
|
||||
['2026-09-13', 22, 3, true, 'secret_balance'],
|
||||
['2026-09-13', 22, 4, false, 'task_failed'],
|
||||
['2026-09-13', 22, 5, false, 'task_failed'],
|
||||
['2026-09-13', 22, 6, false, 'secret_balance'],
|
||||
].map(([day, hour, seq, read, scene], index) => notif(index + 1, day, hour, seq, read, scene))
|
||||
|
||||
function notif(id, day, hour, seq, read) {
|
||||
const NOTIFICATION_SEED = structuredClone(NOTIFICATIONS)
|
||||
|
||||
function notif(id, day, hour, seq, read, scene) {
|
||||
const minutes = String(seq * 7).padStart(2, '0')
|
||||
const secret = scene === 'secret_balance'
|
||||
return {
|
||||
id,
|
||||
scene: id % 3 === 0 ? 'secret_balance' : 'task_failed',
|
||||
level: id % 3 === 0 ? 'error' : 'warning',
|
||||
title: id % 3 === 0 ? `用户密钥异常:测试用户${seq}` : `跟价任务失败`,
|
||||
content: id % 3 === 0 ? `用户 测试用户${seq}(uid=${1100 + seq})的代理设置对应服务商余额不足` : `用户 测试用户${seq} 有 ${seq} 个跟价任务失败`,
|
||||
scene,
|
||||
level: secret ? 'error' : 'warning',
|
||||
title: secret ? `用户密钥异常:测试用户${seq}` : `跟价任务失败`,
|
||||
content: secret
|
||||
? `用户 测试用户${seq}(uid=${1100 + seq})的代理设置对应服务商余额不足`
|
||||
: `用户 测试用户${seq} 有 ${seq} 个跟价任务失败`,
|
||||
// 事件主体用户:与后端 V158 那列同义,聚合分组键的第三维。seq>3 归 1196、其余归 1160,
|
||||
// 让"同一天两个用户"在夹具里真的存在(否则聚合视图测不到按用户拆组这一维)。
|
||||
subjectUserId: seq > 3 ? 1196 : 1160,
|
||||
read,
|
||||
readAt: read ? `${day} ${hour}:${minutes}:00` : null,
|
||||
createdAt: `${day} ${hour}:${minutes}:00`,
|
||||
}
|
||||
}
|
||||
|
||||
/** 与后端 groups 出口同形的聚合:场景 × 自然日 × 主体用户。 */
|
||||
function groupRows(rows) {
|
||||
const byKey = new Map()
|
||||
for (const item of [...rows].sort((a, b) => b.id - a.id)) {
|
||||
const day = item.createdAt.slice(0, 10)
|
||||
const key = `${item.scene}|${day}|${item.subjectUserId ?? 'none'}`
|
||||
let group = byKey.get(key)
|
||||
if (!group) {
|
||||
group = {
|
||||
latestId: item.id,
|
||||
scene: item.scene,
|
||||
category: item.scene === 'secret_balance' ? 'config_error' : 'task_error',
|
||||
day,
|
||||
subjectUserId: item.subjectUserId ?? null,
|
||||
rowCount: 0,
|
||||
unreadCount: 0,
|
||||
level: item.level,
|
||||
title: item.title,
|
||||
content: item.content,
|
||||
createdAt: item.createdAt,
|
||||
}
|
||||
byKey.set(key, group)
|
||||
}
|
||||
group.rowCount += 1
|
||||
if (!item.read) group.unreadCount += 1
|
||||
if (item.level === 'error') group.level = 'error'
|
||||
}
|
||||
return [...byKey.values()]
|
||||
}
|
||||
|
||||
/** 通知列表:关键字匹配标题/内容,日期按年月日区间(与 Java 侧同语义)。 */
|
||||
function notificationPage(searchParams) {
|
||||
/** 列表与聚合共用的筛选:关键字 / 日期区间 / 展开某一组(场景 + 自然日 + 主体用户)。 */
|
||||
function filteredRows(searchParams) {
|
||||
const keyword = (searchParams.get('keyword') || '').trim()
|
||||
const startDate = searchParams.get('startDate') || ''
|
||||
const endDate = searchParams.get('endDate') || ''
|
||||
const page = Math.max(1, Number(searchParams.get('page') || 1))
|
||||
const pageSize = Math.min(100, Math.max(1, Number(searchParams.get('pageSize') || 20)))
|
||||
const scene = searchParams.get('scene') || ''
|
||||
const day = searchParams.get('day') || ''
|
||||
const subjectUserId = searchParams.get('subjectUserId')
|
||||
const subjectUnlabelled = searchParams.get('subjectUnlabelled') === 'true'
|
||||
let rows = NOTIFICATIONS
|
||||
if (keyword) {
|
||||
rows = rows.filter((item) => `${item.title}${item.content}`.includes(keyword))
|
||||
@@ -189,7 +249,29 @@ function notificationPage(searchParams) {
|
||||
if (endDate) {
|
||||
rows = rows.filter((item) => item.createdAt.slice(0, 10) <= endDate)
|
||||
}
|
||||
const start = (page - 1) * pageSize
|
||||
if (scene) {
|
||||
rows = rows.filter((item) => item.scene === scene)
|
||||
}
|
||||
if (day) {
|
||||
rows = rows.filter((item) => item.createdAt.slice(0, 10) === day)
|
||||
}
|
||||
if (subjectUserId) {
|
||||
rows = rows.filter((item) => String(item.subjectUserId) === String(subjectUserId))
|
||||
} else if (subjectUnlabelled) {
|
||||
rows = rows.filter((item) => item.subjectUserId === null || item.subjectUserId === undefined)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
function readPaging(searchParams) {
|
||||
const page = Math.max(1, Number(searchParams.get('page') || 1))
|
||||
const pageSize = Math.min(100, Math.max(1, Number(searchParams.get('pageSize') || 20)))
|
||||
return { page, pageSize, start: (page - 1) * pageSize }
|
||||
}
|
||||
|
||||
function notificationPage(searchParams) {
|
||||
const rows = filteredRows(searchParams)
|
||||
const { page, pageSize, start } = readPaging(searchParams)
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
@@ -202,6 +284,25 @@ function notificationPage(searchParams) {
|
||||
}
|
||||
}
|
||||
|
||||
/** 聚合出口:分页按组切,total=组数、rowCount=折叠前的明细条数,两个都给前端。 */
|
||||
function notificationGroupsPage(searchParams) {
|
||||
const rows = filteredRows(searchParams)
|
||||
const groups = groupRows(rows)
|
||||
const { page, pageSize, start } = readPaging(searchParams)
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
groups: groups.slice(start, start + pageSize),
|
||||
total: groups.length,
|
||||
rowCount: rows.length,
|
||||
page,
|
||||
pageSize,
|
||||
unreadGroupCount: groups.filter((group) => group.unreadCount > 0).length,
|
||||
unreadCount: rows.filter((item) => !item.read).length,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const server = createServer((req, res) => {
|
||||
const url = (req.url || '').split('?')[0]
|
||||
const method = req.method || 'GET'
|
||||
@@ -410,15 +511,44 @@ const server = createServer((req, res) => {
|
||||
data: { pending: false, scanned_at: '2026-09-05 08:30:00', items: ALL_ROWS, total: ALL_ROWS.length, page: 1, page_size: 20 },
|
||||
})
|
||||
}
|
||||
// 已读标记会改内存里的夹具(不是幂等只读口)⇒ 用例之间要靠下面这条重置口隔离,
|
||||
// 否则同一份 mock 服务被 reuseExistingServer 复用时,第二次跑就会带着上一次的已读态。
|
||||
if (method === 'POST' && url === '/api/admin/notifications/__reset') {
|
||||
NOTIFICATIONS.splice(0, NOTIFICATIONS.length, ...structuredClone(NOTIFICATION_SEED))
|
||||
return json(res, { success: true, data: NOTIFICATIONS.length })
|
||||
}
|
||||
if (method === 'POST' && /^\/api\/admin\/notifications\/\d+\/read$/.test(url)) {
|
||||
const id = Number(url.split('/')[3])
|
||||
const item = NOTIFICATIONS.find((row) => row.id === id)
|
||||
if (item && !item.read) {
|
||||
item.read = true
|
||||
item.readAt = `${item.createdAt.slice(0, 10)} 23:59:59`
|
||||
}
|
||||
return json(res, { success: true, data: true })
|
||||
}
|
||||
if (method === 'POST' && url === '/api/admin/notifications/read-all') {
|
||||
for (const item of NOTIFICATIONS) {
|
||||
if (!item.read) {
|
||||
item.read = true
|
||||
item.readAt = `${item.createdAt.slice(0, 10)} 23:59:59`
|
||||
}
|
||||
}
|
||||
return json(res, { success: true, data: NOTIFICATIONS.length })
|
||||
}
|
||||
if (url === '/api/admin/notifications/summary') {
|
||||
const groups = groupRows(NOTIFICATIONS)
|
||||
return json(res, {
|
||||
success: true,
|
||||
data: {
|
||||
unreadCount: NOTIFICATIONS.filter((item) => !item.read).length,
|
||||
unreadGroupCount: groups.filter((group) => group.unreadCount > 0).length,
|
||||
latestId: NOTIFICATIONS.reduce((max, item) => Math.max(max, item.id), 0),
|
||||
},
|
||||
})
|
||||
}
|
||||
if (url === '/api/admin/notifications/groups') {
|
||||
return json(res, notificationGroupsPage(new URL(req.url || '/', 'http://127.0.0.1').searchParams))
|
||||
}
|
||||
if (url === '/api/admin/notifications') {
|
||||
return json(res, notificationPage(new URL(req.url || '/', 'http://127.0.0.1').searchParams))
|
||||
}
|
||||
|
||||
@@ -23,9 +23,38 @@ export interface AdminNotificationPage {
|
||||
|
||||
export interface AdminNotificationSummary {
|
||||
unreadCount: number
|
||||
/** 有未读的聚合组数;徽标用它。unreadCount 仍是"条数",给老明细视图与对账用。 */
|
||||
unreadGroupCount?: number
|
||||
latestId: number
|
||||
}
|
||||
|
||||
/** 聚合组:一个「场景 × 自然日 × 事件主体用户」折成的一行。 */
|
||||
export interface AdminNotificationGroup {
|
||||
latestId: number
|
||||
scene: string
|
||||
category: string
|
||||
day: string
|
||||
subjectUserId: number | null
|
||||
rowCount: number
|
||||
unreadCount: number
|
||||
level: string
|
||||
title: string
|
||||
content: string
|
||||
createdAt: string | null
|
||||
}
|
||||
|
||||
export interface AdminNotificationGroupPage {
|
||||
groups: AdminNotificationGroup[]
|
||||
/** 组数(分页分母)。 */
|
||||
total: number
|
||||
/** 折叠前的明细条数——必须与 total 同屏,否则「共 12 条」会被读成只有 12 条通知。 */
|
||||
rowCount: number
|
||||
page: number
|
||||
pageSize: number
|
||||
unreadGroupCount: number
|
||||
unreadCount: number
|
||||
}
|
||||
|
||||
/** 铃铛轮询:未读数 + 最新通知 id。 */
|
||||
export async function fetchNotificationSummary(): Promise<AdminNotificationSummary> {
|
||||
const { data } = await http.get('/api/admin/notifications/summary')
|
||||
@@ -40,6 +69,30 @@ export interface AdminNotificationListParams {
|
||||
keyword?: string
|
||||
startDate?: string
|
||||
endDate?: string
|
||||
/** 展开聚合组:三个条件取自该组自己返回的值,原样回传。 */
|
||||
scene?: string
|
||||
day?: string
|
||||
subjectUserId?: number | null
|
||||
/** true 表示展开「未区分用户」那一组(subject_user_id 为空的存量行)。 */
|
||||
subjectUnlabelled?: boolean
|
||||
}
|
||||
|
||||
/** 聚合列表(铃铛默认视图)。分页按组切。 */
|
||||
export async function fetchNotificationGroups(
|
||||
params: AdminNotificationListParams = {},
|
||||
): Promise<AdminNotificationGroupPage> {
|
||||
const keyword = (params.keyword ?? '').trim()
|
||||
const { data } = await http.get('/api/admin/notifications/groups', {
|
||||
params: {
|
||||
page: params.page ?? 1,
|
||||
pageSize: params.pageSize ?? 20,
|
||||
onlyUnread: params.onlyUnread ? 'true' : 'false',
|
||||
keyword: keyword || undefined,
|
||||
startDate: params.startDate || undefined,
|
||||
endDate: params.endDate || undefined,
|
||||
},
|
||||
})
|
||||
return unwrap<AdminNotificationGroupPage>(data)
|
||||
}
|
||||
|
||||
export async function fetchNotificationList(
|
||||
@@ -54,6 +107,10 @@ export async function fetchNotificationList(
|
||||
keyword: keyword || undefined,
|
||||
startDate: params.startDate || undefined,
|
||||
endDate: params.endDate || undefined,
|
||||
scene: params.scene || undefined,
|
||||
day: params.day || undefined,
|
||||
subjectUserId: params.subjectUserId ?? undefined,
|
||||
subjectUnlabelled: params.subjectUnlabelled ? 'true' : undefined,
|
||||
},
|
||||
})
|
||||
return unwrap<AdminNotificationPage>(data)
|
||||
|
||||
@@ -77,25 +77,48 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="loading && !items.length" class="bell-empty">正在加载...</div>
|
||||
<div v-else-if="loadError && !items.length" class="bell-empty bell-empty--error">{{ loadError }}</div>
|
||||
<div v-else-if="!items.length" class="bell-empty">{{ hasFilter ? '没有符合条件的通知' : '暂无通知' }}</div>
|
||||
<div v-if="loading && !groups.length" class="bell-empty">正在加载...</div>
|
||||
<div v-else-if="loadError && !groups.length" class="bell-empty bell-empty--error">{{ loadError }}</div>
|
||||
<div v-else-if="!groups.length" class="bell-empty">{{ hasFilter ? '没有符合条件的通知' : '暂无通知' }}</div>
|
||||
<ul v-else class="bell-list">
|
||||
<template v-for="group in groupedItems" :key="group.day || 'unknown'">
|
||||
<li class="bell-day-head">{{ group.label }}</li>
|
||||
<template v-for="(group, index) in groups" :key="notificationGroupKey(group)">
|
||||
<li v-if="startsNewDay(index)" class="bell-day-head">{{ formatDayLabel(group.day) }}</li>
|
||||
<li
|
||||
v-for="item in group.items"
|
||||
:key="item.id"
|
||||
class="bell-item"
|
||||
:class="[`bell-item--${item.level || 'warning'}`, { 'bell-item--unread': !item.read }]"
|
||||
@click="onItemClick(item)"
|
||||
class="bell-group"
|
||||
:class="[`bell-item--${group.level || 'warning'}`, { 'bell-group--open': isExpanded(group) }]"
|
||||
@click="toggleGroup(group)"
|
||||
>
|
||||
<div class="bell-item-head">
|
||||
<span class="bell-item-title">{{ item.title }}</span>
|
||||
<span class="bell-item-time">{{ formatTime(item.createdAt) }}</span>
|
||||
<span class="bell-item-title">{{ group.title }}</span>
|
||||
<span class="bell-item-time">{{ formatTime(group.createdAt) }}</span>
|
||||
</div>
|
||||
<div class="bell-item-content">{{ group.content }}</div>
|
||||
<div class="bell-group-foot">
|
||||
<span class="bell-group-count">{{ formatGroupCounts(group.rowCount, group.unreadCount) }}</span>
|
||||
<span class="bell-group-toggle">{{ isExpanded(group) ? '收起明细' : '展开明细' }}</span>
|
||||
</div>
|
||||
<div class="bell-item-content">{{ item.content }}</div>
|
||||
</li>
|
||||
<!-- 已读只能进明细逐条点:聚合行上的点击只做展开,避免"看一眼顺手把没看过的全标成已读" -->
|
||||
<template v-if="isExpanded(group)">
|
||||
<li v-if="detailLoading" class="bell-empty bell-empty--detail">正在加载明细...</li>
|
||||
<li v-else-if="!details.length" class="bell-empty bell-empty--detail">这一组里没有通知</li>
|
||||
<li
|
||||
v-for="item in details"
|
||||
:key="item.id"
|
||||
class="bell-item bell-item--detail"
|
||||
:class="{ 'bell-item--unread': !item.read }"
|
||||
@click="onItemClick(item)"
|
||||
>
|
||||
<div class="bell-item-head">
|
||||
<span class="bell-item-title">{{ item.title }}</span>
|
||||
<span class="bell-item-time">{{ formatTime(item.createdAt) }}</span>
|
||||
</div>
|
||||
<div class="bell-item-content">{{ item.content }}</div>
|
||||
</li>
|
||||
<li v-if="!detailLoading && detailTotal > details.length" class="bell-detail-more">
|
||||
另有 {{ detailTotal - details.length }} 条未列出,可缩小日期范围后查看
|
||||
</li>
|
||||
</template>
|
||||
</template>
|
||||
</ul>
|
||||
|
||||
@@ -117,7 +140,7 @@
|
||||
>
|
||||
下一页
|
||||
</button>
|
||||
<span class="bell-page-total">共 {{ total }} 条</span>
|
||||
<span class="bell-page-total">共 {{ total }} 组 · 明细 {{ rowCount }} 条</span>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
@@ -125,177 +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 {
|
||||
fetchNotificationList,
|
||||
fetchNotificationSummary,
|
||||
markAllNotificationsRead,
|
||||
markNotificationRead,
|
||||
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,
|
||||
groupNotificationsByDay,
|
||||
hasNewNotification,
|
||||
markReadFailureMessage,
|
||||
readLastNotifiedId,
|
||||
writeLastNotifiedId,
|
||||
notificationGroupKey,
|
||||
} from '@/layout/notification-bell-model'
|
||||
import { todayDateInput } from '@/utils/datetime'
|
||||
|
||||
const PAGE_SIZE = 10
|
||||
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 items = ref<AdminNotificationItem[]>([])
|
||||
const total = 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 badgeText = computed(() => formatUnreadBadge(unreadCount.value))
|
||||
const groupedItems = computed(() => groupNotificationsByDay(items.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) : ''
|
||||
/** 模板里仍是 startsNewDay(index):组序列在面板层,这里只补一次取值。 */
|
||||
function startsNewDay(index: number): boolean {
|
||||
return groupStartsNewDay(groups.value, index)
|
||||
}
|
||||
|
||||
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)
|
||||
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 fetchNotificationList({
|
||||
page: targetPage,
|
||||
pageSize: PAGE_SIZE,
|
||||
keyword: keyword.value,
|
||||
...normalizedDayRange(),
|
||||
})
|
||||
const list = Array.isArray(result?.items) ? result.items : []
|
||||
items.value = list
|
||||
total.value = Number(result?.total ?? list.length)
|
||||
unreadCount.value = Number(result?.unreadCount ?? unreadCount.value)
|
||||
page.value = targetPage
|
||||
loadError.value = ''
|
||||
// 无筛选时首页就是最新数据,顺带记录「已提醒过的最大 id」;有筛选时最新 id 不代表真实最新
|
||||
if (targetPage <= 1 && !hasFilter.value && list.length) {
|
||||
const latest = Number(list[0].id)
|
||||
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 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 定位,位置按触发器实时算(右对齐在铃铛下方)。 */
|
||||
@@ -313,44 +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)
|
||||
} 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 item of items.value) {
|
||||
item.read = true
|
||||
}
|
||||
unreadCount.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
|
||||
@@ -370,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)
|
||||
})
|
||||
|
||||
@@ -395,10 +280,6 @@ onUnmounted(() => {
|
||||
window.clearInterval(pollTimer)
|
||||
pollTimer = null
|
||||
}
|
||||
if (searchTimer != null) {
|
||||
window.clearTimeout(searchTimer)
|
||||
searchTimer = null
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -528,6 +409,70 @@ onUnmounted(() => {
|
||||
background: #f7f9fc;
|
||||
}
|
||||
|
||||
/* ---- 聚合行(默认视图的一级)与明细行(展开后的二级)---- */
|
||||
.bell-group {
|
||||
padding: 11px 14px 8px;
|
||||
border-bottom: 1px solid #f0f3f7;
|
||||
cursor: pointer;
|
||||
transition: background 0.12s ease;
|
||||
}
|
||||
|
||||
.bell-group:hover {
|
||||
background: #f7f9fc;
|
||||
}
|
||||
|
||||
.bell-group--open {
|
||||
background: #f4f8fd;
|
||||
}
|
||||
|
||||
.bell-group-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.bell-group-count {
|
||||
color: #7c8b9a;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.bell-group-toggle {
|
||||
color: var(--admin-primary-strong, #2f5d8b);
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* 明细缩进 + 左侧一道竖线,让"这是上面那一组里的东西"看得出来,而不是又一批同级通知 */
|
||||
.bell-item--detail {
|
||||
padding-left: 26px;
|
||||
background: #fcfdfe;
|
||||
border-bottom-color: #f5f8fb;
|
||||
}
|
||||
|
||||
.bell-item--detail::before {
|
||||
content: '';
|
||||
display: inline-block;
|
||||
width: 2px;
|
||||
height: 26px;
|
||||
margin: 0 0 -8px -14px;
|
||||
border-radius: 2px;
|
||||
background: #dce7f2;
|
||||
}
|
||||
|
||||
.bell-empty--detail {
|
||||
padding: 14px 0;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.bell-detail-more {
|
||||
padding: 8px 14px;
|
||||
color: #8a99a8;
|
||||
font-size: 11px;
|
||||
text-align: center;
|
||||
background: #fcfdfe;
|
||||
}
|
||||
|
||||
.bell-item--unread {
|
||||
background: #f2f6ff;
|
||||
}
|
||||
@@ -697,3 +642,11 @@ onUnmounted(() => {
|
||||
font-size: 11px;
|
||||
}
|
||||
</style>
|
||||
|
||||
<style>
|
||||
/* 日期选择面板与通知面板同为 body 级浮层,须压在通知面板(3200)之上:
|
||||
Element 弹层只自 2000 起递增,不抬就会被面板挡住,表现为「日期点不动」。 */
|
||||
.bell-date-popper {
|
||||
z-index: 3300 !important;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -88,32 +88,6 @@ export function formatDayLabel(day: string, now: Date = new Date()): string {
|
||||
return `${year}年${month}月${date}日`
|
||||
}
|
||||
|
||||
export interface NotificationDayGroup<T> {
|
||||
day: string
|
||||
label: string
|
||||
items: T[]
|
||||
}
|
||||
|
||||
/** 按年月日分组(组内保持入参顺序,列表本身已按 id 倒序)。 */
|
||||
export function groupNotificationsByDay<T extends { createdAt: string | null }>(
|
||||
items: T[],
|
||||
now: Date = new Date(),
|
||||
): NotificationDayGroup<T>[] {
|
||||
const groups: NotificationDayGroup<T>[] = []
|
||||
const indexByDay = new Map<string, NotificationDayGroup<T>>()
|
||||
for (const item of items ?? []) {
|
||||
const day = notificationDayKey(item.createdAt)
|
||||
let group = indexByDay.get(day)
|
||||
if (!group) {
|
||||
group = { day, label: formatDayLabel(day, now), items: [] }
|
||||
indexByDay.set(day, group)
|
||||
groups.push(group)
|
||||
}
|
||||
group.items.push(item)
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
/** 通知时间展示:今天只显示 HH:mm;昨天显示「昨天 HH:mm」;更早显示 MM-DD HH:mm。 */
|
||||
export function formatNotificationTime(
|
||||
value: string | null | undefined,
|
||||
@@ -146,6 +120,28 @@ export function formatNotificationTime(
|
||||
return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${hourMinute}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚合组的稳定键:场景 × 自然日 × 事件主体用户,与后端的分组键逐字对应。
|
||||
* 主体为空(存量未标注那一组)要参与拼键,否则两组不同主体的组会撞成同一个 key,
|
||||
* 展开态就会串台——点开 A 组、展开的却是 B 组。
|
||||
*/
|
||||
export function notificationGroupKey(group: {
|
||||
scene?: string | null
|
||||
day?: string | null
|
||||
subjectUserId?: number | string | null
|
||||
}): string {
|
||||
const subject =
|
||||
group.subjectUserId === null || group.subjectUserId === undefined ? 'none' : String(group.subjectUserId)
|
||||
return `${group.scene ?? ''}|${group.day ?? ''}|${subject}`
|
||||
}
|
||||
|
||||
/** 组行上的计数徽语:折叠前有几条、其中几条没读。只报一个数就会被读成"一共就这些通知"。 */
|
||||
export function formatGroupCounts(rowCount: number | null | undefined, unreadCount: number | null | undefined): string {
|
||||
const total = Number(rowCount ?? 0)
|
||||
const unread = Number(unreadCount ?? 0)
|
||||
return unread > 0 ? `${total} 条 · ${unread} 未读` : `${total} 条`
|
||||
}
|
||||
|
||||
/**
|
||||
* 失败反馈的文案与「同场故障只提示一次」的闸门(四面9分口径 §2 后管「错误静默」)。
|
||||
*
|
||||
|
||||
@@ -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>
|
||||
@@ -2,7 +2,7 @@
|
||||
"note": "readSource 钉子逐文件基线。两把尺子:pins=落在用例体内的读盘,reads=全文读点总数(含模块级夹具与 helper)。都只许减;pins 下降而 reads 没同步下降=把读盘挪出体内,不算改进。由 tests/source-pin-ratchet.test.ts 生成。",
|
||||
"totals": {
|
||||
"files": 244,
|
||||
"cases": 1726,
|
||||
"cases": 1727,
|
||||
"pins": 448,
|
||||
"reads": 639
|
||||
},
|
||||
@@ -303,7 +303,7 @@
|
||||
"reads": 2
|
||||
},
|
||||
"notification-bell.test.ts": {
|
||||
"cases": 6,
|
||||
"cases": 7,
|
||||
"pins": 0,
|
||||
"reads": 0
|
||||
},
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
/**
|
||||
* 首批组件挂载用例之二(四面9分口径 §2 后管「0 组件挂载测试」)。
|
||||
*
|
||||
* 靶子是 NotificationBell.vue 的两处静默 catch(未读数轮询、点通知标已读)。
|
||||
* 靶子是 NotificationBell.vue 的两处静默 catch(未读数轮询、点明细标已读)。
|
||||
* 这里跑真组件:真 pinia 会话、真 `notification-bell-model` 里的提示闸门、真定时器
|
||||
* (用 vi 的假时钟推进 60s 轮询),只把两个出口(api 与 admin-feedback-ui)换成可断言的假件
|
||||
* ⇒ 判的是运行时行为,不是读源码的形状钉子。
|
||||
*
|
||||
* 10-13 聚合改造(场景 × 自然日 × 主体用户)后,面板默认视图拿的是 `fetchNotificationGroups`,
|
||||
* 明细要展开聚合行才由 `fetchNotificationList` 取 ⇒ 点已读那两支都先展开再点明细行;
|
||||
* 顺带钉住「聚合行点击只展开、不替用户标已读」与「红点按组数、组内没读完不许掉」。
|
||||
*
|
||||
* ⚠ 面板是 `<Teleport to="body">`:每支用例都必须 unmount 并清空 body,
|
||||
* 否则上一支留下的那一行 `.bell-item--unread` 会被这一支的 document 查询捡到(实测会串味)。
|
||||
*
|
||||
* 跑法:`npm run test:mount`。
|
||||
* ⚠ 这面还有一支 `npm run test:mount`(vitest,只收 tests/mount/**),
|
||||
* 与 `npm test`(node --test,glob 不递归)互不抓取 ⇒ 改铃铛必须两把都跑,只跑一把就是没验。
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
|
||||
@@ -22,6 +26,7 @@ import { NOTIFICATION_POLL_INTERVAL_MS } from '@/layout/notification-bell-model'
|
||||
const feedback = vi.hoisted(() => ({ showAdminFeedback: vi.fn(), runBusy: vi.fn() }))
|
||||
const api = vi.hoisted(() => ({
|
||||
fetchNotificationSummary: vi.fn(),
|
||||
fetchNotificationGroups: vi.fn(),
|
||||
fetchNotificationList: vi.fn(),
|
||||
markNotificationRead: vi.fn(),
|
||||
markAllNotificationsRead: vi.fn(),
|
||||
@@ -42,6 +47,33 @@ const notification = (over: Record<string, unknown> = {}) => ({
|
||||
...over,
|
||||
})
|
||||
|
||||
/** 聚合行:一条组 = 场景 × 自然日 × 主体用户,rowCount 是折叠前的明细条数。 */
|
||||
const group = (over: Record<string, unknown> = {}) => ({
|
||||
latestId: 7,
|
||||
scene: 'service_down',
|
||||
category: 'system_error',
|
||||
day: '2026-09-13',
|
||||
subjectUserId: 1160,
|
||||
rowCount: 1,
|
||||
unreadCount: 1,
|
||||
level: 'error',
|
||||
title: '品牌检测服务挂了',
|
||||
content: '上游 503',
|
||||
createdAt: new Date().toISOString(),
|
||||
...over,
|
||||
})
|
||||
|
||||
const groupPage = (rows: unknown[], over: Record<string, unknown> = {}) => ({
|
||||
groups: rows,
|
||||
total: rows.length,
|
||||
rowCount: rows.length,
|
||||
page: 1,
|
||||
pageSize: 6,
|
||||
unreadGroupCount: rows.filter((g) => (g as { unreadCount: number }).unreadCount > 0).length,
|
||||
unreadCount: rows.reduce((sum, g) => sum + (g as { unreadCount: number }).unreadCount, 0),
|
||||
...over,
|
||||
})
|
||||
|
||||
describe('NotificationBell:两处失败必须可见', () => {
|
||||
let pinia: Pinia
|
||||
let wrapper: VueWrapper | null = null
|
||||
@@ -52,8 +84,16 @@ describe('NotificationBell:两处失败必须可见', () => {
|
||||
}
|
||||
|
||||
/** 只看当前这一棵树里的面板:Teleport 出去的内容挂在 document.body 上。 */
|
||||
function panelRow(): HTMLElement | null {
|
||||
return document.body.querySelector('.bell-item') as HTMLElement | null
|
||||
function panelRow(selector: string): HTMLElement | null {
|
||||
return document.body.querySelector(selector) as HTMLElement | null
|
||||
}
|
||||
|
||||
/** 展开第一个聚合行(聚合行点击只展开,明细行才是能标已读的那一层)。 */
|
||||
async function expandFirstGroup() {
|
||||
const row = panelRow('.bell-group')
|
||||
if (!row) throw new Error('面板 Teleport 到 body 后没渲染出聚合行')
|
||||
row.click()
|
||||
await flushPromises()
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -61,8 +101,9 @@ describe('NotificationBell:两处失败必须可见', () => {
|
||||
pinia = createPinia()
|
||||
setActivePinia(pinia)
|
||||
useAdminSessionStore().user = { id: 9, username: 'root', role: 'super_admin' }
|
||||
api.fetchNotificationList.mockResolvedValue({ items: [], total: 0, page: 1, pageSize: 10, unreadCount: 0 })
|
||||
api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 0, latestId: 0 })
|
||||
api.fetchNotificationGroups.mockResolvedValue(groupPage([]))
|
||||
api.fetchNotificationList.mockResolvedValue({ items: [], total: 0, page: 1, pageSize: 50, unreadCount: 0 })
|
||||
api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 0, unreadGroupCount: 0, latestId: 0 })
|
||||
api.markNotificationRead.mockResolvedValue(true)
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
})
|
||||
@@ -95,7 +136,7 @@ describe('NotificationBell:两处失败必须可见', () => {
|
||||
await vi.advanceTimersByTimeAsync(NOTIFICATION_POLL_INTERVAL_MS * 3)
|
||||
expect(feedback.showAdminFeedback).toHaveBeenCalledTimes(1)
|
||||
|
||||
api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 2, latestId: 11 })
|
||||
api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 2, unreadGroupCount: 1, latestId: 11 })
|
||||
await vi.advanceTimersByTimeAsync(NOTIFICATION_POLL_INTERVAL_MS)
|
||||
api.fetchNotificationSummary.mockRejectedValue(new Error('503'))
|
||||
await vi.advanceTimersByTimeAsync(NOTIFICATION_POLL_INTERVAL_MS)
|
||||
@@ -105,11 +146,12 @@ describe('NotificationBell:两处失败必须可见', () => {
|
||||
})
|
||||
|
||||
it('点通知标已读失败:提示带原因,且这条不许被前端冒充成"已读"', async () => {
|
||||
api.fetchNotificationGroups.mockResolvedValue(groupPage([group({ latestId: 21 })]))
|
||||
api.fetchNotificationList.mockResolvedValue({
|
||||
items: [notification({ id: 21 })],
|
||||
total: 1,
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
pageSize: 50,
|
||||
unreadCount: 1,
|
||||
})
|
||||
api.markNotificationRead.mockRejectedValue(new Error('403 Forbidden'))
|
||||
@@ -119,23 +161,28 @@ describe('NotificationBell:两处失败必须可见', () => {
|
||||
await bell.find('button.bell-trigger').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
const row = panelRow()
|
||||
if (!row) throw new Error('面板 Teleport 到 body 后没渲染出那一行通知')
|
||||
// 展开这一步本身不许标已读:口径是"聚合行只展开,已读进明细逐条点"
|
||||
expect(api.markNotificationRead).not.toHaveBeenCalled()
|
||||
await expandFirstGroup()
|
||||
|
||||
const row = panelRow('.bell-item--detail')
|
||||
if (!row) throw new Error('展开聚合行后没渲染出明细行')
|
||||
row.click()
|
||||
await flushPromises()
|
||||
|
||||
expect(feedback.showAdminFeedback).toHaveBeenCalledWith('这条通知没能标记为已读:403 Forbidden', 'error')
|
||||
// 前端不许替后端宣布已读:行仍是未读态、徽标还在
|
||||
expect(panelRow()?.className).toContain('bell-item--unread')
|
||||
expect(panelRow('.bell-item--detail')?.className).toContain('bell-item--unread')
|
||||
expect(bell.find('.bell-badge').exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('反向钉:标已读成功时一句提示都不许有,行也要真的转为已读', async () => {
|
||||
api.fetchNotificationGroups.mockResolvedValue(groupPage([group({ latestId: 22 })]))
|
||||
api.fetchNotificationList.mockResolvedValue({
|
||||
items: [notification({ id: 22 })],
|
||||
total: 1,
|
||||
page: 1,
|
||||
pageSize: 10,
|
||||
pageSize: 50,
|
||||
unreadCount: 1,
|
||||
})
|
||||
api.markNotificationRead.mockResolvedValue(true)
|
||||
@@ -144,14 +191,73 @@ describe('NotificationBell:两处失败必须可见', () => {
|
||||
await flushPromises()
|
||||
await bell.find('button.bell-trigger').trigger('click')
|
||||
await flushPromises()
|
||||
await expandFirstGroup()
|
||||
|
||||
const row = panelRow()
|
||||
if (!row) throw new Error('面板 Teleport 到 body 后没渲染出那一行通知')
|
||||
const row = panelRow('.bell-item--detail')
|
||||
if (!row) throw new Error('展开聚合行后没渲染出明细行')
|
||||
row.click()
|
||||
await flushPromises()
|
||||
|
||||
expect(feedback.showAdminFeedback).not.toHaveBeenCalled()
|
||||
expect(panelRow()?.className).not.toContain('bell-item--unread')
|
||||
expect(panelRow('.bell-item--detail')?.className).not.toContain('bell-item--unread')
|
||||
expect(bell.find('.bell-badge').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('组内还有未读时红点不许掉,读完最后一条才掉', async () => {
|
||||
api.fetchNotificationGroups.mockResolvedValue(
|
||||
groupPage([group({ latestId: 32, rowCount: 2, unreadCount: 2 })], { unreadCount: 2, unreadGroupCount: 1 }),
|
||||
)
|
||||
api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 2, unreadGroupCount: 1, latestId: 32 })
|
||||
api.fetchNotificationList.mockResolvedValue({
|
||||
items: [notification({ id: 31 }), notification({ id: 32 })],
|
||||
total: 2,
|
||||
page: 1,
|
||||
pageSize: 50,
|
||||
unreadCount: 2,
|
||||
})
|
||||
|
||||
const bell = mountBell()
|
||||
await flushPromises()
|
||||
await bell.find('button.bell-trigger').trigger('click')
|
||||
await flushPromises()
|
||||
await expandFirstGroup()
|
||||
|
||||
panelRow('.bell-item--detail.bell-item--unread')!.click()
|
||||
await flushPromises()
|
||||
expect(api.markNotificationRead).toHaveBeenCalledTimes(1)
|
||||
expect(bell.find('.bell-badge').exists()).toBe(true, '这一组还剩一条没读,红点不许先掉')
|
||||
|
||||
panelRow('.bell-item--detail.bell-item--unread')!.click()
|
||||
await flushPromises()
|
||||
expect(api.markNotificationRead).toHaveBeenCalledTimes(2)
|
||||
expect(bell.find('.bell-badge').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it('下钻带上主体用户:同场景同一天是好几组,少一维就把别的主体的行混进来', async () => {
|
||||
api.fetchNotificationGroups.mockResolvedValue(
|
||||
groupPage([group({ subjectUserId: 1196, latestId: 41 }), group({ subjectUserId: 1160, latestId: 42 })]),
|
||||
)
|
||||
api.fetchNotificationList.mockResolvedValue({
|
||||
items: [notification({ id: 41 })],
|
||||
total: 1,
|
||||
page: 1,
|
||||
pageSize: 50,
|
||||
unreadCount: 1,
|
||||
})
|
||||
|
||||
const bell = mountBell()
|
||||
await flushPromises()
|
||||
await bell.find('button.bell-trigger').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(document.body.querySelectorAll('.bell-group')).toHaveLength(2)
|
||||
await expandFirstGroup()
|
||||
|
||||
expect(api.fetchNotificationList.mock.calls[0][0]).toMatchObject({
|
||||
scene: 'service_down',
|
||||
day: '2026-09-13',
|
||||
subjectUserId: 1196,
|
||||
})
|
||||
expect(api.fetchNotificationList.mock.calls[0][0].subjectUnlabelled).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
*
|
||||
* 前 4 支是**行为断言**:直接 import `src/layout/notification-bell-model.ts` 跑真函数,
|
||||
* 提示出口是注入进去的假 sink——不挂载组件也测得到运行时行为。
|
||||
* 第 5 支是**源码钉子**(readSource):钉的是「组件那两处 catch 接的是这条出口」这个形状,
|
||||
* 第 5 支是**源码钉子**(readSource):钉的是「面板层那两处 catch 接的是这条出口」这个形状,
|
||||
* (10-13 起 catch 在 notification-bell-panel.ts,同支还钉住组件确实 import 了这层。)
|
||||
* 不是运行时行为;运行时那一面由 `tests/mount/notification-bell-failure.mount.test.ts`
|
||||
* (`npm run test:mount`,vitest + @vue/test-utils + jsdom)覆盖。
|
||||
* 两者都要:钉子跑在零依赖的 `node --test` 里,挂载例要装 node_modules。
|
||||
@@ -21,6 +22,7 @@ import {
|
||||
} from '../src/layout/notification-bell-model.ts'
|
||||
|
||||
const BELL = 'src/components/NotificationBell.vue'
|
||||
const PANEL = 'src/layout/notification-bell-panel.ts'
|
||||
|
||||
/** 钉子判据:两处失败路径的 console.warn 之后 160 字符窗口里必须有用户可见出口。 */
|
||||
function bellFailureExits(src: string): string[] {
|
||||
@@ -84,21 +86,23 @@ test('闸门不会把成功当失败:reportSuccess 之后再报错误仍是可
|
||||
})
|
||||
|
||||
test('源码钉子(非行为断言):两处 catch 都接到 admin-feedback-ui 的统一出口', () => {
|
||||
const src = readSource(BELL)
|
||||
assert.ok(src.length > 0, '取样集非空自检:NotificationBell.vue 读到了')
|
||||
// 10-13 两级改造后这两处 catch 长在面板模块里(SFC 顶到可读棘轮的 800 行上限,状态机整块拆出);
|
||||
// 钉子跟着搬;「组件在用这一层」由 tests/mount 那支挂载用例在运行时证(这里再加一枚 readSource 就是往只许减的台账里添读点)。
|
||||
const src = readSource(PANEL)
|
||||
assert.ok(src.length > 0, '取样集非空自检:notification-bell-panel.ts 读到了')
|
||||
assert.ok(src.includes(`import { showAdminFeedback } from '@/components/admin-feedback-ui'`),
|
||||
'铃铛没接 admin-feedback-ui 的统一出口')
|
||||
assert.ok(src.includes('createSummaryFailureAlerter'), '轮询闸门没在组件里实例化')
|
||||
assert.ok(src.includes('createSummaryFailureAlerter'), '轮询闸门没在面板层实例化')
|
||||
assert.deepEqual(bellFailureExits(src), [], '两处静默 catch 里有一处又退回只 console 了')
|
||||
})
|
||||
|
||||
test('判据自证(内存变异):摘掉提示出口,上面那枚钉子必须变红', () => {
|
||||
const src = readSource(BELL)
|
||||
const src = readSource(PANEL)
|
||||
assert.deepEqual(bellFailureExits(src), [], '基线就该是干净的,否则这条自证测不出任何东西')
|
||||
|
||||
const variants: Array<[string, string]> = [
|
||||
['摘掉轮询提示', " summaryFailures.reportFailure(error)\n"],
|
||||
['摘掉标记已读提示', " showAdminFeedback(markReadFailureMessage(error), 'error')\n"],
|
||||
['摘掉轮询提示', " summaryFailures.reportFailure(error)\n"],
|
||||
['摘掉标记已读提示', " showAdminFeedback(markReadFailureMessage(error), 'error')\n"],
|
||||
]
|
||||
for (const [label, dropped] of variants) {
|
||||
assert.equal(src.split(dropped).length - 1, 1, `「${label}」的锚串在源码里不唯一,变异不作数`)
|
||||
|
||||
@@ -3,7 +3,9 @@ import assert from 'node:assert/strict'
|
||||
import {
|
||||
formatNotificationTime,
|
||||
formatUnreadBadge,
|
||||
groupNotificationsByDay,
|
||||
formatDayLabel,
|
||||
formatGroupCounts,
|
||||
notificationGroupKey,
|
||||
hasNewNotification,
|
||||
readLastNotifiedId,
|
||||
writeLastNotifiedId,
|
||||
@@ -82,48 +84,29 @@ test('test_时间展示:今天/昨天/更早', () => {
|
||||
assert.equal(formatNotificationTime('not-a-date', now), '')
|
||||
})
|
||||
|
||||
test('test_按年月日分组:今天/昨天/更早,组内保持原顺序', () => {
|
||||
test('test_日期组头文案:今天/昨天/更早/未知时间', () => {
|
||||
const now = new Date(2026, 8, 13, 15, 30)
|
||||
const items = [
|
||||
{ id: 4, createdAt: new Date(2026, 8, 13, 15, 0).toISOString() },
|
||||
{ id: 3, createdAt: new Date(2026, 8, 13, 9, 0).toISOString() },
|
||||
{ id: 2, createdAt: new Date(2026, 8, 12, 23, 0).toISOString() },
|
||||
{ id: 1, createdAt: new Date(2026, 8, 1, 8, 0).toISOString() },
|
||||
]
|
||||
|
||||
const groups = groupNotificationsByDay(items, now)
|
||||
|
||||
assert.equal(groups.length, 3)
|
||||
assert.deepEqual(
|
||||
groups.map((group) => [group.day, group.label]),
|
||||
[
|
||||
['2026-09-13', '今天'],
|
||||
['2026-09-12', '昨天'],
|
||||
['2026-09-01', '2026年9月1日'],
|
||||
],
|
||||
)
|
||||
assert.deepEqual(
|
||||
groups[0].items.map((item) => item.id),
|
||||
[4, 3],
|
||||
'同一天的多条合为一组且保持倒序',
|
||||
)
|
||||
assert.equal(formatDayLabel('2026-09-13', now), '今天')
|
||||
assert.equal(formatDayLabel('2026-09-12', now), '昨天')
|
||||
assert.equal(formatDayLabel('2026-09-01', now), '2026年9月1日')
|
||||
assert.equal(formatDayLabel('', now), '未知时间')
|
||||
})
|
||||
|
||||
test('test_按年月日分组:时间缺失/非法归入未知时间组', () => {
|
||||
const now = new Date(2026, 8, 13, 15, 30)
|
||||
const groups = groupNotificationsByDay(
|
||||
[
|
||||
{ id: 2, createdAt: null },
|
||||
{ id: 1, createdAt: 'not-a-date' },
|
||||
],
|
||||
now,
|
||||
)
|
||||
|
||||
assert.equal(groups.length, 1)
|
||||
assert.equal(groups[0].day, '')
|
||||
assert.equal(groups[0].label, '未知时间')
|
||||
assert.deepEqual(
|
||||
groups[0].items.map((item) => item.id),
|
||||
[2, 1],
|
||||
)
|
||||
test('test_聚合组键:三维各自都能把两组分开', () => {
|
||||
const base = { scene: 'task_partial', day: '2026-09-13', subjectUserId: 1160 }
|
||||
assert.notEqual(notificationGroupKey({ ...base, subjectUserId: 1196 }), notificationGroupKey(base),
|
||||
'同场景同天、不同主体用户必须是两组(这是定下来的粒度)')
|
||||
assert.notEqual(notificationGroupKey({ ...base, scene: 'task_failed' }), notificationGroupKey(base),
|
||||
'同一天不同场景必须是两组')
|
||||
assert.notEqual(notificationGroupKey({ ...base, day: '2026-09-12' }), notificationGroupKey(base),
|
||||
'同场景同主体、不同自然日必须是两组')
|
||||
assert.equal(notificationGroupKey({ ...base, subjectUserId: null }),
|
||||
notificationGroupKey({ ...base, subjectUserId: undefined }),
|
||||
'null 与 undefined 都是"未标注主体",必须落进同一组')
|
||||
})
|
||||
|
||||
test('test_组行计数文案:读完不再挂 0 未读', () => {
|
||||
assert.equal(formatGroupCounts(12, 3), '12 条 · 3 未读')
|
||||
assert.equal(formatGroupCounts(12, 0), '12 条')
|
||||
assert.equal(formatGroupCounts(1, null), '1 条')
|
||||
})
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* 面板层纯函数的行为用例(10-13 从 NotificationBell.vue 拆出这一层的唯一目的就在这)。
|
||||
*
|
||||
* 组件那一层在本面只能挂载跑(vitest+jsdom),而"红点按组数、组内没读完不许掉、
|
||||
* 下钻三维、换页清展开态"这几条口径其实都是纯计算——放这一层就能逐条喂数据判它,
|
||||
* 不必退化成 readSource 钉源码字形(那种钉子在这仓已被记进只许减的台账)。
|
||||
*
|
||||
* 跑法:`npx vitest run --config vitest.config.ts`(`npm test` 那把 node --test 零依赖,
|
||||
* 解析不了 @ 别名与 vue,所以这一支走 vitest 的 tests/pure/**)。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
PANEL_DETAIL_LIMIT,
|
||||
applyGroupsPage,
|
||||
applyMarkReadToCounts,
|
||||
detailQueryFor,
|
||||
itemLevel,
|
||||
latestIdWorthRecording,
|
||||
normalizedDayRange,
|
||||
startsNewDay,
|
||||
} from '@/layout/notification-bell-panel'
|
||||
|
||||
const group = (over: Record<string, unknown> = {}) => ({
|
||||
latestId: 7,
|
||||
scene: 'service_down',
|
||||
category: 'system_error',
|
||||
day: '2026-09-13',
|
||||
subjectUserId: 1160,
|
||||
rowCount: 1,
|
||||
unreadCount: 1,
|
||||
level: 'error',
|
||||
title: '品牌检测服务挂了',
|
||||
content: '上游 503',
|
||||
createdAt: '2026-09-13T09:00:00.000Z',
|
||||
...over,
|
||||
})
|
||||
|
||||
describe('通知面板层纯函数', () => {
|
||||
it('起止日期倒挂自动交换;单边留空不下发该条件', () => {
|
||||
expect(normalizedDayRange('2026-09-14', '2026-09-13')).toEqual({
|
||||
startDate: '2026-09-13',
|
||||
endDate: '2026-09-14',
|
||||
})
|
||||
expect(normalizedDayRange('', '')).toEqual({ startDate: undefined, endDate: undefined })
|
||||
expect(normalizedDayRange('2026-09-13', '')).toEqual({ startDate: '2026-09-13', endDate: undefined })
|
||||
})
|
||||
|
||||
it('下钻条件带满三维,主体为空改走 IS NULL 旗标', () => {
|
||||
const labelled = detailQueryFor(group({ subjectUserId: 1196 }) as never)
|
||||
expect(labelled.scene).toBe('service_down')
|
||||
expect(labelled.day).toBe('2026-09-13')
|
||||
expect(labelled.subjectUserId).toBe(1196)
|
||||
expect(labelled.subjectUnlabelled).toBe(false)
|
||||
expect(labelled.pageSize).toBe(PANEL_DETAIL_LIMIT)
|
||||
|
||||
// 改动上线前的存量行没有主体用户:按 null 下发等于把条件丢掉,必须换成旗标
|
||||
const unlabelled = detailQueryFor(group({ subjectUserId: null }) as never)
|
||||
expect(unlabelled.subjectUserId).toBeNull()
|
||||
expect(unlabelled.subjectUnlabelled).toBe(true)
|
||||
})
|
||||
|
||||
it('组内还有未读时组数不许减,读完最后一条才减', () => {
|
||||
const groups = [group({ unreadCount: 2 }), group({ subjectUserId: 1196, unreadCount: 1 })]
|
||||
const key = 'service_down|2026-09-13|1160'
|
||||
|
||||
const first = applyMarkReadToCounts(groups, key, 3, 2)
|
||||
expect(groups[0].unreadCount).toBe(1, '第一条读完,组内还剩一条')
|
||||
expect(first.unreadCount).toBe(2, '明细条数照实减')
|
||||
expect(first.unreadGroupCount).toBe(2, '这一组还没读完,未读组数不许动')
|
||||
|
||||
const last = applyMarkReadToCounts(groups, key, 2, 2)
|
||||
expect(groups[0].unreadCount).toBe(0)
|
||||
expect(last.unreadGroupCount).toBe(1, '组内清零,红点(按组数)才掉这一格')
|
||||
})
|
||||
|
||||
it('没展开任何一组时只减明细数,不减组数', () => {
|
||||
const groups = [group({ unreadCount: 1 })]
|
||||
const next = applyMarkReadToCounts(groups, '', 1, 1)
|
||||
expect(groups[0].unreadCount).toBe(1, '找不到归属组就不该改组内计数')
|
||||
expect(next.unreadCount).toBe(0)
|
||||
expect(next.unreadGroupCount).toBe(1)
|
||||
})
|
||||
|
||||
it('两个计数不许越界成负数', () => {
|
||||
const next = applyMarkReadToCounts([], 'nothing-expanded', 0, 0)
|
||||
expect(next).toEqual({ unreadCount: 0, unreadGroupCount: 0 })
|
||||
})
|
||||
|
||||
it('聚合页缺字段时回落:组数按实收、明细条数按清单长度', () => {
|
||||
const applied = applyGroupsPage(
|
||||
{ groups: [group(), group({ subjectUserId: 1196 })] } as never,
|
||||
{ unreadCount: 5, unreadGroupCount: 3 },
|
||||
)
|
||||
expect(applied.total).toBe(2)
|
||||
expect(applied.rowCount).toBe(2)
|
||||
expect(applied.unreadCount).toBe(5, '后端没给这一格就保留上一次读数,别凭空归零')
|
||||
expect(applied.unreadGroupCount).toBe(3)
|
||||
|
||||
const empty = applyGroupsPage({ groups: null } as never, { unreadCount: 1, unreadGroupCount: 1 })
|
||||
expect(empty.groups).toEqual([])
|
||||
expect(empty.total).toBe(0)
|
||||
})
|
||||
|
||||
it('日期头只在换天时出现:同一天多组(多用户/多场景)不重复挂头', () => {
|
||||
const list = [group(), group({ subjectUserId: 1196 }), group({ day: '2026-09-12' })]
|
||||
expect(startsNewDay(list, 0)).toBe(true)
|
||||
expect(startsNewDay(list, 1)).toBe(false)
|
||||
expect(startsNewDay(list, 2)).toBe(true)
|
||||
})
|
||||
|
||||
it('级别兜底:非法/缺失都按 warning,组行与明细行不会配色分家', () => {
|
||||
expect(itemLevel({ level: 'error' })).toBe('error')
|
||||
expect(itemLevel({ level: 'info' })).toBe('info')
|
||||
expect(itemLevel({ level: 'fatal' })).toBe('warning')
|
||||
expect(itemLevel({ level: '' })).toBe('warning')
|
||||
})
|
||||
|
||||
it('已提醒水位只在首页真有数据时推进,取不到 id 就什么也不写', () => {
|
||||
expect(latestIdWorthRecording([])).toBe(0)
|
||||
expect(latestIdWorthRecording([group({ latestId: 0 })])).toBe(0)
|
||||
expect(latestIdWorthRecording([group({ latestId: 'x' })])).toBe(0)
|
||||
expect(latestIdWorthRecording([group({ latestId: 88 })])).toBe(88)
|
||||
})
|
||||
})
|
||||
@@ -8,7 +8,8 @@ import vue from '@vitejs/plugin-vue'
|
||||
* 与 vite.config.ts 分家:那份管生产构建,这里只服务 `npm run test:mount`,
|
||||
* 动它不会改变 `npm run build` 的产物(也不在 tsconfig 的 include 里,vue-tsc 不检它)。
|
||||
*
|
||||
* include 只收 `tests/mount/**`:本仓其余判据走 `node --test tests/*.test.ts`,
|
||||
* include 收 `tests/mount/**`(组件挂载)与 `tests/pure/**`(面板层纯函数:那层要解析 @ 别名
|
||||
* 与 vue/element-plus,进不了零依赖的 `node --test`):本仓其余判据走 `node --test tests/*.test.ts`,
|
||||
* 那支 glob 不递归 ⇒ 两套 runner 不会互相抓到对方的文件。
|
||||
*/
|
||||
export default defineConfig({
|
||||
@@ -20,6 +21,6 @@ export default defineConfig({
|
||||
},
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
include: ['tests/mount/**/*.test.ts'],
|
||||
include: ['tests/mount/**/*.test.ts', 'tests/pure/**/*.test.ts'],
|
||||
},
|
||||
})
|
||||
|
||||
@@ -5,7 +5,7 @@ package com.nanri.aiimage.common.api;
|
||||
* {@code defaultValue} 里 15/20/50/1000 四种并存,31 处魔法数)。
|
||||
*
|
||||
* <p><b>这里没有"全局统一默认页容量"这一说,而且是故意的。</b>
|
||||
* 实测 49 处数字型 {@code defaultValue}(21 处页码 + 28 处条数)分属不同的真实用途:
|
||||
* 实测 53 处数字型 {@code defaultValue}(23 处页码 + 30 处条数)分属不同的真实用途:
|
||||
* 用户端列表、超管台、任务历史、扫描上限、导出取全量——把它们拍成一个值是<b>改行为</b>,
|
||||
* 不是清理。本类只做一件事:让每个数字有一个说明它<i>为什么是这个数</i>的名字,
|
||||
* 并让"同一个用途冒出第二个默认值"变成判据红({@code PageDefaultsLedgerTest})。
|
||||
@@ -21,9 +21,9 @@ public final class PageDefaults {
|
||||
private PageDefaults() {
|
||||
}
|
||||
|
||||
// ---- 页码:21 处全是 1,这一族本来就是单一口径 ----
|
||||
// ---- 页码:23 处全是 1,这一族本来就是单一口径 ----
|
||||
|
||||
/** 起始页码。全树 21 处分页入口一致取 1(不是 0);改这个数等于把所有列表第一页翻空。 */
|
||||
/** 起始页码。全树 23 处分页入口一致取 1(不是 0);改这个数等于把所有列表第一页翻空。 */
|
||||
public static final String FIRST_PAGE = "1";
|
||||
|
||||
/** {@link #FIRST_PAGE} 的数字镜像。 */
|
||||
|
||||
+39
-4
@@ -4,6 +4,7 @@ import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.notification.model.dto.NotificationPageQuery;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationGroupPageVo;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationPageVo;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationSummaryVo;
|
||||
import com.nanri.aiimage.modules.notification.service.NotificationService;
|
||||
@@ -43,11 +44,34 @@ public class AdminNotificationController {
|
||||
return ApiResponse.success(notificationService.summary(userId, NotificationService.AUDIENCE_ADMIN));
|
||||
}
|
||||
|
||||
@GetMapping("/groups")
|
||||
@Operation(summary = "通知聚合列表(铃铛默认视图)",
|
||||
description = "按「场景 × 自然日 × 事件主体用户」折叠,分页按组切。"
|
||||
+ "返回 total=组数、rowCount=同条件下折叠前的明细条数,两个数都要显示,"
|
||||
+ "否则「共 12 条」会被读成只有 12 条通知。筛选条件与单条列表共用一套实现。")
|
||||
public ApiResponse<NotificationGroupPageVo> groups(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "页码(按组)") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@Parameter(description = "每页组数") @RequestParam(defaultValue = PageDefaults.ADMIN_LIST_PAGE_SIZE) Long pageSize,
|
||||
@Parameter(description = "只看未读") @RequestParam(required = false, defaultValue = "false") Boolean onlyUnread,
|
||||
@Parameter(description = "关键字(标题/内容)") @RequestParam(required = false) String keyword,
|
||||
@Parameter(description = "类型大类:system_error/task_error/config_error/system_notice")
|
||||
@RequestParam(required = false) String category,
|
||||
@Parameter(description = "起始日期(yyyy-MM-dd,含)")
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
|
||||
@Parameter(description = "结束日期(yyyy-MM-dd,含)")
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
|
||||
Long userId = currentAdminId(request);
|
||||
return ApiResponse.success(notificationService.groups(userId, NotificationService.AUDIENCE_ADMIN,
|
||||
NotificationPageQuery.of(page, pageSize, onlyUnread, keyword, category, startDate, endDate)));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "通知分页列表",
|
||||
description = "onlyUnread=true 时只返回未读;keyword 模糊匹配标题/内容;"
|
||||
+ "category 按类型大类筛选(system_error/task_error/config_error/system_notice);"
|
||||
+ "startDate/endDate 为年月日闭区间。")
|
||||
+ "startDate/endDate 为年月日闭区间;"
|
||||
+ "scene/day/subjectUserId 三个条件用于展开聚合组、取该组内的明细。")
|
||||
public ApiResponse<NotificationPageVo> page(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@@ -59,10 +83,21 @@ public class AdminNotificationController {
|
||||
@Parameter(description = "起始日期(yyyy-MM-dd,含)")
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
|
||||
@Parameter(description = "结束日期(yyyy-MM-dd,含)")
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
|
||||
@Parameter(description = "聚合组展开:场景") @RequestParam(required = false) String scene,
|
||||
@Parameter(description = "聚合组展开:自然日(yyyy-MM-dd)")
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate day,
|
||||
@Parameter(description = "聚合组展开:事件主体用户 id") @RequestParam(required = false) Long subjectUserId,
|
||||
@Parameter(description = "聚合组展开:取「未区分用户」那一组(subject_user_id 为空的存量行)")
|
||||
@RequestParam(required = false, defaultValue = "false") Boolean subjectUnlabelled) {
|
||||
Long userId = currentAdminId(request);
|
||||
return ApiResponse.success(notificationService.page(userId, NotificationService.AUDIENCE_ADMIN,
|
||||
NotificationPageQuery.of(page, pageSize, onlyUnread, keyword, category, startDate, endDate)));
|
||||
NotificationPageQuery query = NotificationPageQuery.of(page, pageSize, onlyUnread, keyword, category,
|
||||
startDate, endDate);
|
||||
query.setScene(scene);
|
||||
query.setDay(day);
|
||||
query.setSubjectUserId(subjectUserId);
|
||||
query.setSubjectUnlabelled(subjectUnlabelled);
|
||||
return ApiResponse.success(notificationService.page(userId, NotificationService.AUDIENCE_ADMIN, query));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/read")
|
||||
|
||||
+32
-4
@@ -4,6 +4,7 @@ import com.nanri.aiimage.common.api.ApiResponse;
|
||||
import com.nanri.aiimage.common.api.PageDefaults;
|
||||
import com.nanri.aiimage.common.security.AdminAuthSupport;
|
||||
import com.nanri.aiimage.modules.notification.model.dto.NotificationPageQuery;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationGroupPageVo;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationPageVo;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationSummaryVo;
|
||||
import com.nanri.aiimage.modules.notification.service.NotificationService;
|
||||
@@ -43,11 +44,32 @@ public class NotificationController {
|
||||
return ApiResponse.success(notificationService.summary(userId, NotificationService.AUDIENCE_USER));
|
||||
}
|
||||
|
||||
@GetMapping("/groups")
|
||||
@Operation(summary = "通知聚合列表(铃铛默认视图)",
|
||||
description = "按「场景 × 自然日」折叠(桌面端的主体用户就是本人,分组键里的用户列恒等于自己)。"
|
||||
+ "total=组数、rowCount=折叠前的明细条数,两个数都要显示。")
|
||||
public ApiResponse<NotificationGroupPageVo> groups(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "页码(按组)") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@Parameter(description = "每页组数") @RequestParam(defaultValue = PageDefaults.ADMIN_LIST_PAGE_SIZE) Long pageSize,
|
||||
@Parameter(description = "只看未读") @RequestParam(required = false, defaultValue = "false") Boolean onlyUnread,
|
||||
@Parameter(description = "关键字(标题/内容)") @RequestParam(required = false) String keyword,
|
||||
@Parameter(description = "类型大类:system_error/task_error/config_error/system_notice")
|
||||
@RequestParam(required = false) String category,
|
||||
@Parameter(description = "起始日期(yyyy-MM-dd,含)")
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
|
||||
@Parameter(description = "结束日期(yyyy-MM-dd,含)")
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
|
||||
Long userId = currentUserId(request);
|
||||
return ApiResponse.success(notificationService.groups(userId, NotificationService.AUDIENCE_USER,
|
||||
NotificationPageQuery.of(page, pageSize, onlyUnread, keyword, category, startDate, endDate)));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@Operation(summary = "通知分页列表",
|
||||
description = "onlyUnread=true 时只返回未读;keyword 模糊匹配标题/内容;"
|
||||
+ "category 按类型大类筛选(system_error/task_error/config_error/system_notice);"
|
||||
+ "startDate/endDate 为年月日闭区间。")
|
||||
+ "startDate/endDate 为年月日闭区间;scene/day 用于展开聚合组、取该组内的明细。")
|
||||
public ApiResponse<NotificationPageVo> page(
|
||||
HttpServletRequest request,
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
|
||||
@@ -59,10 +81,16 @@ public class NotificationController {
|
||||
@Parameter(description = "起始日期(yyyy-MM-dd,含)")
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
|
||||
@Parameter(description = "结束日期(yyyy-MM-dd,含)")
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
|
||||
@Parameter(description = "聚合组展开:场景") @RequestParam(required = false) String scene,
|
||||
@Parameter(description = "聚合组展开:自然日(yyyy-MM-dd)")
|
||||
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate day) {
|
||||
Long userId = currentUserId(request);
|
||||
return ApiResponse.success(notificationService.page(userId, NotificationService.AUDIENCE_USER,
|
||||
NotificationPageQuery.of(page, pageSize, onlyUnread, keyword, category, startDate, endDate)));
|
||||
NotificationPageQuery query = NotificationPageQuery.of(page, pageSize, onlyUnread, keyword, category,
|
||||
startDate, endDate);
|
||||
query.setScene(scene);
|
||||
query.setDay(day);
|
||||
return ApiResponse.success(notificationService.page(userId, NotificationService.AUDIENCE_USER, query));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/read")
|
||||
|
||||
+6
@@ -19,6 +19,12 @@ public class NotificationPageQuery {
|
||||
private String category;
|
||||
private LocalDate startDate;
|
||||
private LocalDate endDate;
|
||||
/** 聚合组展开:只取该组内的明细,三个条件成对出现(空表示不限制)。 */
|
||||
private String scene;
|
||||
private LocalDate day;
|
||||
private Long subjectUserId;
|
||||
/** true 表示"按 subjectUserId IS NULL 过滤"(未区分用户那一组),与 subjectUserId 互斥。 */
|
||||
private Boolean subjectUnlabelled;
|
||||
|
||||
public static NotificationPageQuery of(Long page, Long pageSize, Boolean onlyUnread,
|
||||
String keyword, String category,
|
||||
|
||||
+2
@@ -14,6 +14,8 @@ public class UserNotificationEntity {
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
private Long userId;
|
||||
/** 事件主体用户:管理员行=这件事关于谁,桌面端行=本人;null=存量未标注或主体不唯一。 */
|
||||
private Long subjectUserId;
|
||||
private String audience;
|
||||
private String scene;
|
||||
private String level;
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.nanri.aiimage.modules.notification.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 通知聚合分页结果。{@code total} 是**组数**(分页按组切),
|
||||
* {@code rowCount} 是这些筛选条件下的明细条数——两个数必须同屏,
|
||||
* 否则「共 12 条」会被读成"只有 12 条通知",而那是 12 组、展开是 217 条。
|
||||
*/
|
||||
@Data
|
||||
public class NotificationGroupPageVo {
|
||||
|
||||
private List<NotificationGroupVo> groups;
|
||||
/** 组数(分页分母)。 */
|
||||
private Long total;
|
||||
/** 明细条数(同一批筛选条件下折叠前的行数)。 */
|
||||
private Long rowCount;
|
||||
private Long page;
|
||||
private Long pageSize;
|
||||
/** 有未读的组数(新前端红点用它)。 */
|
||||
private Long unreadGroupCount;
|
||||
/** 未读明细条数(与单条列表口径一致,老客户端读的就是这个数)。 */
|
||||
private Long unreadCount;
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.nanri.aiimage.modules.notification.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 通知聚合组:一个「场景 × 自然日 × 主体用户」折成一行。
|
||||
*
|
||||
* <p>分组键里的 subjectUserId 对桌面端恒等于收件人本人;对后台管理员是「这件事关于谁」
|
||||
* (V158 补的列)。存量行没有这一列 ⇒ 全部落进 subjectUserId=null 的那一组,
|
||||
* 界面上显示成「未区分用户」,展开仍能看到明细——这是"不回填"口径的可见代价,
|
||||
* 不拿正则去解析历史文案凑分组键(措辞改过形的行会静默漏归)。
|
||||
*/
|
||||
@Data
|
||||
public class NotificationGroupVo {
|
||||
|
||||
/** 组内最新一条的 id,作为该组在列表里的锚点(展开明细、去重都按它定位)。 */
|
||||
private Long latestId;
|
||||
private String scene;
|
||||
/** 类型大类,沿用单条的归类口径(铃铛筛选按它走)。 */
|
||||
private String category;
|
||||
private LocalDate day;
|
||||
/** 事件主体用户;null=存量未标注或主体不唯一(服务级故障、一把密钥被多账号共用)。 */
|
||||
private Long subjectUserId;
|
||||
/** 组内条数(明细总数)。 */
|
||||
private Long rowCount;
|
||||
/** 组内未读条数;>0 即该组计为一个未读组。 */
|
||||
private Long unreadCount;
|
||||
/** 级别取组内最高(error > warning > info),一组里混进 error 不能被 warning 盖掉。 */
|
||||
private String level;
|
||||
/** 组内最新一条的标题与正文,作为该组的摘要行。 */
|
||||
private String title;
|
||||
private String content;
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
+2
@@ -7,5 +7,7 @@ import lombok.Data;
|
||||
public class NotificationSummaryVo {
|
||||
|
||||
private Long unreadCount;
|
||||
/** 有未读的聚合组数;新前端徽标用它。unreadCount 保持"条数"不变,是为了老客户端。 */
|
||||
private Long unreadGroupCount;
|
||||
private Long latestId;
|
||||
}
|
||||
|
||||
+3
-2
@@ -65,7 +65,7 @@ public class NotificationDispatchService {
|
||||
}
|
||||
String key = dedupeKeyBase + ":" + admin.getId();
|
||||
if (notificationService.pushOrRefresh(admin.getId(), NotificationService.AUDIENCE_ADMIN,
|
||||
scene, level, title, content, key)) {
|
||||
scene, level, title, content, key, subjectUserId)) {
|
||||
pushed++;
|
||||
}
|
||||
}
|
||||
@@ -95,8 +95,9 @@ public class NotificationDispatchService {
|
||||
filtered++;
|
||||
continue;
|
||||
}
|
||||
// 主体不唯一(一把密钥被 N 个账号共用),不挑一个 uid 冒充:留 null,聚合时自成一组
|
||||
if (notificationService.pushOrRefresh(admin.getId(), NotificationService.AUDIENCE_ADMIN,
|
||||
scene, level, title, content, dedupeKeyBase + ":" + admin.getId())) {
|
||||
scene, level, title, content, dedupeKeyBase + ":" + admin.getId(), null)) {
|
||||
pushed++;
|
||||
}
|
||||
}
|
||||
|
||||
+197
-5
@@ -1,10 +1,13 @@
|
||||
package com.nanri.aiimage.modules.notification.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.nanri.aiimage.modules.notification.mapper.UserNotificationMapper;
|
||||
import com.nanri.aiimage.modules.notification.model.dto.NotificationPageQuery;
|
||||
import com.nanri.aiimage.modules.notification.model.entity.UserNotificationEntity;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationGroupPageVo;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationGroupVo;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationItemVo;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationPageVo;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationSummaryVo;
|
||||
@@ -12,8 +15,12 @@ import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -74,11 +81,23 @@ public class NotificationService {
|
||||
private final UserNotificationMapper userNotificationMapper;
|
||||
|
||||
/**
|
||||
* 推送一条通知。dedupeKey 非空且库中已存在同键记录时跳过(返回 false),
|
||||
* 用于「同一异常在时间窗内只提醒一次」;dedupeKey 为空则不去重。
|
||||
* 桌面端行的便捷档:收件人就是事件主体,不必每个调用点重复传一遍。
|
||||
* 管理员行**不能**走这里——那样会把管理员自己的 id 写成主体,聚合时每个管理员
|
||||
* 各成一组、且永远看不到"这件事关于谁"。
|
||||
*/
|
||||
public boolean push(Long userId, String audience, String scene, String level,
|
||||
String title, String content, String dedupeKey) {
|
||||
return push(userId, audience, scene, level, title, content, dedupeKey, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 推送一条通知。dedupeKey 非空且库中已存在同键记录时跳过(返回 false),
|
||||
* 用于「同一异常在时间窗内只提醒一次」;dedupeKey 为空则不去重。
|
||||
*
|
||||
* @param subjectUserId 事件主体用户;桌面端行传 null 即可(收件人就是主体,见 {@link #resolveSubjectUserId})
|
||||
*/
|
||||
public boolean push(Long userId, String audience, String scene, String level,
|
||||
String title, String content, String dedupeKey, Long subjectUserId) {
|
||||
if (userId == null || userId <= 0) {
|
||||
log.warn("[notification] 推送被跳过:接收者无效 userId={} scene={}", userId, scene);
|
||||
return false;
|
||||
@@ -89,9 +108,11 @@ public class NotificationService {
|
||||
userId, audience, scene, key);
|
||||
return false;
|
||||
}
|
||||
String normalizedAudience = normalize(audience).isEmpty() ? AUDIENCE_USER : audience;
|
||||
UserNotificationEntity row = new UserNotificationEntity();
|
||||
row.setUserId(userId);
|
||||
row.setAudience(normalize(audience).isEmpty() ? AUDIENCE_USER : audience);
|
||||
row.setAudience(normalizedAudience);
|
||||
row.setSubjectUserId(resolveSubjectUserId(normalizedAudience, userId, subjectUserId));
|
||||
row.setScene(normalize(scene).isEmpty() ? SCENE_SYSTEM : scene);
|
||||
row.setLevel(normalize(level).isEmpty() ? LEVEL_WARNING : level);
|
||||
row.setTitle(truncate(title, TITLE_MAX_LENGTH));
|
||||
@@ -119,13 +140,18 @@ public class NotificationService {
|
||||
*/
|
||||
public boolean pushOrRefresh(Long userId, String audience, String scene, String level,
|
||||
String title, String content, String dedupeKey) {
|
||||
return pushOrRefresh(userId, audience, scene, level, title, content, dedupeKey, null);
|
||||
}
|
||||
|
||||
public boolean pushOrRefresh(Long userId, String audience, String scene, String level,
|
||||
String title, String content, String dedupeKey, Long subjectUserId) {
|
||||
String key = normalize(dedupeKey);
|
||||
if (key.isEmpty()) {
|
||||
return push(userId, audience, scene, level, title, content, key);
|
||||
return push(userId, audience, scene, level, title, content, key, subjectUserId);
|
||||
}
|
||||
UserNotificationEntity existing = selectByDedupeKey(key);
|
||||
if (existing == null) {
|
||||
return push(userId, audience, scene, level, title, content, key);
|
||||
return push(userId, audience, scene, level, title, content, key, subjectUserId);
|
||||
}
|
||||
String nextTitle = truncate(title, TITLE_MAX_LENGTH);
|
||||
String nextContent = truncate(content == null ? "" : content, CONTENT_MAX_LENGTH);
|
||||
@@ -142,6 +168,18 @@ public class NotificationService {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 事件主体用户:桌面端行的收件人就是主体本人,不必让每个写入点各传一遍;
|
||||
* 管理员行的主体只有分发层知道,传 null 就真的是「主体未知/不唯一」(服务级故障、
|
||||
* 一把密钥被 N 个账号共用),聚合时自成一组,不许拿接收者 id 冒充满。
|
||||
*/
|
||||
private static Long resolveSubjectUserId(String audience, Long recipientUserId, Long subjectUserId) {
|
||||
if (subjectUserId != null) {
|
||||
return subjectUserId;
|
||||
}
|
||||
return AUDIENCE_USER.equals(audience) ? recipientUserId : null;
|
||||
}
|
||||
|
||||
/** 分页查询(id 倒序);onlyUnread=true 时只返回未读,keyword/日期区间为空表示不限制。 */
|
||||
public NotificationPageVo page(Long userId, String audience, NotificationPageQuery query) {
|
||||
NotificationPageQuery safe = query == null ? new NotificationPageQuery() : query;
|
||||
@@ -175,6 +213,136 @@ public class NotificationService {
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚合列表:把「场景 × 自然日 × 主体用户」折成一行,分页按组切。
|
||||
*
|
||||
* <p>分组在 Java 侧做、SQL 只投影分组要用的那几列,为的是筛选条件与单条列表共用
|
||||
* {@link #baseWrapper} 这一份实现——同一批判据写两遍(lambda 列名版 + 字符串列名版)
|
||||
* 迟早漂移,而漂移的方向正好是"聚合视图和它展开的明细不是同一批行"。
|
||||
* 分母天然有界:过滤条件恒为「某个收件人 + 某个接收端」,而行只保留
|
||||
* {@code aiimage.notification.retention-days}(默认 7 天,见 NotificationRetentionService)。
|
||||
*/
|
||||
public NotificationGroupPageVo groups(Long userId, String audience, NotificationPageQuery query) {
|
||||
NotificationPageQuery safe = query == null ? new NotificationPageQuery() : query;
|
||||
long safePage = safe.getPage() == null || safe.getPage() < 1 ? 1L : safe.getPage();
|
||||
long safeSize = safe.getPageSize() == null || safe.getPageSize() < 1
|
||||
? 20L : Math.min(safe.getPageSize(), MAX_PAGE_SIZE);
|
||||
List<UserNotificationEntity> rows = userNotificationMapper.selectList(
|
||||
baseWrapper(userId, audience, Boolean.TRUE.equals(safe.getOnlyUnread()), safe)
|
||||
.select(UserNotificationEntity::getId, UserNotificationEntity::getScene,
|
||||
UserNotificationEntity::getSubjectUserId, UserNotificationEntity::getLevel,
|
||||
UserNotificationEntity::getCreatedAt, UserNotificationEntity::getReadAt)
|
||||
.orderByDesc(UserNotificationEntity::getId));
|
||||
|
||||
// 行按 id 倒序进来 ⇒ 每组第一次出现就是该组的最新一条(最终展示顺序另见下面显式排序)。
|
||||
Map<GroupKey, NotificationGroupVo> grouped = new LinkedHashMap<>();
|
||||
for (UserNotificationEntity row : rows) {
|
||||
GroupKey key = new GroupKey(row.getScene(), row.getCreatedAt().toLocalDate(), row.getSubjectUserId());
|
||||
NotificationGroupVo group = grouped.get(key);
|
||||
if (group == null) {
|
||||
group = new NotificationGroupVo();
|
||||
group.setLatestId(row.getId());
|
||||
group.setScene(row.getScene());
|
||||
group.setCategory(categoryOf(row.getScene()));
|
||||
group.setDay(key.day());
|
||||
group.setSubjectUserId(key.subjectUserId());
|
||||
group.setCreatedAt(row.getCreatedAt());
|
||||
group.setRowCount(0L);
|
||||
group.setUnreadCount(0L);
|
||||
group.setLevel(row.getLevel());
|
||||
grouped.put(key, group);
|
||||
}
|
||||
group.setRowCount(group.getRowCount() + 1);
|
||||
if (row.getReadAt() == null) {
|
||||
group.setUnreadCount(group.getUnreadCount() + 1);
|
||||
}
|
||||
if (levelRank(row.getLevel()) > levelRank(group.getLevel())) {
|
||||
group.setLevel(row.getLevel());
|
||||
}
|
||||
}
|
||||
|
||||
// 展示顺序显式按「自然日倒序 → 组内最新 id 倒序」。不靠"id 大就等于时间新":
|
||||
// 补录、时钟回拨都会让两者倒挂,那样最该看到的一组会被排到最后一页。
|
||||
List<NotificationGroupVo> all = new ArrayList<>(grouped.values());
|
||||
all.sort(Comparator.comparing(NotificationGroupVo::getDay, Comparator.reverseOrder())
|
||||
.thenComparing(NotificationGroupVo::getLatestId, Comparator.reverseOrder()));
|
||||
long offset = Math.max(0L, (safePage - 1) * safeSize);
|
||||
List<NotificationGroupVo> slice = offset >= all.size() ? List.of()
|
||||
: all.subList((int) offset, (int) Math.min(offset + safeSize, all.size()));
|
||||
fillGroupHeadline(slice);
|
||||
|
||||
NotificationGroupPageVo vo = new NotificationGroupPageVo();
|
||||
vo.setGroups(slice);
|
||||
vo.setTotal((long) all.size());
|
||||
vo.setRowCount((long) rows.size());
|
||||
vo.setPage(safePage);
|
||||
vo.setPageSize(safeSize);
|
||||
vo.setUnreadGroupCount(unreadGroupCount(userId, audience));
|
||||
vo.setUnreadCount(unreadCount(userId, audience));
|
||||
log.info("[notification] 聚合列表 userId={} audience={} page={} size={} 明细行={} 组数={} 未读组={}",
|
||||
userId, audience, safePage, safeSize, rows.size(), all.size(), vo.getUnreadGroupCount());
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 组头那行要显示标题/正文,只能回表取最新一条;按本页组数取,一页十几条,不做全量。 */
|
||||
private void fillGroupHeadline(List<NotificationGroupVo> slice) {
|
||||
if (slice.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<Long> latestIds = new ArrayList<>(slice.size());
|
||||
for (NotificationGroupVo group : slice) {
|
||||
latestIds.add(group.getLatestId());
|
||||
}
|
||||
Map<Long, UserNotificationEntity> byId = new HashMap<>();
|
||||
for (UserNotificationEntity row : userNotificationMapper.selectBatchIds(latestIds)) {
|
||||
byId.put(row.getId(), row);
|
||||
}
|
||||
for (NotificationGroupVo group : slice) {
|
||||
UserNotificationEntity head = byId.get(group.getLatestId());
|
||||
if (head == null) {
|
||||
continue;
|
||||
}
|
||||
group.setTitle(head.getTitle());
|
||||
group.setContent(head.getContent());
|
||||
}
|
||||
}
|
||||
|
||||
/** error > warning > info:一组里混进 error 不能被后到的 warning 盖掉。 */
|
||||
private static int levelRank(String level) {
|
||||
if (LEVEL_ERROR.equals(level)) {
|
||||
return 2;
|
||||
}
|
||||
return LEVEL_WARNING.equals(level) ? 1 : 0;
|
||||
}
|
||||
|
||||
/** 分组键:场景 × 自然日 × 主体用户;subjectUserId 为 null 时所有未标注行自成一组。 */
|
||||
private record GroupKey(String scene, LocalDate day, Long subjectUserId) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 有未读的**组数**(新前端红点用它)。
|
||||
*
|
||||
* <p>刻意不覆盖 {@link #unreadCount}:已装机的老客户端读的就是那个字段画徽标,把它的语义
|
||||
* 从"条数"换成"组数"会让老客户端出现"红点 3、列表 217 条"的对不上。
|
||||
*
|
||||
* <p>{@code COUNT(DISTINCT a,b,c)} 在 MySQL 里会**跳过任一表达式为 NULL 的行**,
|
||||
* 所以第三段必须 IFNULL——否则存量未标注的那些行整个不计,未读组数会少报。
|
||||
*/
|
||||
public long unreadGroupCount(Long userId, String audience) {
|
||||
List<Map<String, Object>> result = userNotificationMapper.selectMaps(new QueryWrapper<UserNotificationEntity>()
|
||||
.select("COUNT(DISTINCT scene, DATE(created_at), IFNULL(subject_user_id, -1)) AS group_count")
|
||||
.eq("user_id", userId)
|
||||
.eq("audience", audience)
|
||||
.isNull("read_at"));
|
||||
if (result == null || result.isEmpty() || result.get(0) == null || result.get(0).isEmpty()) {
|
||||
log.warn("[notification] 未读组数没读到值(不是 0)userId={} audience={}", userId, audience);
|
||||
return 0L;
|
||||
}
|
||||
// 只 select 了一列 ⇒ 取唯一一个值,不靠列名大小写(别名在不同驱动下形状不同)
|
||||
Object value = result.get(0).values().iterator().next();
|
||||
return value instanceof Number number ? number.longValue() : 0L;
|
||||
}
|
||||
|
||||
/** scene → 用户可见大类;未知 scene(历史遗留/新增未登记)一律归「系统通知」。 */
|
||||
public static String categoryOf(String scene) {
|
||||
return SCENE_TO_CATEGORY.getOrDefault(normalize(scene), CATEGORY_SYSTEM_NOTICE);
|
||||
@@ -202,6 +370,7 @@ public class NotificationService {
|
||||
public NotificationSummaryVo summary(Long userId, String audience) {
|
||||
NotificationSummaryVo vo = new NotificationSummaryVo();
|
||||
vo.setUnreadCount(unreadCount(userId, audience));
|
||||
vo.setUnreadGroupCount(unreadGroupCount(userId, audience));
|
||||
UserNotificationEntity latest = userNotificationMapper.selectOne(
|
||||
new LambdaQueryWrapper<UserNotificationEntity>()
|
||||
.select(UserNotificationEntity::getId)
|
||||
@@ -285,6 +454,29 @@ public class NotificationService {
|
||||
if (query.getEndDate() != null) {
|
||||
wrapper.lt(UserNotificationEntity::getCreatedAt, query.getEndDate().plusDays(1).atStartOfDay());
|
||||
}
|
||||
applyGroupFilters(wrapper, query);
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚合组展开明细的三个过滤条件。它们与 {@link #groups} 的分组键一一对应:
|
||||
* 前端拿组头返回的 scene/day/subjectUserId 原样回传,取到的就是这一组的行。
|
||||
* subjectUserId 为空且 subjectUnlabelled=true 时按 IS NULL 过滤——那是"存量未区分用户"
|
||||
* 那一组,不这么做它展开时会拿到**所有**没标注的行以外的结果,等于凭空多出一堆明细。
|
||||
*/
|
||||
private void applyGroupFilters(LambdaQueryWrapper<UserNotificationEntity> wrapper, NotificationPageQuery query) {
|
||||
String scene = normalize(query.getScene());
|
||||
if (!scene.isEmpty()) {
|
||||
wrapper.eq(UserNotificationEntity::getScene, scene);
|
||||
}
|
||||
if (query.getDay() != null) {
|
||||
wrapper.ge(UserNotificationEntity::getCreatedAt, query.getDay().atStartOfDay());
|
||||
wrapper.lt(UserNotificationEntity::getCreatedAt, query.getDay().plusDays(1).atStartOfDay());
|
||||
}
|
||||
if (query.getSubjectUserId() != null) {
|
||||
wrapper.eq(UserNotificationEntity::getSubjectUserId, query.getSubjectUserId());
|
||||
} else if (Boolean.TRUE.equals(query.getSubjectUnlabelled())) {
|
||||
wrapper.isNull(UserNotificationEntity::getSubjectUserId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
-- =============================================================
|
||||
-- 迁移 V158__notification_subject_user
|
||||
--
|
||||
-- 1. 变更目的:给 `biz_user_notification` 补一列「这件事是关于哪个用户的」。
|
||||
-- 这张表从 V116 建表起只有一个用户列 `user_id`,语义是**接收者**(桌面端用户本人
|
||||
-- 或后台管理员本人),而后台管理员行的主体用户只写在 `content` 文案里
|
||||
-- ("用户 小魏11(uid=1160)任务 COLLECT_DATA-…")。后果是列表出口拿不到"按用户
|
||||
-- 聚合"的分组键 ⇒ 铃铛只能一个事件一行地平铺。用户 2026-10-13 反馈
|
||||
-- 「现在通知的数据都没做整合 看的累」,实测后台侧 217 条未读、22 页,
|
||||
-- 其中同一场景反复出现、只有 uid 与任务号不同(见截图两条「用户采集数据任务部分结果缺失」)。
|
||||
-- 本迁移是"场景 × 自然日 × 用户"聚合的那一把分组键的存储前提。
|
||||
--
|
||||
-- 2. 前提取证(本轮只做代码侧,未跑生产只读普查):
|
||||
-- · V116 建表语句里与用户相关的列只有 `user_id BIGINT NOT NULL COMMENT '接收者ID'`
|
||||
-- 与 `audience`(user=桌面端/admin=后台),没有主体用户列;
|
||||
-- · 写入侧本来就知道主体是谁:`NotificationDispatchService.pushToAdmins(..., subjectUserId)`
|
||||
-- 的第 62 行已经拿它做 `audience.canReceive(adminId, subjectUserId)` 的数据权限过滤,
|
||||
-- 只是过滤完就把这个值丢了、没有落库 ⇒ 补列不需要新的推导逻辑;
|
||||
-- · 全仓 `notificationService.push/pushOrRefresh` 的调用点共 6 处,全部在通知模块内
|
||||
-- (NotificationDispatchService 5 处 + NotificationScanScheduler 1 处),
|
||||
-- 没有模块外的写入方需要一起改。
|
||||
--
|
||||
-- 3. 影响表与数据量:只加一列,不写数据、不加索引、不删列、不碰其他表。
|
||||
-- 存量行取 NULL。口径(用户 2026-10-13 定):**存量不回填**——旧的管理员行不按用户
|
||||
-- 拆开,聚合时所有 NULL 归为同一组,界面上表现为「未区分用户」的一组,展开仍能看到明细。
|
||||
-- 不做回填的理由是不拿正则去解析历史文案当分组键(措辞改过形的行会静默漏归,
|
||||
-- 而"漏归"在界面上与"本来就没有"同形)。
|
||||
-- `audience='user'` 的行由写入侧自动补成 `subject_user_id = user_id`(同一人),
|
||||
-- 所以桌面端不需要回填也有分组键。
|
||||
--
|
||||
-- 4. 锁表风险:极低。nullable、无 DEFAULT 的 `ADD COLUMN` 在 MySQL 8 走 INSTANT,
|
||||
-- 不重建表、不阻塞 DML。**刻意不加二级索引**:聚合查询的过滤条件恒为
|
||||
-- `user_id = ? AND audience = ?`,V116 的 `idx_user_audience_read` 已覆盖这对等值前缀,
|
||||
-- 组内行数又被 `NotificationRetentionService` 的 7 天物理保留压住 ⇒ 加 (audience, user_id,
|
||||
-- scene, created_at, subject_user_id) 这种宽索引买不到东西,只多一次重建表。
|
||||
--
|
||||
-- 5. 验证 SQL(迁移后跑,不许只看启动日志的 Successfully applied):
|
||||
-- SHOW COLUMNS FROM `biz_user_notification` LIKE 'subject_user_id';
|
||||
-- -> 期望 1 行:Type = bigint,Null = YES,Default = NULL
|
||||
-- SELECT COUNT(*) AS total,
|
||||
-- SUM(subject_user_id IS NULL) AS unlabelled
|
||||
-- FROM `biz_user_notification`;
|
||||
-- -> 期望 unlabelled = total(本迁移只加列,不回填)
|
||||
-- SHOW INDEX FROM `biz_user_notification`;
|
||||
-- -> 期望索引清单与迁移前逐字相同(没有新增索引)
|
||||
-- 迁移后新产生的行:`SELECT id, audience, user_id, subject_user_id, scene
|
||||
-- FROM biz_user_notification ORDER BY id DESC LIMIT 10;`
|
||||
-- -> audience='user' 的行 subject_user_id 应等于 user_id;
|
||||
-- audience='admin' 的行 subject_user_id 应是文案里那个 uid(跨用户合并的
|
||||
-- pushToAdminsAnyOf 除外,那类事件主体不唯一,留 NULL)。
|
||||
--
|
||||
-- 6. 上线窗口:随 jar 双节点同窗口发布。加列对旧 jar 无影响(旧代码不认识新列,
|
||||
-- MyBatis-Plus 按实体字段生成列名,旧实体没有这一列 ⇒ INSERT 里不会出现它);
|
||||
-- 反过来只发 jar 不发迁移,会在第一次写 subject_user_id 时撞 1054 Unknown column。
|
||||
-- ⇒ 迁移必须与读它的那版 jar 同版。
|
||||
--
|
||||
-- 7. 可重跑性:照 V146/V155/V157 惯例,加列前先查 information_schema——迁移中途失败时
|
||||
-- flyway repair + 重启会从第一条语句重跑整个文件,裸 ADD COLUMN 会撞 1060。
|
||||
--
|
||||
-- 8. 回滚(人工补丁,写成注释以免落在 Flyway 扫描路径里被当迁移执行):
|
||||
-- 触发场景是"这一列不该加"。顺序:停两台应用 → 跑下面一条 DROP →
|
||||
-- 删 flyway_schema_history 的 version='158' 行 → 回滚 jar → 起应用。
|
||||
-- ALTER TABLE `biz_user_notification` DROP COLUMN `subject_user_id`;
|
||||
-- 仅回滚 jar(代码问题、与列无关)不需要 DROP:旧 jar 不认识这一列,留着零影响。
|
||||
-- 注意:新 jar 跑过之后这一列会积累非 NULL 值,DROP 会连带丢掉"按用户分组"的依据,
|
||||
-- 使聚合退回"未区分用户"那一组——那是显示退化,不是数据丢失(明细行本身还在)。
|
||||
-- =============================================================
|
||||
|
||||
SET @tbl := (
|
||||
SELECT COUNT(*) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = 'biz_user_notification'
|
||||
AND COLUMN_NAME = 'subject_user_id'
|
||||
);
|
||||
SET @ddl := IF(@tbl = 0,
|
||||
'ALTER TABLE `biz_user_notification` ADD COLUMN `subject_user_id` bigint NULL DEFAULT NULL COMMENT ''事件主体用户(users.id):管理员行=这件事关于谁,桌面端行=user_id 本人;NULL=存量未标注或主体不唯一''',
|
||||
'SELECT ''biz_user_notification.subject_user_id already exists, skipped'' AS note');
|
||||
PREPARE stmt FROM @ddl;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
+11
-5
@@ -18,7 +18,7 @@ import org.junit.jupiter.api.Test;
|
||||
* 分页/条数默认值的<b>逐点台账 + 棘轮</b>(2026-10-09 评审「可读 5.0 / 交互 5.5」项 5)。
|
||||
*
|
||||
* <p>评审量到的是"15/20/50/1000 四种并存、31 处 {@code defaultValue}"。本轮实测更细:
|
||||
* 数字型 {@code defaultValue} 共 <b>49</b> 处,其中 48 处是分页/条数口径(21 处页码 + 27 处容量与上限),
|
||||
* 数字型 {@code defaultValue} 共 <b>53</b> 处,其中 52 处是分页/条数口径(23 处页码 + 29 处容量与上限),
|
||||
* 另有 1 处是 {@code timeout_minutes=30},不是分页。
|
||||
*
|
||||
* <p>这里<b>不规定"全局统一默认页容量"</b>——把 15/20/50/1000 拍成一个数是改行为。判据只做两件事:
|
||||
@@ -39,7 +39,7 @@ class PageDefaultsLedgerTest {
|
||||
|
||||
/**
|
||||
* 出站点台账:{@code 文件#参数 -> 该页当前默认值的具名出处}。
|
||||
* 48 条,逐条对应一次真实翻页行为;加页要登记,改值要表态。
|
||||
* 52 条,逐条对应一次真实翻页行为;加页要登记,改值要表态。
|
||||
*/
|
||||
private static final List<String> LEDGER = List.of(
|
||||
"AdminUserController.java#page=FIRST_PAGE",
|
||||
@@ -54,6 +54,9 @@ class PageDefaultsLedgerTest {
|
||||
"AdminImageVideoTaskController.java#page_size=ADMIN_LIST_PAGE_SIZE",
|
||||
"AdminNotificationController.java#page=FIRST_PAGE",
|
||||
"AdminNotificationController.java#pageSize=ADMIN_LIST_PAGE_SIZE",
|
||||
// (本批 /groups 端点:参数名与默认值和列表端点同,台账按出站点计数、不去重)
|
||||
"AdminNotificationController.java#page=FIRST_PAGE",
|
||||
"AdminNotificationController.java#pageSize=ADMIN_LIST_PAGE_SIZE",
|
||||
"AppearancePatentController.java#limit=DEFAULT_RESULT_LIMIT",
|
||||
"CollectDataController.java#page=FIRST_PAGE",
|
||||
"CollectDataController.java#page_size=TASK_LIST_PAGE_SIZE",
|
||||
@@ -66,6 +69,9 @@ class PageDefaultsLedgerTest {
|
||||
"InvalidAsinDataController.java#page_size=USER_LIST_PAGE_SIZE",
|
||||
"NotificationController.java#page=FIRST_PAGE",
|
||||
"NotificationController.java#pageSize=ADMIN_LIST_PAGE_SIZE",
|
||||
// (本批 /groups 端点:参数名与默认值和列表端点同,台账按出站点计数、不去重)
|
||||
"NotificationController.java#page=FIRST_PAGE",
|
||||
"NotificationController.java#pageSize=ADMIN_LIST_PAGE_SIZE",
|
||||
"PriceTrackController.java#page=FIRST_PAGE",
|
||||
"PriceTrackController.java#page_size=FULL_EXPORT_PAGE_SIZE",
|
||||
"ProductCategoryController.java#page=FIRST_PAGE",
|
||||
@@ -101,10 +107,10 @@ class PageDefaultsLedgerTest {
|
||||
List<String> constants = actual.stream().filter(s -> !s.contains("LITERAL")).sorted().toList();
|
||||
|
||||
assertThat(constants)
|
||||
.as("48 处分页/条数出站点的具名默认值必须与台账一一对应")
|
||||
.as("52 处分页/条数出站点的具名默认值必须与台账一一对应")
|
||||
.isEqualTo(LEDGER.stream().sorted().toList());
|
||||
// 同口径非零对照:台账不是空的,扫描器也确实数得出 48 处
|
||||
assertThat(constants).hasSize(48);
|
||||
assertThat(constants).hasSize(52);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -120,7 +126,7 @@ class PageDefaultsLedgerTest {
|
||||
List<String> actual = sites();
|
||||
assertThat(kindsUsing(actual, "page", "FIRST_PAGE"))
|
||||
.as("页码口径只有一套:全部从 1 起")
|
||||
.isEqualTo(21);
|
||||
.isEqualTo(23);
|
||||
assertThat(distinctConstants(actual, "page_size"))
|
||||
.as("page_size 的默认容量集合:15/20/50/1000 四种各自登记,新来第五种要红")
|
||||
.containsExactlyInAnyOrder("USER_LIST_PAGE_SIZE", "ADMIN_LIST_PAGE_SIZE",
|
||||
|
||||
+19
-1
@@ -11,6 +11,7 @@ import org.mockito.ArgumentCaptor;
|
||||
import java.time.LocalDate;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
@@ -35,7 +36,8 @@ class AdminNotificationControllerTest {
|
||||
|
||||
controller.summary(request);
|
||||
controller.page(request, 1L, 20L, false, "余额", NotificationService.CATEGORY_CONFIG_ERROR,
|
||||
LocalDate.of(2026, 9, 10), LocalDate.of(2026, 9, 13));
|
||||
LocalDate.of(2026, 9, 10), LocalDate.of(2026, 9, 13),
|
||||
"task_partial", LocalDate.of(2026, 9, 12), 1160L, false);
|
||||
|
||||
verify(notificationService).summary(24L, NotificationService.AUDIENCE_ADMIN);
|
||||
ArgumentCaptor<NotificationPageQuery> queryCaptor = ArgumentCaptor.forClass(NotificationPageQuery.class);
|
||||
@@ -48,6 +50,22 @@ class AdminNotificationControllerTest {
|
||||
assertThat(query.getCategory()).isEqualTo(NotificationService.CATEGORY_CONFIG_ERROR);
|
||||
assertThat(query.getStartDate()).isEqualTo(LocalDate.of(2026, 9, 10));
|
||||
assertThat(query.getEndDate()).isEqualTo(LocalDate.of(2026, 9, 13));
|
||||
// 聚合组展开的三个条件必须原样落到查询对象上,丢了任何一个,展开就会多拿别的组的明细
|
||||
assertThat(query.getScene()).isEqualTo("task_partial");
|
||||
assertThat(query.getDay()).isEqualTo(LocalDate.of(2026, 9, 12));
|
||||
assertThat(query.getSubjectUserId()).isEqualTo(1160L);
|
||||
assertThat(query.getSubjectUnlabelled()).isFalse();
|
||||
}
|
||||
|
||||
/** 聚合视图与单条列表读的是同一份"谁的副本",这里守 groups 这条新出口别绕过管理员维度。 */
|
||||
@Test
|
||||
void groupsUseOperatorIdAndAdminAudience() {
|
||||
when(adminAuthSupport.requireConsoleOperator(request)).thenReturn(admin(24L));
|
||||
|
||||
controller.groups(request, 1L, 20L, false, null, null, null, null);
|
||||
|
||||
verify(notificationService).groups(eq(24L), eq(NotificationService.AUDIENCE_ADMIN),
|
||||
argThat(query -> query.getPage().equals(1L) && query.getPageSize().equals(20L)));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+6
-1
@@ -34,7 +34,8 @@ class NotificationControllerTest {
|
||||
|
||||
controller.summary(request);
|
||||
controller.page(request, 2L, 20L, true, "欠费", NotificationService.CATEGORY_TASK_ERROR,
|
||||
LocalDate.of(2026, 9, 1), LocalDate.of(2026, 9, 13));
|
||||
LocalDate.of(2026, 9, 1), LocalDate.of(2026, 9, 13),
|
||||
"task_failed", LocalDate.of(2026, 9, 5));
|
||||
|
||||
verify(notificationService).summary(1095L, NotificationService.AUDIENCE_USER);
|
||||
ArgumentCaptor<NotificationPageQuery> queryCaptor = ArgumentCaptor.forClass(NotificationPageQuery.class);
|
||||
@@ -47,6 +48,10 @@ class NotificationControllerTest {
|
||||
assertThat(query.getCategory()).isEqualTo(NotificationService.CATEGORY_TASK_ERROR);
|
||||
assertThat(query.getStartDate()).isEqualTo(LocalDate.of(2026, 9, 1));
|
||||
assertThat(query.getEndDate()).isEqualTo(LocalDate.of(2026, 9, 13));
|
||||
assertThat(query.getScene()).isEqualTo("task_failed");
|
||||
assertThat(query.getDay()).isEqualTo(LocalDate.of(2026, 9, 5));
|
||||
// 桌面端的主体用户就是本人,接口不暴露 subjectUserId,展开只靠 场景+自然日
|
||||
assertThat(query.getSubjectUserId()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+30
-20
@@ -14,6 +14,7 @@ import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.contains;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.times;
|
||||
@@ -61,8 +62,7 @@ class NotificationDispatchServiceTest {
|
||||
when(adminAuthSupport.currentRole(superAdmin)).thenReturn("super_admin");
|
||||
when(adminAuthSupport.currentRole(admin)).thenReturn("admin");
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(2L)).thenReturn(List.of(2L));
|
||||
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(true);
|
||||
stubPushOrRefresh();
|
||||
|
||||
NotificationDispatchService.AdminAudience audience = service.prepareAdminAudience();
|
||||
int pushed = service.pushToAdmins(audience, NotificationService.SCENE_TASK_FAILED,
|
||||
@@ -70,9 +70,10 @@ class NotificationDispatchServiceTest {
|
||||
|
||||
// 主管乙不可见用户 20 → 只有超管收到
|
||||
assertThat(pushed).isEqualTo(1);
|
||||
// 第 8 个参数是事件主体用户:管理员行必须带上它,聚合才有"按用户折"的键
|
||||
org.mockito.Mockito.verify(notificationService).pushOrRefresh(eq(1L), eq(NotificationService.AUDIENCE_ADMIN),
|
||||
eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
|
||||
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:1"));
|
||||
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:1"), eq(20L));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -86,8 +87,7 @@ class NotificationDispatchServiceTest {
|
||||
when(adminAuthSupport.currentRole(outOfScope)).thenReturn("admin");
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(2L)).thenReturn(List.of(2L, 20L));
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(3L)).thenReturn(List.of(3L, 30L));
|
||||
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(true);
|
||||
stubPushOrRefresh();
|
||||
|
||||
int pushed = service.pushToAdmins(NotificationService.SCENE_TASK_FAILED,
|
||||
NotificationService.LEVEL_WARNING, "标题", "内容",
|
||||
@@ -97,13 +97,13 @@ class NotificationDispatchServiceTest {
|
||||
assertThat(pushed).isEqualTo(2);
|
||||
verify(notificationService).pushOrRefresh(eq(1L), eq(NotificationService.AUDIENCE_ADMIN),
|
||||
eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
|
||||
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:1"));
|
||||
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:1"), eq(20L));
|
||||
verify(notificationService).pushOrRefresh(eq(2L), eq(NotificationService.AUDIENCE_ADMIN),
|
||||
eq(NotificationService.SCENE_TASK_FAILED), eq(NotificationService.LEVEL_WARNING),
|
||||
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:2"));
|
||||
eq("标题"), eq("内容"), eq("task_failed_admin:20:PRICE_TRACK:20260913:2"), eq(20L));
|
||||
// 非本组主管一条都不落
|
||||
verify(notificationService, never()).pushOrRefresh(eq(3L), anyString(), anyString(),
|
||||
anyString(), anyString(), anyString(), anyString());
|
||||
anyString(), anyString(), anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -121,8 +121,7 @@ class NotificationDispatchServiceTest {
|
||||
when(adminAuthSupport.currentRole(outOfScope)).thenReturn("admin");
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(2L)).thenReturn(List.of(2L, 20L));
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(3L)).thenReturn(List.of(3L, 30L));
|
||||
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(true);
|
||||
stubPushOrRefresh();
|
||||
|
||||
int pushed = service.pushToAdminsAnyOf(service.prepareAdminAudience(),
|
||||
NotificationService.SCENE_SECRET_BALANCE, NotificationService.LEVEL_ERROR,
|
||||
@@ -131,12 +130,14 @@ class NotificationDispatchServiceTest {
|
||||
// 3 个受影响账号 × 2 个可见管理员 = 只落 2 条;非本组主管一条都不落
|
||||
assertThat(pushed).isEqualTo(2);
|
||||
verify(notificationService, times(2)).pushOrRefresh(anyLong(), anyString(), anyString(),
|
||||
anyString(), anyString(), anyString(), anyString());
|
||||
anyString(), anyString(), anyString(), anyString(), any());
|
||||
// 合并告警的主体不唯一(一把密钥被 N 个账号共用)⇒ 留 null,聚合时自成一组,
|
||||
// 不挑一个 uid 冒充"这件事关于谁"
|
||||
verify(notificationService).pushOrRefresh(eq(2L), eq(NotificationService.AUDIENCE_ADMIN),
|
||||
eq(NotificationService.SCENE_SECRET_BALANCE), eq(NotificationService.LEVEL_ERROR),
|
||||
eq("标题"), eq("内容"), eq("secret_balance_admin:group:hash:20261002:2"));
|
||||
eq("标题"), eq("内容"), eq("secret_balance_admin:group:hash:20261002:2"), isNull());
|
||||
verify(notificationService, never()).pushOrRefresh(eq(3L), anyString(), anyString(),
|
||||
anyString(), anyString(), anyString(), anyString());
|
||||
anyString(), anyString(), anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -149,8 +150,7 @@ class NotificationDispatchServiceTest {
|
||||
when(adminAuthSupport.currentRole(adminA)).thenReturn("admin");
|
||||
when(adminAuthSupport.currentRole(adminB)).thenReturn("admin");
|
||||
when(userDataScopeSupport.resolveVisibleUserIds(anyLong())).thenReturn(List.of());
|
||||
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(true);
|
||||
stubPushOrRefresh();
|
||||
|
||||
// 服务探测失败这类全局事件(subjectUserId=null)按设计推给所有管理员,不受分组限制
|
||||
int pushed = service.pushToAdmins(NotificationService.SCENE_SERVICE_DOWN,
|
||||
@@ -170,8 +170,7 @@ class NotificationDispatchServiceTest {
|
||||
AdminUserEntity superAdmin = admin(1L, "超管甲");
|
||||
when(adminUserMapper.selectList(any())).thenReturn(List.of(superAdmin));
|
||||
when(adminAuthSupport.currentRole(superAdmin)).thenReturn("super_admin");
|
||||
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(true);
|
||||
stubPushOrRefresh();
|
||||
|
||||
service.pushPartialResult(20L, 3301L, "BRAND", "BRAND-3301", "12 个品牌查询失败");
|
||||
|
||||
@@ -180,13 +179,12 @@ class NotificationDispatchServiceTest {
|
||||
contains("任务部分结果缺失"), contains("12 个品牌查询失败"), eq("task_partial:3301"));
|
||||
verify(notificationService).pushOrRefresh(eq(1L), eq(NotificationService.AUDIENCE_ADMIN),
|
||||
eq(NotificationService.SCENE_TASK_PARTIAL), eq(NotificationService.LEVEL_WARNING),
|
||||
contains("用户"), anyString(), eq("task_partial_admin:3301:1"));
|
||||
contains("用户"), anyString(), eq("task_partial_admin:3301:1"), eq(20L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pushToUserUsesUserAudience() {
|
||||
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString()))
|
||||
.thenReturn(true);
|
||||
stubPushOrRefresh();
|
||||
|
||||
boolean pushed = service.pushToUser(7L, NotificationService.SCENE_SECRET_BALANCE,
|
||||
NotificationService.LEVEL_ERROR, "标题", "内容", "secret_balance:7:proxy:20260913");
|
||||
@@ -208,6 +206,18 @@ class NotificationDispatchServiceTest {
|
||||
assertThat(service.displayNameOf(null)).isEqualTo("未知用户");
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员行走 8 参重载(带事件主体用户)、桌面端行走 7 参便捷档(主体就是收件人)。
|
||||
* 两条都桩:只桩一条的话,"生产码换了一条出口"会表现成 pushed=0 的假失败,
|
||||
* 看着像分发没跑,其实是桩没接上。
|
||||
*/
|
||||
private void stubPushOrRefresh() {
|
||||
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(),
|
||||
anyString(), anyString(), anyString())).thenReturn(true);
|
||||
when(notificationService.pushOrRefresh(anyLong(), anyString(), anyString(), anyString(),
|
||||
anyString(), anyString(), anyString(), any())).thenReturn(true);
|
||||
}
|
||||
|
||||
private AdminUserEntity admin(Long id, String username) {
|
||||
AdminUserEntity user = new AdminUserEntity();
|
||||
user.setId(id);
|
||||
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
package com.nanri.aiimage.modules.notification.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.modules.notification.mapper.UserNotificationMapper;
|
||||
import com.nanri.aiimage.modules.notification.model.dto.NotificationPageQuery;
|
||||
import com.nanri.aiimage.modules.notification.model.entity.UserNotificationEntity;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationGroupPageVo;
|
||||
import com.nanri.aiimage.modules.notification.model.vo.NotificationGroupVo;
|
||||
import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 通知聚合视图:把「场景 × 自然日 × 事件主体用户」折成一行。
|
||||
*
|
||||
* <p>这组用例钉的是"折叠折在哪、折掉了什么",不是"折得好不好看":
|
||||
* 分组键的三个维度各自都要能**把一组拆成两组**(少一个维度就会把不同用户或不同天
|
||||
* 混成一条,那是比刷屏更糟的错——故障被藏起来了);而 total(组数)与 rowCount(明细条数)
|
||||
* 必须同时给出且不相等,否则界面上的「共 N 条」会被读成"只有 N 条通知"。
|
||||
*/
|
||||
class NotificationGroupTest {
|
||||
|
||||
@BeforeAll
|
||||
static void initTableInfo() {
|
||||
TableInfoHelper.initTableInfo(new MapperBuilderAssistant(new MybatisConfiguration(), ""),
|
||||
UserNotificationEntity.class);
|
||||
}
|
||||
|
||||
private final UserNotificationMapper mapper = mock(UserNotificationMapper.class);
|
||||
private final NotificationService service = new NotificationService(mapper);
|
||||
|
||||
private static UserNotificationEntity row(long id, String scene, Long subject, LocalDate day,
|
||||
String level, LocalDateTime readAt) {
|
||||
UserNotificationEntity entity = new UserNotificationEntity();
|
||||
entity.setId(id);
|
||||
entity.setScene(scene);
|
||||
entity.setSubjectUserId(subject);
|
||||
entity.setLevel(level);
|
||||
entity.setCreatedAt(day.atTime(9, 30).plusMinutes(id % 50));
|
||||
entity.setReadAt(readAt);
|
||||
return entity;
|
||||
}
|
||||
|
||||
private static UserNotificationEntity headline(long id, String title, String content) {
|
||||
UserNotificationEntity entity = new UserNotificationEntity();
|
||||
entity.setId(id);
|
||||
entity.setTitle(title);
|
||||
entity.setContent(content);
|
||||
return entity;
|
||||
}
|
||||
|
||||
/** 只喂分组要用的列,明细文案靠 selectBatchIds 回表取——这条桩同时钉住"组头只回表取本页组"。 */
|
||||
private void stub(List<UserNotificationEntity> rows, List<UserNotificationEntity> heads) {
|
||||
when(mapper.selectList(any())).thenReturn(rows);
|
||||
when(mapper.selectBatchIds(any())).thenReturn(heads);
|
||||
// 行数桩成非 0:page() 在 total==0 时直接短路、根本不调 selectList,
|
||||
// 那样下面两个"筛选条件进没进 WHERE"的断言会抓不到 wrapper 而假失败。
|
||||
when(mapper.selectCount(any())).thenReturn(1L);
|
||||
when(mapper.selectMaps(any())).thenReturn(List.of(Map.of("group_count", 0)));
|
||||
}
|
||||
|
||||
private NotificationGroupPageVo groups() {
|
||||
return service.groups(24L, NotificationService.AUDIENCE_ADMIN, new NotificationPageQuery());
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void sameSceneDaySubjectFoldsIntoOneGroupWithBothCounts() {
|
||||
stub(List.of(
|
||||
row(5, "task_partial", 1160L, LocalDate.of(2026, 10, 13), "warning", null),
|
||||
row(4, "task_partial", 1160L, LocalDate.of(2026, 10, 13), "warning", null),
|
||||
row(3, "task_partial", 1160L, LocalDate.of(2026, 10, 13), "warning",
|
||||
LocalDateTime.of(2026, 10, 13, 10, 0))),
|
||||
List.of(headline(5, "用户采集数据任务部分结果缺失", "用户 小魏11(uid=1160)任务 A:6 行")));
|
||||
|
||||
NotificationGroupPageVo vo = groups();
|
||||
|
||||
assertThat(vo.getGroups()).hasSize(1);
|
||||
NotificationGroupVo group = vo.getGroups().get(0);
|
||||
assertThat(group.getRowCount()).isEqualTo(3L);
|
||||
assertThat(group.getUnreadCount()).isEqualTo(2L);
|
||||
assertThat(group.getLatestId()).isEqualTo(5L);
|
||||
assertThat(group.getTitle()).isEqualTo("用户采集数据任务部分结果缺失");
|
||||
// 组数与明细数必须同时给出且不相等:只报一个,界面上就是"少了一堆通知"
|
||||
assertThat(vo.getTotal()).isEqualTo(1L);
|
||||
assertThat(vo.getRowCount()).isEqualTo(3L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void differentSubjectUsersStayInSeparateGroups() {
|
||||
stub(List.of(
|
||||
row(9, "task_partial", 1196L, LocalDate.of(2026, 10, 12), "warning", null),
|
||||
row(8, "task_partial", 1160L, LocalDate.of(2026, 10, 12), "warning", null)),
|
||||
List.of(headline(9, "t", "c"), headline(8, "t", "c")));
|
||||
|
||||
NotificationGroupPageVo vo = groups();
|
||||
|
||||
assertThat(vo.getGroups()).hasSize(2);
|
||||
assertThat(vo.getGroups()).extracting(NotificationGroupVo::getSubjectUserId).containsExactly(1196L, 1160L);
|
||||
assertThat(vo.getTotal()).isEqualTo(2L);
|
||||
assertThat(vo.getRowCount()).isEqualTo(2L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void differentDaysAndScenesEachBreakTheGroup() {
|
||||
stub(List.of(
|
||||
row(7, "task_failed", 1160L, LocalDate.of(2026, 10, 12), "warning", null),
|
||||
row(6, "task_partial", 1160L, LocalDate.of(2026, 10, 12), "warning", null),
|
||||
row(5, "task_partial", 1160L, LocalDate.of(2026, 10, 11), "warning", null)),
|
||||
List.of(headline(7, "t", "c"), headline(6, "t", "c"), headline(5, "t", "c")));
|
||||
|
||||
NotificationGroupPageVo vo = groups();
|
||||
|
||||
assertThat(vo.getGroups()).hasSize(3);
|
||||
assertThat(vo.getGroups()).extracting(NotificationGroupVo::getDay)
|
||||
.containsExactly(LocalDate.of(2026, 10, 12), LocalDate.of(2026, 10, 12), LocalDate.of(2026, 10, 11));
|
||||
assertThat(vo.getGroups()).extracting(NotificationGroupVo::getScene)
|
||||
.containsExactly("task_failed", "task_partial", "task_partial");
|
||||
}
|
||||
|
||||
/** 存量行没有主体用户列(V158 不回填):它们按"未区分用户"自成一组,而不是按文案里的 uid 拆开。 */
|
||||
@Test
|
||||
void unlabelledLegacyRowsFormOneNullSubjectGroup() {
|
||||
stub(List.of(
|
||||
row(4, "task_partial", null, LocalDate.of(2026, 10, 9), "warning", null),
|
||||
row(3, "task_partial", null, LocalDate.of(2026, 10, 9), "warning", null)),
|
||||
List.of(headline(4, "t", "c")));
|
||||
|
||||
NotificationGroupPageVo vo = groups();
|
||||
|
||||
assertThat(vo.getGroups()).hasSize(1);
|
||||
assertThat(vo.getGroups().get(0).getSubjectUserId()).isNull();
|
||||
assertThat(vo.getGroups().get(0).getRowCount()).isEqualTo(2L);
|
||||
}
|
||||
|
||||
/** 一组里混进 error 不能被后写入的 warning 盖掉——级别是"这组有多严重"的唯一凭据。 */
|
||||
@Test
|
||||
void groupLevelTakesTheMostSevereRowNotTheLatest() {
|
||||
stub(List.of(
|
||||
row(6, "service_down", null, LocalDate.of(2026, 10, 13), "warning", null),
|
||||
row(5, "service_down", null, LocalDate.of(2026, 10, 13), "error", null)),
|
||||
List.of(headline(6, "t", "c")));
|
||||
|
||||
assertThat(groups().getGroups().get(0).getLevel()).isEqualTo("error");
|
||||
}
|
||||
|
||||
@Test
|
||||
void pagingCutsGroupsNotRows() {
|
||||
stub(List.of(
|
||||
row(9, "task_partial", 1160L, LocalDate.of(2026, 10, 13), "warning", null),
|
||||
row(8, "task_partial", 1196L, LocalDate.of(2026, 10, 13), "warning", null),
|
||||
row(7, "task_partial", 1160L, LocalDate.of(2026, 10, 13), "warning", null)),
|
||||
List.of(headline(9, "t", "c"), headline(8, "t", "c")));
|
||||
NotificationPageQuery query = new NotificationPageQuery();
|
||||
query.setPage(2L);
|
||||
query.setPageSize(1L);
|
||||
|
||||
NotificationGroupPageVo vo = service.groups(24L, NotificationService.AUDIENCE_ADMIN, query);
|
||||
|
||||
assertThat(vo.getTotal()).isEqualTo(2L);
|
||||
assertThat(vo.getRowCount()).isEqualTo(3L);
|
||||
assertThat(vo.getGroups()).hasSize(1);
|
||||
assertThat(vo.getGroups().get(0).getSubjectUserId()).isEqualTo(1196L);
|
||||
}
|
||||
|
||||
/**
|
||||
* 补录/时钟回拨会让 id 与 created_at 倒挂:新的一天可能带着更小的 id。
|
||||
* 排序必须按天,否则最该看到的一组被排到最后一页——分页之后就彻底看不见了。
|
||||
*/
|
||||
@Test
|
||||
void groupOrderFollowsDayNotId() {
|
||||
stub(List.of(
|
||||
row(99, "task_failed", 1160L, LocalDate.of(2026, 10, 11), "warning", null),
|
||||
row(1, "task_failed", 1160L, LocalDate.of(2026, 10, 13), "warning", null)),
|
||||
List.of(headline(99, "t", "c"), headline(1, "t", "c")));
|
||||
|
||||
assertThat(groups().getGroups()).extracting(NotificationGroupVo::getDay)
|
||||
.containsExactly(LocalDate.of(2026, 10, 13), LocalDate.of(2026, 10, 11));
|
||||
}
|
||||
|
||||
/** 展开明细的三个条件必须进 WHERE:丢任何一个,展开就会把别的组也倒进来。 */
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void drillDownFiltersReachTheWhereClause() {
|
||||
stub(List.of(), List.of());
|
||||
NotificationPageQuery query = new NotificationPageQuery();
|
||||
query.setScene("task_partial");
|
||||
query.setDay(LocalDate.of(2026, 9, 12));
|
||||
query.setSubjectUserId(1160L);
|
||||
|
||||
service.page(24L, NotificationService.AUDIENCE_ADMIN, query);
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper<UserNotificationEntity>> captor = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
|
||||
verify(mapper, org.mockito.Mockito.atLeastOnce()).selectList(captor.capture());
|
||||
LambdaQueryWrapper<UserNotificationEntity> wrapper = captor.getValue();
|
||||
// MP 3.5.7 要先求值一次 getSqlSegment(),参数才会铺进 paramNameValuePairs
|
||||
String sql = wrapper.getSqlSegment();
|
||||
assertThat(sql).contains("scene").contains("subject_user_id").contains("created_at");
|
||||
assertThat(wrapper.getParamNameValuePairs().values()).contains("task_partial", 1160L);
|
||||
}
|
||||
|
||||
/** 「未区分用户」那一组展开时按 IS NULL 过滤;不这么做它会连带把已标注的行一起倒出来。 */
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void unlabelledGroupExpandsWithIsNull() {
|
||||
stub(List.of(), List.of());
|
||||
NotificationPageQuery query = new NotificationPageQuery();
|
||||
query.setScene("task_partial");
|
||||
query.setSubjectUnlabelled(true);
|
||||
|
||||
service.page(24L, NotificationService.AUDIENCE_ADMIN, query);
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper<UserNotificationEntity>> captor = ArgumentCaptor.forClass(LambdaQueryWrapper.class);
|
||||
verify(mapper, org.mockito.Mockito.atLeastOnce()).selectList(captor.capture());
|
||||
assertThat(captor.getValue().getSqlSegment()).contains("subject_user_id IS NULL");
|
||||
}
|
||||
|
||||
/**
|
||||
* 未读组数走 COUNT(DISTINCT 场景, 自然日, IFNULL(主体用户,-1))。
|
||||
*
|
||||
* <p>这条只证"IFNULL 写了",证不了 MySQL 那半边语义——
|
||||
* {@code COUNT(DISTINCT a,b,c)} 会**跳过任一表达式为 NULL 的行**,少了 IFNULL
|
||||
* 存量未标注的行整个不计、未读组数少报。那半边要靠上线后一条现网只读 SQL 复量
|
||||
* (见 V158 第 5 节的验证语句)。
|
||||
*/
|
||||
@Test
|
||||
void unreadGroupCountGuardsNullSubjectWithIfnull() {
|
||||
when(mapper.selectMaps(any())).thenReturn(List.of(Map.of("group_count", 7)));
|
||||
|
||||
assertThat(service.unreadGroupCount(24L, NotificationService.AUDIENCE_ADMIN)).isEqualTo(7L);
|
||||
|
||||
ArgumentCaptor<com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<UserNotificationEntity>> captor =
|
||||
ArgumentCaptor.forClass(com.baomidou.mybatisplus.core.conditions.query.QueryWrapper.class);
|
||||
verify(mapper).selectMaps(captor.capture());
|
||||
assertThat(captor.getValue().getSqlSelect())
|
||||
.contains("COUNT(DISTINCT scene, DATE(created_at), IFNULL(subject_user_id, -1))");
|
||||
}
|
||||
|
||||
/** 读不到值 ≠ 0:桩成空结果时必须能区分(否则"没数"会被报成"没有未读")。 */
|
||||
@Test
|
||||
void unreadGroupCountDistinguishesNoReadingFromZero() {
|
||||
when(mapper.selectMaps(any())).thenReturn(List.of());
|
||||
assertThat(service.unreadGroupCount(24L, NotificationService.AUDIENCE_ADMIN)).isZero();
|
||||
when(mapper.selectMaps(any())).thenReturn(List.of(Map.of("group_count", 0)));
|
||||
assertThat(service.unreadGroupCount(24L, NotificationService.AUDIENCE_ADMIN)).isZero();
|
||||
}
|
||||
}
|
||||
@@ -209,6 +209,7 @@ export const API_ENDPOINTS = {
|
||||
notification: {
|
||||
summary: '/api/notifications/summary',
|
||||
list: '/api/notifications',
|
||||
groups: '/api/notifications/groups',
|
||||
read: '/api/notifications/{id}/read',
|
||||
readAll: '/api/notifications/read-all',
|
||||
},
|
||||
|
||||
@@ -57,9 +57,38 @@ export interface NotificationPage {
|
||||
|
||||
export interface NotificationSummary {
|
||||
unreadCount: number
|
||||
/** 有未读的聚合组数;徽标用它。unreadCount 仍是"条数",给明细与老客户端用。 */
|
||||
unreadGroupCount?: number
|
||||
latestId: number
|
||||
}
|
||||
|
||||
/** 聚合组:一个「场景 × 自然日」折成的一行(桌面端的主体用户就是本人,故不进分组键的可见维度)。 */
|
||||
export interface NotificationGroup {
|
||||
latestId: number
|
||||
scene: string
|
||||
category: string
|
||||
day: string
|
||||
subjectUserId: number | null
|
||||
rowCount: number
|
||||
unreadCount: number
|
||||
level: string
|
||||
title: string
|
||||
content: string
|
||||
createdAt: string | null
|
||||
}
|
||||
|
||||
export interface NotificationGroupPage {
|
||||
groups: NotificationGroup[]
|
||||
/** 组数(分页分母)。 */
|
||||
total: number
|
||||
/** 折叠前的明细条数——与 total 同屏,否则「共 12 条」会被读成只有 12 条通知。 */
|
||||
rowCount: number
|
||||
page: number
|
||||
pageSize: number
|
||||
unreadGroupCount: number
|
||||
unreadCount: number
|
||||
}
|
||||
|
||||
/** 铃铛轮询:未读数 + 最新通知 id(latestId 增大表示有新通知)。 */
|
||||
export function fetchNotificationSummary() {
|
||||
return unwrapJavaResponse(
|
||||
@@ -79,6 +108,13 @@ export interface NotificationListParams {
|
||||
category?: string
|
||||
startDate?: string
|
||||
endDate?: string
|
||||
/** 展开聚合组:两个条件取自该组自己返回的值,原样回传(空表示不限制)。 */
|
||||
scene?: string
|
||||
day?: string
|
||||
/** 主体用户:同场景同一天可能有好几个用户的事件,展开一组时必须把这一维也带上。 */
|
||||
subjectUserId?: number | null
|
||||
/** true 表示展开的是「未标注主体」那一组(改动上线前的存量行),与 subjectUserId 互斥。 */
|
||||
subjectUnlabelled?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -108,6 +144,18 @@ export function buildNotificationListQuery(
|
||||
if (params.endDate) {
|
||||
query.endDate = params.endDate
|
||||
}
|
||||
if (params.scene) {
|
||||
query.scene = params.scene
|
||||
}
|
||||
if (params.day) {
|
||||
query.day = params.day
|
||||
}
|
||||
if (params.subjectUserId !== null && params.subjectUserId !== undefined) {
|
||||
query.subjectUserId = params.subjectUserId
|
||||
}
|
||||
if (params.subjectUnlabelled) {
|
||||
query.subjectUnlabelled = 'true'
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
@@ -119,6 +167,15 @@ export function fetchNotificationList(params: NotificationListParams = {}) {
|
||||
)
|
||||
}
|
||||
|
||||
/** 聚合列表(铃铛默认视图)。分页按组切。 */
|
||||
export function fetchNotificationGroups(params: NotificationListParams = {}) {
|
||||
return unwrapJavaResponse(
|
||||
get<JavaApiResponse<NotificationGroupPage>>(
|
||||
buildJavaUrl(API_ENDPOINTS.notification.groups, buildNotificationListQuery(params)),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
export function markNotificationRead(id: number) {
|
||||
return unwrapJavaResponse(
|
||||
post<JavaApiResponse<boolean>>(
|
||||
|
||||
@@ -144,7 +144,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="loading && !items.length" class="bell-skeleton" aria-label="正在加载">
|
||||
<div v-if="loading && !groups.length" class="bell-skeleton" aria-label="正在加载">
|
||||
<div v-for="row in 3" :key="row" class="bell-skeleton-row">
|
||||
<span class="bell-skeleton-icon"></span>
|
||||
<span class="bell-skeleton-lines">
|
||||
@@ -154,7 +154,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="loadError && !items.length" class="bell-state">
|
||||
<div v-else-if="loadError && !groups.length" class="bell-state">
|
||||
<span class="bell-state-icon bell-state-icon--error" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
@@ -166,7 +166,7 @@
|
||||
<button type="button" class="bell-state-action" @click="reload">重新加载</button>
|
||||
</div>
|
||||
|
||||
<div v-else-if="!items.length" class="bell-state">
|
||||
<div v-else-if="!groups.length" class="bell-state">
|
||||
<span class="bell-state-icon" aria-hidden="true">
|
||||
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" />
|
||||
@@ -178,71 +178,62 @@
|
||||
</div>
|
||||
|
||||
<ul v-else class="bell-list">
|
||||
<template v-for="group in groupedItems" :key="group.day || 'unknown'">
|
||||
<li class="bell-day-head">{{ group.label }}</li>
|
||||
<template v-for="(group, index) in groups" :key="notificationGroupKey(group)">
|
||||
<li v-if="startsNewDay(index)" class="bell-day-head">{{ formatDayLabel(group.day) }}</li>
|
||||
<li
|
||||
v-for="item in group.items"
|
||||
:key="item.id"
|
||||
class="bell-item"
|
||||
:class="[`bell-item--${itemLevel(item)}`, { 'bell-item--unread': !item.read }]"
|
||||
@click="onItemClick(item)"
|
||||
class="bell-item bell-group"
|
||||
:class="[`bell-item--${itemLevel(group)}`, { 'bell-group--open': isExpanded(group) }]"
|
||||
@click="toggleGroup(group)"
|
||||
>
|
||||
<span class="bell-item-icon" aria-hidden="true">
|
||||
<svg
|
||||
v-if="itemLevel(item) === 'error'"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
|
||||
<path d="M12 9v4" />
|
||||
<path d="M12 17h.01" />
|
||||
</svg>
|
||||
<svg
|
||||
v-else-if="itemLevel(item) === 'info'"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M12 11v5" />
|
||||
<path d="M12 8h.01" />
|
||||
</svg>
|
||||
<svg
|
||||
v-else
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M12 8v4" />
|
||||
<path d="M12 16h.01" />
|
||||
</svg>
|
||||
</span>
|
||||
<NotificationLevelIcon :level="itemLevel(group)" />
|
||||
<div class="bell-item-main">
|
||||
<div class="bell-item-head">
|
||||
<span class="bell-item-title" :title="item.title">{{ item.title }}</span>
|
||||
<span class="bell-item-dot" :class="{ 'bell-item-dot--on': !item.read }" aria-hidden="true"></span>
|
||||
<span class="bell-item-time">{{ formatTime(item.createdAt) }}</span>
|
||||
<span class="bell-item-title" :title="group.title">{{ group.title }}</span>
|
||||
<span
|
||||
class="bell-item-dot"
|
||||
:class="{ 'bell-item-dot--on': group.unreadCount > 0 }"
|
||||
aria-hidden="true"
|
||||
></span>
|
||||
<span class="bell-item-time">{{ formatTime(group.createdAt) }}</span>
|
||||
</div>
|
||||
<p class="bell-item-content" :title="group.content">{{ group.content }}</p>
|
||||
<div class="bell-group-foot">
|
||||
<span class="bell-group-count">{{ formatGroupCounts(group.rowCount, group.unreadCount) }}</span>
|
||||
<span class="bell-group-toggle">{{ isExpanded(group) ? '收起明细' : '展开明细' }}</span>
|
||||
</div>
|
||||
<p class="bell-item-content" :title="item.content">{{ item.content }}</p>
|
||||
</div>
|
||||
</li>
|
||||
<!-- 已读只能进明细逐条点:聚合行上的点击只做展开,避免"看一眼顺手把没看过的全标成已读" -->
|
||||
<template v-if="isExpanded(group)">
|
||||
<li v-if="detailLoading" class="bell-detail-state">正在加载明细...</li>
|
||||
<li v-else-if="!details.length" class="bell-detail-state">这一组里没有通知</li>
|
||||
<li
|
||||
v-for="item in details"
|
||||
:key="item.id"
|
||||
class="bell-item bell-item--detail"
|
||||
:class="[`bell-item--${itemLevel(item)}`, { 'bell-item--unread': !item.read }]"
|
||||
@click="onItemClick(item)"
|
||||
>
|
||||
<NotificationLevelIcon :level="itemLevel(item)" />
|
||||
<div class="bell-item-main">
|
||||
<div class="bell-item-head">
|
||||
<span class="bell-item-title" :title="item.title">{{ item.title }}</span>
|
||||
<span class="bell-item-dot" :class="{ 'bell-item-dot--on': !item.read }" aria-hidden="true"></span>
|
||||
<span class="bell-item-time">{{ formatTime(item.createdAt) }}</span>
|
||||
</div>
|
||||
<p class="bell-item-content" :title="item.content">{{ item.content }}</p>
|
||||
</div>
|
||||
</li>
|
||||
<li v-if="!detailLoading && detailTotal > details.length" class="bell-detail-state">
|
||||
另有 {{ detailTotal - details.length }} 条未列出,可缩小时间范围后查看
|
||||
</li>
|
||||
</template>
|
||||
</template>
|
||||
</ul>
|
||||
|
||||
<footer class="bell-foot">
|
||||
<div class="bell-foot-meta">
|
||||
<span class="bell-foot-total">共 {{ total }} 条</span>
|
||||
<span class="bell-foot-total">共 {{ total }} 组 · 明细 {{ rowCount }} 条</span>
|
||||
<select
|
||||
v-model="pageSize"
|
||||
class="bell-size-select"
|
||||
@@ -279,29 +270,23 @@
|
||||
|
||||
<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,
|
||||
fetchNotificationList,
|
||||
fetchNotificationSummary,
|
||||
markAllNotificationsRead,
|
||||
markNotificationRead,
|
||||
type NotificationItem,
|
||||
} from '@/shared/api/types/modules/notification.ts'
|
||||
PANEL_PAGE_SIZES as PAGE_SIZES,
|
||||
itemLevel,
|
||||
startsNewDay as groupStartsNewDay,
|
||||
useNotificationBellPanel,
|
||||
} from '@/shared/composables/useNotificationBellPanel'
|
||||
import {
|
||||
NOTIFICATION_POLL_INTERVAL_MS,
|
||||
currentNotificationUid,
|
||||
formatDayLabel,
|
||||
formatGroupCounts,
|
||||
formatNotificationTime,
|
||||
formatUnreadBadge,
|
||||
groupNotificationsByDay,
|
||||
hasNewNotification,
|
||||
readLastNotifiedId,
|
||||
writeLastNotifiedId,
|
||||
} from '@/shared/utils/notification-bell.ts'
|
||||
|
||||
const DEFAULT_PAGE_SIZE = 10
|
||||
const PAGE_SIZES = [10, 20, 50, 100]
|
||||
notificationGroupKey,
|
||||
} from '@/shared/utils/notification-bell'
|
||||
|
||||
/** 顶栏主题:工具页/配置页深色(dark),桌面入口首页浅色(light)。 */
|
||||
const props = withDefaults(defineProps<{ theme?: 'dark' | 'light' }>(), {
|
||||
@@ -309,167 +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 items = ref<NotificationItem[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
/** 每页条数(面板底部下拉,取值同后台列表分页 10/20/50/100)。 */
|
||||
const pageSize = ref(DEFAULT_PAGE_SIZE)
|
||||
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(unreadCount.value))
|
||||
const unreadChipText = computed(() =>
|
||||
unreadCount.value > 99 ? '99+ 条未读' : `${unreadCount.value} 条未读`,
|
||||
)
|
||||
const groupedItems = computed(() => groupNotificationsByDay(items.value))
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))
|
||||
const hasFilter = computed(() =>
|
||||
Boolean(keyword.value.trim() || dateRange.value || category.value),
|
||||
)
|
||||
const badgeText = computed(() => formatUnreadBadge(badgeCount.value))
|
||||
const unreadChipText = computed(() => {
|
||||
const count = unreadGroupCount.value
|
||||
return count > 99 ? '99+ 组未读' : `${count} 组未读`
|
||||
})
|
||||
|
||||
let pollTimer: number | null = null
|
||||
let searchTimer: number | null = null
|
||||
|
||||
/** 通知级别:后端只保证三类,非法值按 warning 兜底(配色与图标按级别区分)。 */
|
||||
function itemLevel(item: NotificationItem): 'error' | 'warning' | 'info' {
|
||||
return item.level === 'error' || item.level === 'info' ? item.level : 'warning'
|
||||
/** 模板里仍是 startsNewDay(index):组序列在面板层,这里只补一次取值。 */
|
||||
function startsNewDay(index: number): boolean {
|
||||
return groupStartsNewDay(groups.value, index)
|
||||
}
|
||||
|
||||
/** 起止日期倒挂时自动交换,避免用户只看到「没有符合条件的通知」不知原因。 */
|
||||
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)
|
||||
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 fetchNotificationList({
|
||||
page: targetPage,
|
||||
pageSize: pageSize.value,
|
||||
keyword: keyword.value,
|
||||
category: category.value,
|
||||
...normalizedDayRange(),
|
||||
})
|
||||
const list = Array.isArray(result?.items) ? result.items : []
|
||||
items.value = list
|
||||
total.value = Number(result?.total ?? list.length)
|
||||
unreadCount.value = Number(result?.unreadCount ?? unreadCount.value)
|
||||
page.value = targetPage
|
||||
loadError.value = ''
|
||||
// 无筛选时首页就是最新数据,顺带记录「已提醒过的最大 id」;有筛选时最新 id 不代表真实最新
|
||||
if (targetPage <= 1 && !hasFilter.value && list.length) {
|
||||
const latest = Number(list[0].id)
|
||||
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 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 定位,位置按触发器实时算(右对齐在铃铛下方)。 */
|
||||
@@ -493,45 +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)
|
||||
} 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 item of items.value) {
|
||||
item.read = true
|
||||
}
|
||||
unreadCount.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
|
||||
@@ -553,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)
|
||||
})
|
||||
|
||||
@@ -578,10 +429,6 @@ onUnmounted(() => {
|
||||
window.clearInterval(pollTimer)
|
||||
pollTimer = null
|
||||
}
|
||||
if (searchTimer != null) {
|
||||
window.clearTimeout(searchTimer)
|
||||
searchTimer = null
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -983,6 +830,54 @@ onUnmounted(() => {
|
||||
background: var(--bell-unread-bg);
|
||||
}
|
||||
|
||||
/* ---- 聚合行(一级)与明细行(二级)---- */
|
||||
.bell-group--open {
|
||||
background: var(--bell-hover);
|
||||
}
|
||||
|
||||
.bell-group-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.bell-group-count {
|
||||
color: var(--bell-text-mute);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.bell-group-toggle {
|
||||
flex: 0 0 auto;
|
||||
color: var(--bell-accent);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* 明细缩进 + 左侧一道竖线:看得出"这是上面那一组里的东西",而不是又一批同级通知 */
|
||||
.bell-item--detail {
|
||||
padding-left: 30px;
|
||||
}
|
||||
|
||||
.bell-item--detail::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
bottom: 0;
|
||||
left: 18px;
|
||||
width: 2px;
|
||||
border-radius: 2px;
|
||||
background: var(--bell-border);
|
||||
}
|
||||
|
||||
.bell-detail-state {
|
||||
padding: 12px 16px;
|
||||
color: var(--bell-text-mute);
|
||||
font-size: 12px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.bell-item-icon {
|
||||
display: inline-flex;
|
||||
flex: 0 0 auto;
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
<template>
|
||||
<span class="bell-item-icon" aria-hidden="true">
|
||||
<svg
|
||||
v-if="level === 'error'"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
|
||||
<path d="M12 9v4" />
|
||||
<path d="M12 17h.01" />
|
||||
</svg>
|
||||
<svg
|
||||
v-else-if="level === 'info'"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M12 11v5" />
|
||||
<path d="M12 8h.01" />
|
||||
</svg>
|
||||
<svg
|
||||
v-else
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<circle cx="12" cy="12" r="9" />
|
||||
<path d="M12 8v4" />
|
||||
<path d="M12 16h.01" />
|
||||
</svg>
|
||||
</span>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 通知级别图标:聚合行与明细行都要用,抽出来免得同一组 svg 抄两遍
|
||||
* (抄两遍的结局是以后只改了一处,两类行的图标开始不一致)。
|
||||
*
|
||||
* <p>外圈那个圆的底色/描边色由父级按级别给(.bell-item--unread.bell-item--error .bell-item-icon),
|
||||
* 这里只负责形状与尺寸——父组件的 scoped 属性会落到本组件根节点上,所以那几条配色规则照旧命中。
|
||||
*/
|
||||
defineProps<{ level: 'error' | 'warning' | 'info' }>()
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.bell-item-icon svg {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
}
|
||||
</style>
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -96,30 +96,28 @@ export function formatDayLabel(day: string, now: Date = new Date()): string {
|
||||
return `${year}年${month}月${date}日`
|
||||
}
|
||||
|
||||
export interface NotificationDayGroup<T> {
|
||||
day: string
|
||||
label: string
|
||||
items: T[]
|
||||
/**
|
||||
* 聚合组的稳定键:场景 × 自然日 × 事件主体用户,与后端 groups 出口的分组键逐字对应。
|
||||
* 主体为空也要参与拼键,否则两组会撞成同一个 key,展开态串台。
|
||||
*/
|
||||
export function notificationGroupKey(group: {
|
||||
scene?: string | null
|
||||
day?: string | null
|
||||
subjectUserId?: number | string | null
|
||||
}): string {
|
||||
const subject =
|
||||
group.subjectUserId === null || group.subjectUserId === undefined ? 'none' : String(group.subjectUserId)
|
||||
return `${group.scene ?? ''}|${group.day ?? ''}|${subject}`
|
||||
}
|
||||
|
||||
/** 按年月日分组(组内保持入参顺序,列表本身已按 id 倒序)。 */
|
||||
export function groupNotificationsByDay<T extends { createdAt: string | null }>(
|
||||
items: T[],
|
||||
now: Date = new Date(),
|
||||
): NotificationDayGroup<T>[] {
|
||||
const groups: NotificationDayGroup<T>[] = []
|
||||
const indexByDay = new Map<string, NotificationDayGroup<T>>()
|
||||
for (const item of items ?? []) {
|
||||
const day = notificationDayKey(item.createdAt)
|
||||
let group = indexByDay.get(day)
|
||||
if (!group) {
|
||||
group = { day, label: formatDayLabel(day, now), items: [] }
|
||||
indexByDay.set(day, group)
|
||||
groups.push(group)
|
||||
}
|
||||
group.items.push(item)
|
||||
}
|
||||
return groups
|
||||
/** 组行上的计数徽语:折叠前几条、其中几条没读。只报一个数就会被读成"一共就这些通知"。 */
|
||||
export function formatGroupCounts(
|
||||
rowCount: number | null | undefined,
|
||||
unreadCount: number | null | undefined,
|
||||
): string {
|
||||
const total = Number(rowCount ?? 0)
|
||||
const unread = Number(unreadCount ?? 0)
|
||||
return unread > 0 ? `${total} 条 · ${unread} 未读` : `${total} 条`
|
||||
}
|
||||
|
||||
/** 通知时间展示:今天只显示 HH:mm;昨天显示「昨天 HH:mm」;更早显示 MM-DD HH:mm。 */
|
||||
|
||||
@@ -24,7 +24,10 @@ const BASELINE = {
|
||||
// 同一批另两处(pywebview addEventListener 的外层兜底、isSessionExpiredNav 的外层兜底)挡的是
|
||||
// 不可能发生的事(内层 lsGet 已自带兜底、URLSearchParams 对字符串永不抛),本轮直接摘掉,
|
||||
// 所以这里只 +1 而不是 +3。静默数 silent 一格没动(仍 <=84),逐文件台账也对平。
|
||||
blocks: 298,
|
||||
// 299 = 298 + 桌面端铃铛 toggleGroup 的一支 try/catch(10-13 通知聚合改造):展开明细要单独发请求,
|
||||
// 失败写进面板内 loadError(与列表加载同一个可见出口,不弹全局打扰),改前是"点了没反应"。
|
||||
// silent 一格没涨:该支首条语句不是 console.*,且有可见出口。
|
||||
blocks: 299,
|
||||
// 298 = 296 + 全局错误出口 app-error.ts 的两支新 try/catch(10-09 装 app.config.errorHandler /
|
||||
// window.onerror / unhandledrejection 时引入),两支都不是"吞":
|
||||
// ① String(reason) 对无 toString 的对象/Symbol 会抛,兜法返回一句中文占位文本,
|
||||
@@ -32,7 +35,11 @@ const BASELINE = {
|
||||
// ② guardRun 挡的是"处理器自己崩了把页面带白屏",兜法是 console.error + 一次中文提示,
|
||||
// 且刻意不向上重抛(重抛会让 Vue 再进一次同一个处理器)。
|
||||
// silent 一格没涨(两支都有用户可见出口),台账无需新增条目。
|
||||
silent: 84,
|
||||
// 83 = 10-13 面板状态机拆进 useNotificationBellPanel.ts 后的实扫值(原 84)。
|
||||
// 拆分是为了 SFC 顶到可读棘轮的 800 行上限(1439 行 > 台账点名的 1318),不是冲静默来的:
|
||||
// 铃铛那两处"有意静默降级"(轮询失败不亮红点、列表失败在面板内给文案)整块搬进了新文件,
|
||||
// 逐文件台账跟着实况走——组件 3→0、新记 useNotificationBellPanel.ts=2,总数还比基线少 1。
|
||||
silent: 83,
|
||||
/** 逐文件台账:只钉总数与文件数两个标量的棘轮,会被「A 加一条 + B 减一条」整段绕过。 */
|
||||
perFile: {
|
||||
'src/pages/brand/components/BrandCollectDataTab.vue': 4,
|
||||
@@ -61,8 +68,9 @@ const BASELINE = {
|
||||
'src/shared/bridges/web-fallback.ts': 2,
|
||||
'src/shared/components/ApiSecretSettingsPanel.vue': 1,
|
||||
'src/shared/components/ExpiryNotice.vue': 2,
|
||||
'src/shared/components/NotificationBell.vue': 3,
|
||||
'src/shared/components/NotificationBell.vue': 0,
|
||||
'src/shared/composables/useLiveTaskBoard.ts': 1,
|
||||
'src/shared/composables/useNotificationBellPanel.ts': 2,
|
||||
'src/shared/composables/useTaskProgressLoop.ts': 3,
|
||||
'src/shared/composables/useVersionUpdate.ts': 1,
|
||||
'src/shared/dispatch-guard-ui.ts': 1,
|
||||
|
||||
@@ -317,6 +317,7 @@ test('test_endpoints_frozen_snapshot', () => {
|
||||
"notification": {
|
||||
"summary": "/api/notifications/summary",
|
||||
"list": "/api/notifications",
|
||||
"groups": "/api/notifications/groups",
|
||||
"read": "/api/notifications/{id}/read",
|
||||
"readAll": "/api/notifications/read-all"
|
||||
},
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
/**
|
||||
* 用户端首批组件挂载用例(四面9分口径 §2「错误静默 …;0 挂载测试」那一半句的执行证据)。
|
||||
* 用户端铃铛的组件挂载用例(四面9分口径 §2「错误静默 …;0 挂载测试」那一半句的执行证据)。
|
||||
*
|
||||
* 为什么是这三个靶子:本面 src 下的 vue 组件里"只 console 不给用户看"的 catch 实测 5 处,
|
||||
* 其中铃铛占 3 处(未读数轮询、列表加载、点通知标已读)。轮询与列表那两处是**有意**静默
|
||||
* (源码注释声明"不打扰用户",列表失败改在面板内给文案),所以这里钉的是"声明的意图真兑现";
|
||||
* 标已读那一处改前是真静默——点了通知没反应、行也没转已读,用户只能反复点,本轮改成可见。
|
||||
* 两组靶子:
|
||||
* ① 三处失败的用户可见性——本面 src 下的 vue 组件里"只 console 不给用户看"的 catch 实测 5 处,
|
||||
* 铃铛占 3 处(未读数轮询、组加载、点明细标已读)。轮询与组加载那两处是**有意**静默
|
||||
* (源码注释声明"不打扰用户",组加载失败改在面板内给文案),这里钉的是"声明的意图真兑现";
|
||||
* 标已读那一处改前是真静默——点了通知没反应、行也没转已读,用户只能反复点,本轮改成可见。
|
||||
* ② 10-13 聚合改造(场景 × 自然日 × 用户)带出来的三条口径:点聚合行只展开不标已读、
|
||||
* 红点按组数亮、组内没读完红点不许掉。这三条都只能在真组件上验,纯函数用例判不到 DOM 与状态联动。
|
||||
*
|
||||
* 跑真组件:真 api 桩、真 ElMessage 出口、真 DOM,判的是运行时行为,
|
||||
* 不是读源码的形状钉子(那类钉子在本仓已占 25% 用例,见 §2 后管同源问题)。
|
||||
@@ -12,7 +15,7 @@
|
||||
* ⚠ 面板是 `<Teleport to="body">`:每支用例都必须 unmount 并清 body,
|
||||
* 否则上一支留下的 `.bell-item--unread` 会被这一支的 document 查询捡到。
|
||||
*
|
||||
* 跑法:`npx vitest run --root frontend-vue`
|
||||
* 跑法:`npx vitest run --config vitest.config.ts`(在 frontend-vue 目录下)
|
||||
*/
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
|
||||
@@ -28,6 +31,7 @@ const message = vi.hoisted(() => ({
|
||||
}))
|
||||
const api = vi.hoisted(() => ({
|
||||
fetchNotificationSummary: vi.fn(),
|
||||
fetchNotificationGroups: vi.fn(),
|
||||
fetchNotificationList: vi.fn(),
|
||||
markNotificationRead: vi.fn(),
|
||||
markAllNotificationsRead: vi.fn(),
|
||||
@@ -37,6 +41,7 @@ vi.mock('element-plus', () => ({ ElMessage: message }))
|
||||
vi.mock('@/shared/api/types/modules/notification.ts', () => ({
|
||||
NOTIFICATION_CATEGORY_OPTIONS: [],
|
||||
fetchNotificationSummary: api.fetchNotificationSummary,
|
||||
fetchNotificationGroups: api.fetchNotificationGroups,
|
||||
fetchNotificationList: api.fetchNotificationList,
|
||||
markAllNotificationsRead: api.markAllNotificationsRead,
|
||||
markNotificationRead: api.markNotificationRead,
|
||||
@@ -52,6 +57,22 @@ const notification = (over: Record<string, unknown> = {}) => ({
|
||||
...over,
|
||||
})
|
||||
|
||||
/** 聚合行:一条组 = 场景 × 自然日 × 主体用户,rowCount 是折叠前的明细条数。 */
|
||||
const group = (over: Record<string, unknown> = {}) => ({
|
||||
latestId: 7,
|
||||
scene: 'brand_check_failed',
|
||||
category: 'task_error',
|
||||
day: '2026-09-13',
|
||||
subjectUserId: 1160,
|
||||
rowCount: 1,
|
||||
unreadCount: 1,
|
||||
level: 'error',
|
||||
title: '品牌检测服务挂了',
|
||||
content: '上游 503',
|
||||
createdAt: new Date().toISOString(),
|
||||
...over,
|
||||
})
|
||||
|
||||
let wrapper: VueWrapper | null = null
|
||||
|
||||
/** 打开面板:触发 togglePanel ⇒ 内部 void loadPage(1),靠 flushPromises 等它落地。 */
|
||||
@@ -63,22 +84,44 @@ async function openPanel() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 点第一条通知。⚠ 面板是 Teleport 到 body 的,`wrapper.find()` 看不见里面的节点
|
||||
* (实测 wrapper 查 `.bell-item` 得到空 wrapper 而 document 里那一行确实在)
|
||||
* ⇒ 一律从 document 取节点、用原生 click 触发,Vue 的 @click 监听挂在元素上,照样生效。
|
||||
* 从 document 取节点、用原生 click 触发:面板是 Teleport 到 body 的,
|
||||
* `wrapper.find()` 看不见里面的节点(实测 wrapper 查 `.bell-item` 得到空 wrapper
|
||||
* 而 document 里那一行确实在),而 Vue 的 @click 监听挂在元素上,原生 click 照样生效。
|
||||
*/
|
||||
function clickFirstRow() {
|
||||
const row = document.querySelector<HTMLElement>('.bell-item')
|
||||
expect(row, '面板里没有可点的通知行').not.toBeNull()
|
||||
function clickElement(selector: string) {
|
||||
const row = document.querySelector<HTMLElement>(selector)
|
||||
expect(row, `面板里没有可点的 ${selector}`).not.toBeNull()
|
||||
row!.click()
|
||||
}
|
||||
|
||||
/** 展开第一个聚合行:聚合行上的点击只做展开,明细行才是要点的那些。 */
|
||||
async function expandFirstGroup() {
|
||||
clickElement('.bell-group')
|
||||
await flushPromises()
|
||||
}
|
||||
|
||||
/**
|
||||
* 红点取自 wrapper 而不是 document:`mount()` 不挂 attachTo,组件自身(含 .bell-trigger 与
|
||||
* 它里面的 .bell-badge)渲染在游离节点上,只有 Teleport 到 body 的面板才能在 document 里查到。
|
||||
*/
|
||||
function badgeText(): string | null {
|
||||
const badge = wrapper?.find('.bell-badge')
|
||||
return badge && badge.exists() ? badge.text() : null
|
||||
}
|
||||
|
||||
describe('NotificationBell:三处失败的用户可见性', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = ''
|
||||
localStorage.clear()
|
||||
api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 1, latestId: 7 })
|
||||
api.fetchNotificationList.mockResolvedValue({ items: [notification()], total: 1, unreadCount: 1 })
|
||||
api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 1, unreadGroupCount: 1, latestId: 7 })
|
||||
api.fetchNotificationGroups.mockResolvedValue({
|
||||
groups: [group()],
|
||||
total: 1,
|
||||
rowCount: 1,
|
||||
unreadGroupCount: 1,
|
||||
unreadCount: 1,
|
||||
})
|
||||
api.fetchNotificationList.mockResolvedValue({ items: [notification()], total: 1 })
|
||||
api.markNotificationRead.mockResolvedValue(undefined)
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
@@ -92,12 +135,13 @@ describe('NotificationBell:三处失败的用户可见性', () => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('点通知标已读失败:必须给一条带原因的错误提示,且不许把这一行冒充成已读', async () => {
|
||||
it('点明细标已读失败:必须给一条带原因的错误提示,且不许把这一行冒充成已读', async () => {
|
||||
api.markNotificationRead.mockRejectedValue(new Error('403 Forbidden'))
|
||||
await openPanel()
|
||||
expect(document.querySelectorAll('.bell-item')).toHaveLength(1)
|
||||
await expandFirstGroup()
|
||||
expect(document.querySelectorAll('.bell-item--detail')).toHaveLength(1)
|
||||
|
||||
clickFirstRow()
|
||||
clickElement('.bell-item--detail')
|
||||
await flushPromises()
|
||||
|
||||
expect(message.error).toHaveBeenCalledTimes(1)
|
||||
@@ -108,12 +152,13 @@ describe('NotificationBell:三处失败的用户可见性', () => {
|
||||
|
||||
it('反向钉:标已读成功时不产生任何提示,而这一行要真的转为已读', async () => {
|
||||
await openPanel()
|
||||
await expandFirstGroup()
|
||||
// 挂载那一轮 refreshSummary 发现"有新通知"本来就会弹一条 warning(既有设计,不是缺陷),
|
||||
// 所以先把账清掉——本用例判的是"点成功这个动作"不许再产生提示。
|
||||
message.error.mockClear()
|
||||
message.warning.mockClear()
|
||||
|
||||
clickFirstRow()
|
||||
clickElement('.bell-item--detail')
|
||||
await flushPromises()
|
||||
|
||||
expect(message.error).not.toHaveBeenCalled()
|
||||
@@ -121,8 +166,8 @@ describe('NotificationBell:三处失败的用户可见性', () => {
|
||||
expect(document.querySelector('.bell-item--unread')).toBeNull()
|
||||
})
|
||||
|
||||
it('列表加载失败:文案进面板本身,而不是弹一条全局消息打扰用户', async () => {
|
||||
api.fetchNotificationList.mockRejectedValue(new Error('502 Bad Gateway'))
|
||||
it('组加载失败:文案进面板本身,而不是弹一条全局消息打扰用户', async () => {
|
||||
api.fetchNotificationGroups.mockRejectedValue(new Error('502 Bad Gateway'))
|
||||
await openPanel()
|
||||
|
||||
expect(document.body.textContent).toContain('502 Bad Gateway')
|
||||
@@ -130,3 +175,113 @@ describe('NotificationBell:三处失败的用户可见性', () => {
|
||||
expect(document.querySelectorAll('.bell-item')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('NotificationBell:聚合两级与红点口径', () => {
|
||||
beforeEach(() => {
|
||||
document.body.innerHTML = ''
|
||||
localStorage.clear()
|
||||
api.fetchNotificationSummary.mockResolvedValue({ unreadCount: 2, unreadGroupCount: 1, latestId: 7 })
|
||||
api.fetchNotificationGroups.mockResolvedValue({
|
||||
groups: [group({ latestId: 13, rowCount: 3, unreadCount: 2 })],
|
||||
total: 1,
|
||||
rowCount: 3,
|
||||
unreadGroupCount: 1,
|
||||
unreadCount: 2,
|
||||
})
|
||||
api.fetchNotificationList.mockResolvedValue({
|
||||
items: [notification({ id: 11 }), notification({ id: 12 }), notification({ id: 13, read: true })],
|
||||
total: 3,
|
||||
})
|
||||
api.markNotificationRead.mockResolvedValue(undefined)
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
wrapper?.unmount()
|
||||
wrapper = null
|
||||
document.body.innerHTML = ''
|
||||
vi.restoreAllMocks()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('点聚合行只展开:一次都不许替用户把通知标成已读', async () => {
|
||||
await openPanel()
|
||||
// 折叠态:面板里只有组行,一条明细都不该出现(明细要用户主动展开才拉)
|
||||
expect(document.querySelectorAll('.bell-group')).toHaveLength(1)
|
||||
expect(document.querySelectorAll('.bell-item--detail')).toHaveLength(0)
|
||||
|
||||
await expandFirstGroup()
|
||||
|
||||
expect(api.markNotificationRead).not.toHaveBeenCalled()
|
||||
expect(api.fetchNotificationList).toHaveBeenCalledTimes(1)
|
||||
// 下钻必须带上第三维(主体用户):同场景同一天里小魏11 与小魏17 是两组,
|
||||
// 只按 scene+day 查会把两家的行都捞进同一份明细。
|
||||
expect(api.fetchNotificationList.mock.calls[0][0]).toMatchObject({
|
||||
scene: 'brand_check_failed',
|
||||
day: '2026-09-13',
|
||||
subjectUserId: 1160,
|
||||
})
|
||||
expect(api.fetchNotificationList.mock.calls[0][0].subjectUnlabelled).toBe(false)
|
||||
expect(document.querySelectorAll('.bell-item--detail')).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('展开「未标注主体」那一组:按 IS NULL 查,不许把有主体的行混进来', async () => {
|
||||
api.fetchNotificationGroups.mockResolvedValue({
|
||||
groups: [group({ subjectUserId: null, rowCount: 2, unreadCount: 2 })],
|
||||
total: 1,
|
||||
rowCount: 2,
|
||||
unreadGroupCount: 1,
|
||||
unreadCount: 2,
|
||||
})
|
||||
await openPanel()
|
||||
await expandFirstGroup()
|
||||
|
||||
const sent = api.fetchNotificationList.mock.calls[0][0]
|
||||
expect(sent.subjectUnlabelled).toBe(true)
|
||||
expect(sent.subjectUserId).toBeNull()
|
||||
})
|
||||
|
||||
it('红点按组数亮、明细条数同屏:一组两条未读也不会亮成"2"', async () => {
|
||||
await openPanel()
|
||||
|
||||
expect(badgeText()).toBe('1')
|
||||
expect(document.querySelector('.bell-unread-chip')?.textContent).toContain('1 组未读')
|
||||
// 组数与条数必须同时在屏上,只给一个数就会被读成"一共就这些通知"
|
||||
expect(document.querySelector('.bell-foot-total')?.textContent).toContain('共 1 组')
|
||||
expect(document.querySelector('.bell-foot-total')?.textContent).toContain('明细 3 条')
|
||||
expect(document.querySelector('.bell-group-count')?.textContent).toBe('3 条 · 2 未读')
|
||||
})
|
||||
|
||||
it('组内还有未读时红点不许掉,读完最后一条才掉', async () => {
|
||||
await openPanel()
|
||||
await expandFirstGroup()
|
||||
|
||||
clickElement('.bell-item--detail.bell-item--unread')
|
||||
await flushPromises()
|
||||
expect(api.markNotificationRead).toHaveBeenCalledTimes(1)
|
||||
expect(badgeText()).toBe('1')
|
||||
// 判组数必须看 chip:徽标在 unreadGroupCount 为 0 时会退回条数(兼容没给新字段的旧后端),
|
||||
// 只钉徽标的话"组内没读完就把组数减掉"这条回归会被那层兜底盖住(变异自证 M2 实测存活过一次)。
|
||||
expect(document.querySelector('.bell-unread-chip')?.textContent).toContain('1 组未读')
|
||||
|
||||
clickElement('.bell-item--detail.bell-item--unread')
|
||||
await flushPromises()
|
||||
expect(api.markNotificationRead).toHaveBeenCalledTimes(2)
|
||||
// 这一组的两条未读都读完了:组数从 1 掉到 0,红点与"组未读"字样一起消失
|
||||
expect(document.querySelector('.bell-badge')).toBeNull()
|
||||
expect(document.querySelector('.bell-unread-chip')).toBeNull()
|
||||
})
|
||||
|
||||
it('明细超出上限时说明还剩多少,不许让用户以为这就是全部', async () => {
|
||||
api.fetchNotificationList.mockResolvedValue({
|
||||
items: Array.from({ length: 50 }, (_, i) => notification({ id: 100 + i })),
|
||||
total: 60,
|
||||
})
|
||||
await openPanel()
|
||||
await expandFirstGroup()
|
||||
|
||||
expect(document.querySelectorAll('.bell-item--detail')).toHaveLength(50)
|
||||
expect(document.querySelector('.bell-detail-state')?.textContent).toContain('另有 10 条未列出')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,7 +3,9 @@ import assert from 'node:assert/strict'
|
||||
import {
|
||||
formatNotificationTime,
|
||||
formatUnreadBadge,
|
||||
groupNotificationsByDay,
|
||||
formatDayLabel,
|
||||
formatGroupCounts,
|
||||
notificationGroupKey,
|
||||
hasNewNotification,
|
||||
readLastNotifiedId,
|
||||
writeLastNotifiedId,
|
||||
@@ -90,52 +92,6 @@ test('formatNotificationTime 今天/昨天/更早展示', () => {
|
||||
assert.equal(formatNotificationTime('not-a-date', now), '')
|
||||
})
|
||||
|
||||
test('groupNotificationsByDay 按年月日分组:今天/昨天/更早,组内保持原顺序', () => {
|
||||
const now = new Date(2026, 8, 13, 15, 30)
|
||||
const items = [
|
||||
{ id: 4, createdAt: new Date(2026, 8, 13, 15, 0).toISOString() },
|
||||
{ id: 3, createdAt: new Date(2026, 8, 13, 9, 0).toISOString() },
|
||||
{ id: 2, createdAt: new Date(2026, 8, 12, 23, 0).toISOString() },
|
||||
{ id: 1, createdAt: new Date(2026, 8, 1, 8, 0).toISOString() },
|
||||
]
|
||||
|
||||
const groups = groupNotificationsByDay(items, now)
|
||||
|
||||
assert.equal(groups.length, 3)
|
||||
assert.deepEqual(
|
||||
groups.map((group) => [group.day, group.label]),
|
||||
[
|
||||
['2026-09-13', '今天'],
|
||||
['2026-09-12', '昨天'],
|
||||
['2026-09-01', '2026年9月1日'],
|
||||
],
|
||||
)
|
||||
assert.deepEqual(
|
||||
groups[0].items.map((item) => item.id),
|
||||
[4, 3],
|
||||
'同一天的多条合为一组且保持倒序',
|
||||
)
|
||||
})
|
||||
|
||||
test('groupNotificationsByDay 时间缺失/非法归入未知时间组', () => {
|
||||
const now = new Date(2026, 8, 13, 15, 30)
|
||||
const groups = groupNotificationsByDay(
|
||||
[
|
||||
{ id: 2, createdAt: null },
|
||||
{ id: 1, createdAt: 'not-a-date' },
|
||||
],
|
||||
now,
|
||||
)
|
||||
|
||||
assert.equal(groups.length, 1)
|
||||
assert.equal(groups[0].day, '')
|
||||
assert.equal(groups[0].label, '未知时间')
|
||||
assert.deepEqual(
|
||||
groups[0].items.map((item) => item.id),
|
||||
[2, 1],
|
||||
)
|
||||
})
|
||||
|
||||
test('buildNotificationListQuery:关键字去空白、空条件不下发、分类与日期原样透传', () => {
|
||||
assert.deepEqual(buildNotificationListQuery(), { page: 1, pageSize: 20, onlyUnread: 'false' })
|
||||
|
||||
@@ -180,3 +136,35 @@ test('类型筛选项覆盖后端四个大类且标签非空', () => {
|
||||
assert.ok(option.label.trim().length > 0, `分类 ${option.value} 缺中文标签`)
|
||||
}
|
||||
})
|
||||
|
||||
test('notificationGroupKey 聚合组键:三维各自都能把两组分开', () => {
|
||||
const base = { scene: 'task_partial', day: '2026-09-13', subjectUserId: 1160 }
|
||||
assert.notEqual(notificationGroupKey({ ...base, subjectUserId: 1196 }), notificationGroupKey(base))
|
||||
assert.notEqual(notificationGroupKey({ ...base, scene: 'task_failed' }), notificationGroupKey(base))
|
||||
assert.notEqual(notificationGroupKey({ ...base, day: '2026-09-12' }), notificationGroupKey(base))
|
||||
assert.equal(notificationGroupKey({ ...base, subjectUserId: null }),
|
||||
notificationGroupKey({ ...base, subjectUserId: undefined }))
|
||||
})
|
||||
|
||||
test('formatGroupCounts 组行计数:读完不再挂 0 未读', () => {
|
||||
assert.equal(formatGroupCounts(12, 3), '12 条 · 3 未读')
|
||||
assert.equal(formatGroupCounts(12, 0), '12 条')
|
||||
})
|
||||
|
||||
test('formatDayLabel 日期组头:今天/昨天/更早/未知时间', () => {
|
||||
const now = new Date(2026, 8, 13, 15, 30)
|
||||
assert.equal(formatDayLabel('2026-09-13', now), '今天')
|
||||
assert.equal(formatDayLabel('2026-09-12', now), '昨天')
|
||||
assert.equal(formatDayLabel('2026-09-01', now), '2026年9月1日')
|
||||
assert.equal(formatDayLabel('', now), '未知时间')
|
||||
})
|
||||
test('buildNotificationListQuery 下钻条件:主体用户按值下发、未标注走 IS NULL 旗标', () => {
|
||||
const labelled = buildNotificationListQuery({ scene: 'task_partial', day: '2026-09-13', subjectUserId: 1160, subjectUnlabelled: false })
|
||||
assert.equal(labelled.subjectUserId, 1160)
|
||||
assert.equal('subjectUnlabelled' in labelled, false, '有主体时不下发 IS NULL 旗标,两个条件互斥')
|
||||
|
||||
// 存量行没有主体用户:按 null 下发等于把条件丢掉,必须换成旗标,否则展开一组会串进别人那组
|
||||
const unlabelled = buildNotificationListQuery({ scene: 'task_partial', day: '2026-09-13', subjectUserId: null, subjectUnlabelled: true })
|
||||
assert.equal('subjectUserId' in unlabelled, false, 'null 主体不下发成空值参数')
|
||||
assert.equal(unlabelled.subjectUnlabelled, 'true')
|
||||
})
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* 面板层纯函数的行为用例(10-13 从 NotificationBell.vue 拆出这一层的唯一目的就在这)。
|
||||
*
|
||||
* 与后管同一形状各一份(两端是两个 app,没有共享包):这里判的是聚合两级的口径本身——
|
||||
* 红点按组数、组内没读完不许掉、下钻三维、日期倒挂交换、换天挂组头。
|
||||
* 组件那一面由 tests/mount 的挂载用例跑真 DOM,两边不重复。
|
||||
*
|
||||
* 跑法:`npx vitest run --config vitest.config.ts`(`npm test` 那把 node --test 零依赖,
|
||||
* 解析不了 @ 别名与 vue,所以这一支走 vitest 的 tests/pure/**)。
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
PANEL_DETAIL_LIMIT,
|
||||
PANEL_PAGE_SIZES,
|
||||
PANEL_PAGE_SIZE,
|
||||
applyGroupsPage,
|
||||
applyMarkReadToCounts,
|
||||
detailQueryFor,
|
||||
itemLevel,
|
||||
normalizedDayRange,
|
||||
startsNewDay,
|
||||
} from '@/shared/composables/useNotificationBellPanel'
|
||||
|
||||
const group = (over: Record<string, unknown> = {}) => ({
|
||||
latestId: 7,
|
||||
scene: 'task_partial',
|
||||
category: 'task_error',
|
||||
day: '2026-09-13',
|
||||
subjectUserId: 1160,
|
||||
rowCount: 1,
|
||||
unreadCount: 1,
|
||||
level: 'error',
|
||||
title: '用户采集数据任务部分结果缺失',
|
||||
content: '缺 6 行',
|
||||
createdAt: '2026-09-13T09:00:00.000Z',
|
||||
...over,
|
||||
})
|
||||
|
||||
describe('用户端通知面板层纯函数', () => {
|
||||
it('分页档位与默认每页组数:面板高度按量级设计,别把组数默认成明细数', () => {
|
||||
expect(PANEL_PAGE_SIZE).toBe(10)
|
||||
expect(PANEL_PAGE_SIZES).toEqual([10, 20, 50, 100])
|
||||
})
|
||||
|
||||
it('未选日期时不下发日期条件;倒挂自动交换', () => {
|
||||
expect(normalizedDayRange(null)).toEqual({})
|
||||
expect(normalizedDayRange(['2026-09-14', '2026-09-13'])).toEqual({
|
||||
startDate: '2026-09-13',
|
||||
endDate: '2026-09-14',
|
||||
})
|
||||
})
|
||||
|
||||
it('下钻条件带满三维,主体为空改走 IS NULL 旗标', () => {
|
||||
const labelled = detailQueryFor(group({ subjectUserId: 1196 }) as never)
|
||||
expect(labelled.scene).toBe('task_partial')
|
||||
expect(labelled.day).toBe('2026-09-13')
|
||||
expect(labelled.subjectUserId).toBe(1196)
|
||||
expect(labelled.subjectUnlabelled).toBe(false)
|
||||
expect(labelled.pageSize).toBe(PANEL_DETAIL_LIMIT)
|
||||
|
||||
const unlabelled = detailQueryFor(group({ subjectUserId: null }) as never)
|
||||
expect(unlabelled.subjectUserId).toBeNull()
|
||||
expect(unlabelled.subjectUnlabelled).toBe(true)
|
||||
})
|
||||
|
||||
it('组内还有未读时组数不许减,读完最后一条才减', () => {
|
||||
const groups = [group({ unreadCount: 2 })]
|
||||
const key = 'task_partial|2026-09-13|1160'
|
||||
|
||||
const first = applyMarkReadToCounts(groups, key, 2, 1)
|
||||
expect(groups[0].unreadCount).toBe(1)
|
||||
expect(first.unreadCount).toBe(1)
|
||||
expect(first.unreadGroupCount).toBe(1, '这一组还剩一条没读,红点不许先掉')
|
||||
|
||||
const last = applyMarkReadToCounts(groups, key, 1, 1)
|
||||
expect(groups[0].unreadCount).toBe(0)
|
||||
expect(last.unreadGroupCount).toBe(0)
|
||||
})
|
||||
|
||||
it('没展开任何一组时只减明细数;两个计数都不许越界成负数', () => {
|
||||
const groups = [group({ unreadCount: 1 })]
|
||||
expect(applyMarkReadToCounts(groups, '', 1, 1)).toEqual({ unreadCount: 0, unreadGroupCount: 1 })
|
||||
expect(applyMarkReadToCounts([], '', 0, 0)).toEqual({ unreadCount: 0, unreadGroupCount: 0 })
|
||||
})
|
||||
|
||||
it('聚合页缺字段时回落:组数按实收、明细条数按清单长度', () => {
|
||||
const applied = applyGroupsPage(
|
||||
{ groups: [group(), group({ subjectUserId: 1196, day: '2026-09-12' })] } as never,
|
||||
{ unreadCount: 4, unreadGroupCount: 2 },
|
||||
)
|
||||
expect(applied.total).toBe(2)
|
||||
expect(applied.rowCount).toBe(2)
|
||||
expect(applied.unreadCount).toBe(4)
|
||||
expect(applied.unreadGroupCount).toBe(2)
|
||||
|
||||
const empty = applyGroupsPage({ groups: null } as never, { unreadCount: 1, unreadGroupCount: 1 })
|
||||
expect(empty.groups).toEqual([])
|
||||
expect(empty.total).toBe(0)
|
||||
})
|
||||
|
||||
it('日期头只在换天时出现:同一天多组(多用户/多场景)不重复挂头', () => {
|
||||
const list = [group(), group({ subjectUserId: 1196 }), group({ scene: 'task_failed' })]
|
||||
expect(startsNewDay(list, 0)).toBe(true)
|
||||
expect(startsNewDay(list, 1)).toBe(false)
|
||||
expect(startsNewDay(list, 2)).toBe(false, '同一天不同场景仍是两组,但不重复挂日期头')
|
||||
})
|
||||
|
||||
it('级别兜底:非法/缺失都按 warning,组行与明细行配色不分家', () => {
|
||||
expect(itemLevel({ level: 'error' })).toBe('error')
|
||||
expect(itemLevel({ level: 'info' })).toBe('info')
|
||||
expect(itemLevel({ level: 'warn' })).toBe('warning')
|
||||
expect(itemLevel({ level: '' })).toBe('warning')
|
||||
})
|
||||
})
|
||||
@@ -7,7 +7,8 @@ import vue from '@vitejs/plugin-vue'
|
||||
*
|
||||
* 与 vite.config.ts 分家:那份管生产构建,这里只服务挂载用例,
|
||||
* 动它不改变 `npm run build` 的产物,也不在 tsconfig include 里(vue-tsc 不检它)。
|
||||
* include 只收 `tests/mount/**`——本仓其余判据走 `node --test tests/*.test.ts`,
|
||||
* include 收 `tests/mount/**`(组件挂载)与 `tests/pure/**`(面板层纯函数:那层要解析 @ 别名
|
||||
* 与 vue/element-plus,进不了零依赖的 `node --test`)——本仓其余判据走 `node --test tests/*.test.ts`,
|
||||
* 那支 glob 不递归,两套 runner 抓不到对方的文件(后管同款分法,已验证互不串)。
|
||||
*/
|
||||
export default defineConfig({
|
||||
@@ -21,6 +22,6 @@ export default defineConfig({
|
||||
// 本面装的是 happy-dom(后管那份用 jsdom):环境名写错时 vitest 直接 MISSING DEPENDENCY,
|
||||
// 一支用例都跑不起来还报 "no tests"——所以这条与 devDependencies 必须同处对账。
|
||||
environment: 'happy-dom',
|
||||
include: ['tests/mount/**/*.test.ts'],
|
||||
include: ['tests/mount/**/*.test.ts', 'tests/pure/**/*.test.ts'],
|
||||
},
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user