feat(通知): 列表按 场景×自然日×主体用户 聚合成两级,红点按组数亮而明细条数同屏;后管日期面板不再被弹窗压住
V158 给 biz_user_notification 加 subject_user_id(事件主体用户,与收件人 user_id 分家): 一行通知是给某个收件人看的,被通知的那个 uid 原先只活在文案字符串里,没有列就没法按用户成组, 也不肯用正则去解历史文案凑分组键。存量不回填(定案)⇒ 老行 subject_user_id 为 NULL,自成「未标注主体」一组。 写入侧 pushOrRefresh 第 8 参带主体,AUDIENCE_USER 时主体=收件人(故新增 7 参便捷档,68 处调用一行没改); pushToAdminsAnyOf 传 null 并注明理由:一把密钥被 N 个账号共用,不挑一个 uid 冒充。 新增 GET /api/notifications/groups 与 /api/admin/notifications/groups:Java 侧分组(复用 baseWrapper 一份筛选实现), 分页按组切,同屏返回 total=组数 与 rowCount=明细条数;unreadGroupCount 走 COUNT(DISTINCT scene, DATE(created_at), IFNULL(subject_user_id,-1)) —— IFNULL 不能省, MySQL 的 COUNT(DISTINCT a,b,c) 会跳过任一表达式为 NULL 的行,不兜就把存量那一组整个数没。 红点是新增 unreadGroupCount 而不动 unreadCount 语义:已装机老客户端读 unreadCount 画徽标, 换语义会让老客户端出现「红点 3、列表 217 条」对不上。 铃铛两级(后管+桌面各一份):聚合行点击只展开、不替用户标已读,已读必须进明细逐条点; 明细一次最多 50 条,超出显示「另有 N 条未列出」;下钻带 scene+day+subjectUserId(主体为空改下发 subjectUnlabelled 旗标走 IS NULL),少一维就会把同场景同天别主体的行混进这一组的明细——桌面端最初就漏了这一维。 死码随两级视图退场:groupNotificationsByDay/NotificationDayGroup 删掉,用例换成 formatDayLabel/notificationGroupKey/formatGroupCounts。 后管日期选择面板 z-index 抬到 3300(面板 3200)之上:Element 弹层只自 2000 起递增,不抬就被面板压住,表现为「日期点不动」。 playwright 加 E2E_PORT+strictPort:实测 5174/5176 被别的项目的 vite 占着,reuseExistingServer 让 e2e 连上别人的应用, 当时 5 条全红是端口归属问题而不是回归。 验证=后端通知面 66/66(-Dtest='Notification*' 63 + AdminNotificationControllerTest 3)BUILD SUCCESS; 后管 node --test 1819/1819、真浏览器 e2e 10/10(含遮挡与「展开只取本组」); 桌面 node --test 834/834、组件挂载 vitest 8/8;两前端 vue-tsc --noEmit rc=0;ops 值班侧 18/18。 记账三处=后管 source-pin 逐文件基线 notification-bell.test.ts 用例 6→7(该文件钉子仍 0,占比不动); 桌面 catch 棘轮 blocks 298→299(新增那支是 toggleGroup 明细失败写进面板 loadError,非静默,silent 84 一格没涨); 桌面 endpoints 台账补 /api/notifications/groups。 变异自证 7 条全 KILLED:红点按条数/组内没读完就减组数/聚合行直接标已读/明细截断不报数/下钻丢主体/ 丢 IS NULL 旗标/null 主体当值下发。其中「组内没读完就减组数」第一轮 SURVIVED——用例只钉了徽标, 而徽标在 unreadGroupCount 归零时会退回条数兜底,把这条回归盖住了;改成同时钉「N 组未读」chip 才杀掉。 已知盲区(下次补,别当已验):①桌面两级只在 happy-dom 跑过真组件,布局与层级没在真浏览器点过 (桌面日期弹层的层级修复本就在 HEAD 里,不是这批引入);②后管 e2e 夹具没有 subjectUserId=null 的行, 「存量自成一组」在后管 UI 层没被点过,只有后端 WHERE 与桌面组件各一条用例钉着。
This commit is contained in:
@@ -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>
|
||||
@@ -129,10 +152,12 @@ import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
import {
|
||||
fetchNotificationGroups,
|
||||
fetchNotificationList,
|
||||
fetchNotificationSummary,
|
||||
markAllNotificationsRead,
|
||||
markNotificationRead,
|
||||
type AdminNotificationGroup,
|
||||
type AdminNotificationItem,
|
||||
} from '@/api/notifications'
|
||||
import { useAdminSessionStore } from '@/stores/admin-session'
|
||||
@@ -140,17 +165,22 @@ import { showAdminFeedback } from '@/components/admin-feedback-ui'
|
||||
import {
|
||||
NOTIFICATION_POLL_INTERVAL_MS,
|
||||
createSummaryFailureAlerter,
|
||||
formatDayLabel,
|
||||
formatGroupCounts,
|
||||
formatNotificationTime,
|
||||
formatUnreadBadge,
|
||||
groupNotificationsByDay,
|
||||
hasNewNotification,
|
||||
markReadFailureMessage,
|
||||
notificationGroupKey,
|
||||
readLastNotifiedId,
|
||||
writeLastNotifiedId,
|
||||
} from '@/layout/notification-bell-model'
|
||||
import { todayDateInput } from '@/utils/datetime'
|
||||
|
||||
const PAGE_SIZE = 10
|
||||
/** 聚合行比单条高(多一行计数与展开入口),一页 6 组刚好是面板的高度量级。 */
|
||||
const PAGE_SIZE = 6
|
||||
/** 展开一组时列出的明细上限:一组最多可能有几百条,全塞进 DOM 会把面板撑到不可滚动。 */
|
||||
const DETAIL_LIMIT = 50
|
||||
|
||||
const session = useAdminSessionStore()
|
||||
const rootRef = ref<HTMLElement | null>(null)
|
||||
@@ -158,8 +188,10 @@ const panelRef = ref<HTMLElement | null>(null)
|
||||
const panelStyle = ref<Record<string, string>>({})
|
||||
|
||||
const unreadCount = ref(0)
|
||||
const items = ref<AdminNotificationItem[]>([])
|
||||
const unreadGroupCount = ref(0)
|
||||
const groups = ref<AdminNotificationGroup[]>([])
|
||||
const total = ref(0)
|
||||
const rowCount = ref(0)
|
||||
const page = ref(1)
|
||||
const panelOpen = ref(false)
|
||||
const loading = ref(false)
|
||||
@@ -168,9 +200,15 @@ const loadError = ref('')
|
||||
const keyword = ref('')
|
||||
const startDate = ref(todayDateInput())
|
||||
const endDate = ref(todayDateInput())
|
||||
const expandedKey = ref('')
|
||||
const details = ref<AdminNotificationItem[]>([])
|
||||
const detailTotal = ref(0)
|
||||
const detailLoading = ref(false)
|
||||
|
||||
const badgeText = computed(() => formatUnreadBadge(unreadCount.value))
|
||||
const groupedItems = computed(() => groupNotificationsByDay(items.value))
|
||||
/** 徽标按**组数**亮:同类事件一天刷几十条不该把红点做成计数器;后端没给这个字段时退回条数。 */
|
||||
const badgeText = computed(() =>
|
||||
formatUnreadBadge(unreadGroupCount.value || unreadCount.value),
|
||||
)
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / PAGE_SIZE)))
|
||||
/** 日期恒为「当天」是默认视图、不算主动筛选:若计入,下方「无筛选才记录已提醒 id」的分支会永久失效。 */
|
||||
const hasFilter = computed(() => Boolean(keyword.value.trim()))
|
||||
@@ -223,6 +261,7 @@ async function refreshSummary() {
|
||||
const summary = await fetchNotificationSummary()
|
||||
summaryFailures.reportSuccess()
|
||||
unreadCount.value = Number(summary?.unreadCount ?? 0)
|
||||
unreadGroupCount.value = Number(summary?.unreadGroupCount ?? 0)
|
||||
const latestId = Number(summary?.latestId ?? 0)
|
||||
if (hasNewNotification(latestId, readLastNotifiedId(currentUid()))) {
|
||||
ElMessage.warning('收到新的告警通知,请点击右上角铃铛查看')
|
||||
@@ -241,21 +280,25 @@ async function loadPage(targetPage: number) {
|
||||
if (loading.value) return
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await fetchNotificationList({
|
||||
const result = await fetchNotificationGroups({
|
||||
page: targetPage,
|
||||
pageSize: PAGE_SIZE,
|
||||
keyword: keyword.value,
|
||||
...normalizedDayRange(),
|
||||
})
|
||||
const list = Array.isArray(result?.items) ? result.items : []
|
||||
items.value = list
|
||||
const list = Array.isArray(result?.groups) ? result.groups : []
|
||||
groups.value = list
|
||||
total.value = Number(result?.total ?? list.length)
|
||||
rowCount.value = Number(result?.rowCount ?? list.length)
|
||||
unreadCount.value = Number(result?.unreadCount ?? unreadCount.value)
|
||||
unreadGroupCount.value = Number(result?.unreadGroupCount ?? unreadGroupCount.value)
|
||||
page.value = targetPage
|
||||
loadError.value = ''
|
||||
// 换页/重查后展开态必须清掉:旧组的明细列表与新页的组对不上,会串台
|
||||
collapse()
|
||||
// 无筛选时首页就是最新数据,顺带记录「已提醒过的最大 id」;有筛选时最新 id 不代表真实最新
|
||||
if (targetPage <= 1 && !hasFilter.value && list.length) {
|
||||
const latest = Number(list[0].id)
|
||||
const latest = Number(list[0].latestId)
|
||||
if (latest > 0) {
|
||||
writeLastNotifiedId(currentUid(), Math.max(readLastNotifiedId(currentUid()), latest))
|
||||
}
|
||||
@@ -269,6 +312,56 @@ async function loadPage(targetPage: number) {
|
||||
}
|
||||
}
|
||||
|
||||
function isExpanded(group: AdminNotificationGroup): boolean {
|
||||
return expandedKey.value === notificationGroupKey(group)
|
||||
}
|
||||
|
||||
/** 日期头只在"与上一组不是同一天"时出现:同一天可能有多个组(多个用户/多个场景)。 */
|
||||
function startsNewDay(index: number): boolean {
|
||||
if (index === 0) return true
|
||||
return groups.value[index - 1]?.day !== groups.value[index]?.day
|
||||
}
|
||||
|
||||
function collapse() {
|
||||
expandedKey.value = ''
|
||||
details.value = []
|
||||
detailTotal.value = 0
|
||||
detailLoading.value = false
|
||||
}
|
||||
|
||||
async function toggleGroup(group: AdminNotificationGroup) {
|
||||
if (isExpanded(group)) {
|
||||
collapse()
|
||||
return
|
||||
}
|
||||
collapse()
|
||||
expandedKey.value = notificationGroupKey(group)
|
||||
detailLoading.value = true
|
||||
try {
|
||||
const result = await fetchNotificationList({
|
||||
page: 1,
|
||||
pageSize: DETAIL_LIMIT,
|
||||
scene: group.scene,
|
||||
day: group.day,
|
||||
subjectUserId: group.subjectUserId,
|
||||
subjectUnlabelled: group.subjectUserId === null || group.subjectUserId === undefined,
|
||||
})
|
||||
// 请求期间用户可能已经收起了另一组:晚到的结果不能盖掉当前展开的那组
|
||||
if (expandedKey.value !== notificationGroupKey(group)) return
|
||||
details.value = Array.isArray(result?.items) ? result.items : []
|
||||
detailTotal.value = Number(result?.total ?? details.value.length)
|
||||
} catch (error) {
|
||||
if (expandedKey.value !== notificationGroupKey(group)) return
|
||||
details.value = []
|
||||
detailTotal.value = 0
|
||||
showAdminFeedback(error instanceof Error ? error.message : '明细加载失败', 'error')
|
||||
} finally {
|
||||
if (expandedKey.value === notificationGroupKey(group)) {
|
||||
detailLoading.value = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function goPage(targetPage: number) {
|
||||
const safe = Math.min(Math.max(1, targetPage), totalPages.value)
|
||||
if (safe === page.value || loading.value) return
|
||||
@@ -323,6 +416,14 @@ async function onItemClick(item: AdminNotificationItem) {
|
||||
await markNotificationRead(item.id)
|
||||
item.read = true
|
||||
unreadCount.value = Math.max(0, unreadCount.value - 1)
|
||||
// 组内未读清零 ⇒ 这一组不再计为未读组,红点(按组数)才会跟着掉一格
|
||||
const owner = groups.value.find((group) => notificationGroupKey(group) === expandedKey.value)
|
||||
if (owner && owner.unreadCount > 0) {
|
||||
owner.unreadCount -= 1
|
||||
if (owner.unreadCount === 0) {
|
||||
unreadGroupCount.value = Math.max(0, unreadGroupCount.value - 1)
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// 改前只 console.warn:点了通知没反应,用户只能反复点。失败必须可见(统一出口)。
|
||||
console.warn('[admin-notification] 标记已读失败:', error)
|
||||
@@ -335,10 +436,14 @@ async function readAll() {
|
||||
markingAll.value = true
|
||||
try {
|
||||
await markAllNotificationsRead()
|
||||
for (const item of items.value) {
|
||||
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')
|
||||
@@ -528,6 +633,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 +866,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 后管「错误静默」)。
|
||||
*
|
||||
|
||||
@@ -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
|
||||
},
|
||||
|
||||
@@ -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 条')
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user