feat(通知): 四级严重度与严重度/时间双排序,客户端与后台管理同步

通知表新增 severity(紧急/高危/中危/低危,V161),由 scene + level 推导且
不回改 level:老客户端配色不受影响,secret_balance 的余量偏低与欠费也能分档。
列表与聚合接口默认按严重度倒序(同档按时间倒序),sort=time 切纯时间排序;
聚合组取组内最高严重度。两端铃铛加彩色等级标签与排序切换,展开明细沿用
同一排序,严重度排序下隐藏会跨天误导的日期头。
This commit is contained in:
2026-10-21 13:33:07 +08:00
parent f6aa04d0f2
commit 86d78160fd
23 changed files with 804 additions and 40 deletions
@@ -1,11 +1,25 @@
import { http } from './http'
import { unwrap } from './envelope'
/** 业务严重度:紧急 / 高危 / 中危 / 低危(后端按 scene + level 推导)。 */
export type AdminNotificationSeverity = 'urgent' | 'high' | 'medium' | 'low'
export type AdminNotificationSortMode = 'severity' | 'time'
export const ADMIN_NOTIFICATION_SEVERITY_LABELS: Readonly<Record<AdminNotificationSeverity, string>> = {
urgent: '紧急',
high: '高危',
medium: '中危',
low: '低危',
}
/** 单条通知(后台铃铛)。 */
export interface AdminNotificationItem {
id: number
scene: string
level: string
/** 业务严重度;旧后端不返回时前端按 level 兜底。 */
severity?: string
title: string
content: string
read: boolean
@@ -38,6 +52,8 @@ export interface AdminNotificationGroup {
rowCount: number
unreadCount: number
level: string
/** 组内最高严重度。 */
severity?: string
title: string
content: string
createdAt: string | null
@@ -69,6 +85,8 @@ export interface AdminNotificationListParams {
keyword?: string
startDate?: string
endDate?: string
/** 排序:severity(默认)或 time;默认值不下发。 */
sort?: AdminNotificationSortMode
/** 展开聚合组:三个条件取自该组自己返回的值,原样回传。 */
scene?: string
day?: string
@@ -90,6 +108,7 @@ export async function fetchNotificationGroups(
keyword: keyword || undefined,
startDate: params.startDate || undefined,
endDate: params.endDate || undefined,
sort: params.sort === 'time' ? 'time' : undefined,
},
})
return unwrap<AdminNotificationGroupPage>(data)
@@ -107,6 +126,7 @@ export async function fetchNotificationList(
keyword: keyword || undefined,
startDate: params.startDate || undefined,
endDate: params.endDate || undefined,
sort: params.sort === 'time' ? 'time' : undefined,
scene: params.scene || undefined,
day: params.day || undefined,
subjectUserId: params.subjectUserId ?? undefined,
@@ -75,6 +75,25 @@
重置
</button>
</div>
<div class="bell-sort-chips" role="group" aria-label="通知排序">
<span class="bell-sort-label">排序</span>
<button
type="button"
class="bell-sort-chip"
:class="{ 'is-active': sortMode === 'severity' }"
@click="setSortMode('severity')"
>
严重度
</button>
<button
type="button"
class="bell-sort-chip"
:class="{ 'is-active': sortMode === 'time' }"
@click="setSortMode('time')"
>
时间
</button>
</div>
</div>
<div v-if="loading && !groups.length" class="bell-empty">正在加载...</div>
@@ -82,13 +101,17 @@
<div v-else-if="!groups.length" class="bell-empty">{{ hasFilter ? '没有符合条件的通知' : '暂无通知' }}</div>
<ul v-else class="bell-list">
<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-if="sortMode === 'time' && startsNewDay(index)" class="bell-day-head">{{ formatDayLabel(group.day) }}</li>
<li
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-severity-tag" :class="`bell-severity-tag--${itemSeverity(group)}`">
{{ severityLabel(group) }}
</span>
<span class="bell-item-title">{{ group.title }}</span>
<span class="bell-item-time">{{ formatTime(group.createdAt) }}</span>
</div>
@@ -110,6 +133,9 @@
@click="onItemClick(item)"
>
<div class="bell-item-head">
<span class="bell-severity-tag" :class="`bell-severity-tag--${itemSeverity(item)}`">
{{ severityLabel(item) }}
</span>
<span class="bell-item-title">{{ item.title }}</span>
<span class="bell-item-time">{{ formatTime(item.createdAt) }}</span>
</div>
@@ -161,6 +187,8 @@ import {
import { todayDateInput } from '@/utils/datetime'
import {
itemLevel,
itemSeverity,
severityLabel,
startsNewDay as groupStartsNewDay,
useNotificationBellPanel,
} from '@/layout/notification-bell-panel'
@@ -195,6 +223,8 @@ const {
reload,
resetFilters,
rowCount,
setSortMode,
sortMode,
toggleGroup,
total,
totalPages,
@@ -496,6 +526,7 @@ onUnmounted(() => {
}
.bell-item-title {
flex: 1;
color: var(--admin-text, #24384d);
font-size: 13px;
font-weight: 700;
@@ -505,6 +536,36 @@ onUnmounted(() => {
white-space: nowrap;
}
.bell-severity-tag {
flex-shrink: 0;
padding: 1px 6px;
border: 1px solid currentColor;
border-radius: 999px;
font-size: 10.5px;
font-weight: 600;
line-height: 1.5;
}
.bell-severity-tag--urgent {
background: #fdecec;
color: #c92a2a;
}
.bell-severity-tag--high {
background: #fdf3e2;
color: #b26a12;
}
.bell-severity-tag--medium {
background: #eaf2fb;
color: #2f6fb3;
}
.bell-severity-tag--low {
background: #f1f4f7;
color: #6b7c8e;
}
.bell-item--error .bell-item-title {
color: #b23c3c;
}
@@ -594,6 +655,42 @@ onUnmounted(() => {
background: #edf5fb;
}
.bell-sort-chips {
display: flex;
align-items: center;
gap: 6px;
}
.bell-sort-label {
color: #8a99a8;
font-size: 11px;
}
.bell-sort-chip {
height: 24px;
padding: 0 10px;
border: 1px solid #d8e3ee;
border-radius: 12px;
background: #ffffff;
color: #667085;
font-size: 12px;
line-height: 1;
cursor: pointer;
transition: color 0.15s ease, border-color 0.15s ease, background 0.15s ease;
}
.bell-sort-chip:hover {
border-color: var(--admin-primary-strong, #2f5d8b);
color: var(--admin-primary-strong, #2f5d8b);
}
.bell-sort-chip.is-active {
border-color: var(--admin-primary-strong, #2f5d8b);
background: #edf5fb;
color: var(--admin-primary-strong, #2f5d8b);
font-weight: 700;
}
.bell-day-head {
padding: 6px 14px;
background: #f4f7fa;
@@ -13,6 +13,7 @@ import { computed, onUnmounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
ADMIN_NOTIFICATION_SEVERITY_LABELS,
fetchNotificationGroups,
fetchNotificationList,
fetchNotificationSummary,
@@ -20,6 +21,8 @@ import {
markNotificationRead,
type AdminNotificationGroup,
type AdminNotificationItem,
type AdminNotificationSeverity,
type AdminNotificationSortMode,
} from '@/api/notifications'
import { showAdminFeedback } from '@/components/admin-feedback-ui'
import {
@@ -64,10 +67,14 @@ export function normalizedDayRange(startDate: string, endDate: string): { startD
}
/** 下钻条件:三维缺一维就会把别的主体的行混进这一组的明细(同场景同一天有好几组)。 */
export function detailQueryFor(group: AdminNotificationGroup) {
export function detailQueryFor(
group: AdminNotificationGroup,
sort: AdminNotificationSortMode = 'severity',
) {
return {
page: 1,
pageSize: PANEL_DETAIL_LIMIT,
sort,
scene: group.scene,
day: group.day,
subjectUserId: group.subjectUserId,
@@ -125,6 +132,24 @@ export function itemLevel(item: { level: string }): 'error' | 'warning' | 'info'
return item.level === 'error' || item.level === 'info' ? item.level : 'warning'
}
/** 严重度兜底:新后端直接给 severity;旧后端没这列时按 level 推,绝不让标签空白。 */
export function itemSeverity(item: {
severity?: string | null
level?: string | null
}): AdminNotificationSeverity {
const value = item.severity
if (value === 'urgent' || value === 'high' || value === 'medium' || value === 'low') {
return value
}
if (item.level === 'error') return 'urgent'
if (item.level === 'info') return 'low'
return 'high'
}
export function severityLabel(item: { severity?: string | null; level?: string | null }): string {
return ADMIN_NOTIFICATION_SEVERITY_LABELS[itemSeverity(item)]
}
export function useNotificationBellPanel(options: NotificationPanelOptions) {
const uid = options.uid
const today = options.today
@@ -141,6 +166,8 @@ export function useNotificationBellPanel(options: NotificationPanelOptions) {
const keyword = ref('')
const startDate = ref(today())
const endDate = ref(today())
/** 默认按严重度;可切「按时间」。 */
const sortMode = ref<AdminNotificationSortMode>('severity')
const expandedKey = ref('')
const details = ref<AdminNotificationItem[]>([])
const detailTotal = ref(0)
@@ -204,6 +231,7 @@ export function useNotificationBellPanel(options: NotificationPanelOptions) {
page: targetPage,
pageSize: PANEL_PAGE_SIZE,
keyword: keyword.value,
sort: sortMode.value,
...normalizedDayRange(startDate.value, endDate.value),
})
const applied = applyGroupsPage(result, {
@@ -244,7 +272,7 @@ export function useNotificationBellPanel(options: NotificationPanelOptions) {
expandedKey.value = key
detailLoading.value = true
try {
const result = await fetchNotificationList(detailQueryFor(group))
const result = await fetchNotificationList(detailQueryFor(group, sortMode.value))
// 请求期间用户可能已经收起了另一组:晚到的结果不能盖掉当前展开的那组
if (expandedKey.value !== key) return
details.value = Array.isArray(result?.items) ? result.items : []
@@ -279,6 +307,15 @@ export function useNotificationBellPanel(options: NotificationPanelOptions) {
void loadPage(1)
}
/** 排序切换:同一档不重复请求;切换后回到第一页并收起明细。 */
function setSortMode(value: AdminNotificationSortMode) {
if (sortMode.value === value) {
return
}
sortMode.value = value
void loadPage(1)
}
async function onItemClick(item: AdminNotificationItem) {
if (item.read) return
try {
@@ -363,6 +400,8 @@ export function useNotificationBellPanel(options: NotificationPanelOptions) {
badgeText,
totalPages,
hasFilter,
sortMode,
setSortMode,
dateRangeValue,
onDateRangeChange,
refreshSummary,
@@ -25,6 +25,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(() => ({
ADMIN_NOTIFICATION_SEVERITY_LABELS: { urgent: '紧急', high: '高危', medium: '中危', low: '低危' },
fetchNotificationSummary: vi.fn(),
fetchNotificationGroups: vi.fn(),
fetchNotificationList: vi.fn(),
@@ -260,4 +261,47 @@ describe('NotificationBell:两处失败必须可见', () => {
})
expect(api.fetchNotificationList.mock.calls[0][0].subjectUnlabelled).toBe(false)
})
it('默认展示四级严重度并按严重度请求;切「时间」后带 sort=time 重查并恢复日期头', async () => {
api.fetchNotificationGroups.mockResolvedValue(
groupPage([
group({ latestId: 51, severity: 'urgent', level: 'error', day: '2026-09-13' }),
group({ latestId: 50, subjectUserId: 1196, severity: 'low', level: 'info', day: '2026-09-12' }),
]),
)
const bell = mountBell()
await flushPromises()
await bell.find('button.bell-trigger').trigger('click')
await flushPromises()
expect(Array.from(document.querySelectorAll('.bell-severity-tag')).map((el) => el.textContent?.trim()))
.toEqual(['紧急', '低危'])
expect(api.fetchNotificationGroups.mock.calls[0][0].sort).toBe('severity')
// 严重度排序会跨天交错,不挂日期头
expect(document.querySelectorAll('.bell-day-head')).toHaveLength(0)
// 展开明细也要带同一种排序,否则会出现「列表按严重度、明细又按时间」
api.fetchNotificationList.mockResolvedValue({
items: [notification({ id: 51, severity: 'urgent' })],
total: 1,
page: 1,
pageSize: 50,
unreadCount: 1,
})
await expandFirstGroup()
expect(api.fetchNotificationList.mock.calls.at(-1)?.[0].sort).toBe('severity')
const timeButton = Array.from(document.querySelectorAll<HTMLElement>('.bell-sort-chips button'))
.find((button) => button.textContent?.includes('时间'))
expect(timeButton).toBeTruthy()
timeButton!.click()
await flushPromises()
expect(api.fetchNotificationGroups.mock.calls.at(-1)?.[0].sort).toBe('time')
expect(document.querySelectorAll('.bell-day-head')).toHaveLength(2)
await expandFirstGroup()
expect(api.fetchNotificationList.mock.calls.at(-1)?.[0].sort).toBe('time')
})
})
@@ -16,8 +16,10 @@ import {
applyMarkReadToCounts,
detailQueryFor,
itemLevel,
itemSeverity,
latestIdWorthRecording,
normalizedDayRange,
severityLabel,
startsNewDay,
} from '@/layout/notification-bell-panel'
@@ -116,6 +118,23 @@ describe('通知面板层纯函数', () => {
expect(itemLevel({ level: '' })).toBe('warning')
})
it('四级严重度:后端给值原样用,旧后端缺字段按 level 兜底,绝不出现空标签', () => {
expect(itemSeverity({ severity: 'urgent', level: 'warning' })).toBe('urgent')
expect(itemSeverity({ severity: 'high' })).toBe('high')
expect(itemSeverity({ severity: 'medium' })).toBe('medium')
expect(itemSeverity({ severity: 'low' })).toBe('low')
expect(itemSeverity({ level: 'error' })).toBe('urgent')
expect(itemSeverity({ level: 'info' })).toBe('low')
expect(itemSeverity({ level: 'warning' })).toBe('high')
expect(itemSeverity({ level: '' })).toBe('high')
expect(itemSeverity({ severity: 'fatal', level: 'warning' })).toBe('high')
expect(severityLabel({ severity: 'urgent' })).toBe('紧急')
expect(severityLabel({ severity: 'high' })).toBe('高危')
expect(severityLabel({ severity: 'medium' })).toBe('中危')
expect(severityLabel({ severity: 'low' })).toBe('低危')
})
it('已提醒水位只在首页真有数据时推进,取不到 id 就什么也不写', () => {
expect(latestIdWorthRecording([])).toBe(0)
expect(latestIdWorthRecording([group({ latestId: 0 })])).toBe(0)
@@ -48,7 +48,8 @@ public class AdminNotificationController {
@Operation(summary = "通知聚合列表(铃铛默认视图)",
description = "按「场景 × 自然日 × 事件主体用户」折叠,分页按组切。"
+ "返回 total=组数、rowCount=同条件下折叠前的明细条数,两个数都要显示,"
+ "否则「共 12 条」会被读成只有 12 条通知。筛选条件与单条列表共用一套实现。")
+ "否则「共 12 条」会被读成只有 12 条通知。筛选条件与单条列表共用一套实现。"
+ "sort 默认 severity(紧急→低危,同档按时间倒序),传 time 则纯时间倒序。")
public ApiResponse<NotificationGroupPageVo> groups(
HttpServletRequest request,
@Parameter(description = "页码(按组)") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
@@ -60,10 +61,14 @@ 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 = "排序:severity=按严重度(默认)/ time=按时间倒序")
@RequestParam(required = false, defaultValue = NotificationService.SORT_SEVERITY) String sort) {
Long userId = currentAdminId(request);
return ApiResponse.success(notificationService.groups(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.setSort(sort);
return ApiResponse.success(notificationService.groups(userId, NotificationService.AUDIENCE_ADMIN, query));
}
@GetMapping
@@ -71,7 +76,8 @@ public class AdminNotificationController {
description = "onlyUnread=true 时只返回未读;keyword 模糊匹配标题/内容;"
+ "category 按类型大类筛选(system_error/task_error/config_error/system_notice);"
+ "startDate/endDate 为年月日闭区间;"
+ "scene/day/subjectUserId 三个条件用于展开聚合组、取该组内的明细。")
+ "scene/day/subjectUserId 三个条件用于展开聚合组、取该组内的明细;"
+ "sort 默认 severity,传 time 则按时间倒序。")
public ApiResponse<NotificationPageVo> page(
HttpServletRequest request,
@Parameter(description = "页码") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
@@ -89,7 +95,9 @@ public class AdminNotificationController {
@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) {
@RequestParam(required = false, defaultValue = "false") Boolean subjectUnlabelled,
@Parameter(description = "排序:severity=按严重度(默认)/ time=按时间倒序")
@RequestParam(required = false, defaultValue = NotificationService.SORT_SEVERITY) String sort) {
Long userId = currentAdminId(request);
NotificationPageQuery query = NotificationPageQuery.of(page, pageSize, onlyUnread, keyword, category,
startDate, endDate);
@@ -97,6 +105,7 @@ public class AdminNotificationController {
query.setDay(day);
query.setSubjectUserId(subjectUserId);
query.setSubjectUnlabelled(subjectUnlabelled);
query.setSort(sort);
return ApiResponse.success(notificationService.page(userId, NotificationService.AUDIENCE_ADMIN, query));
}
@@ -47,7 +47,8 @@ public class NotificationController {
@GetMapping("/groups")
@Operation(summary = "通知聚合列表(铃铛默认视图)",
description = "按「场景 × 自然日」折叠(桌面端的主体用户就是本人,分组键里的用户列恒等于自己)。"
+ "total=组数、rowCount=折叠前的明细条数,两个数都要显示。")
+ "total=组数、rowCount=折叠前的明细条数,两个数都要显示。"
+ "sort 默认 severity(紧急→低危,同档按时间倒序),传 time 则纯时间倒序。")
public ApiResponse<NotificationGroupPageVo> groups(
HttpServletRequest request,
@Parameter(description = "页码(按组)") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
@@ -59,17 +60,22 @@ 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 = "排序:severity=按严重度(默认)/ time=按时间倒序")
@RequestParam(required = false, defaultValue = NotificationService.SORT_SEVERITY) String sort) {
Long userId = currentUserId(request);
return ApiResponse.success(notificationService.groups(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.setSort(sort);
return ApiResponse.success(notificationService.groups(userId, NotificationService.AUDIENCE_USER, query));
}
@GetMapping
@Operation(summary = "通知分页列表",
description = "onlyUnread=true 时只返回未读;keyword 模糊匹配标题/内容;"
+ "category 按类型大类筛选(system_error/task_error/config_error/system_notice);"
+ "startDate/endDate 为年月日闭区间;scene/day 用于展开聚合组、取该组内的明细。")
+ "startDate/endDate 为年月日闭区间;scene/day 用于展开聚合组、取该组内的明细;"
+ "sort 默认 severity,传 time 则按时间倒序。")
public ApiResponse<NotificationPageVo> page(
HttpServletRequest request,
@Parameter(description = "页码") @RequestParam(defaultValue = PageDefaults.FIRST_PAGE) Long page,
@@ -84,12 +90,15 @@ public class NotificationController {
@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) {
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate day,
@Parameter(description = "排序:severity=按严重度(默认)/ time=按时间倒序")
@RequestParam(required = false, defaultValue = NotificationService.SORT_SEVERITY) String sort) {
Long userId = currentUserId(request);
NotificationPageQuery query = NotificationPageQuery.of(page, pageSize, onlyUnread, keyword, category,
startDate, endDate);
query.setScene(scene);
query.setDay(day);
query.setSort(sort);
return ApiResponse.success(notificationService.page(userId, NotificationService.AUDIENCE_USER, query));
}
@@ -19,6 +19,8 @@ public class NotificationPageQuery {
private String category;
private LocalDate startDate;
private LocalDate endDate;
/** 排序:severity=按严重度(默认,紧急→低危,同档按时间倒序);time=按时间倒序。 */
private String sort;
/** 聚合组展开:只取该组内的明细,三个条件成对出现(空表示不限制)。 */
private String scene;
private LocalDate day;
@@ -19,6 +19,8 @@ public class UserNotificationEntity {
private String audience;
private String scene;
private String level;
/** 业务严重度:urgent=紧急/high=高危/medium=中危/low=低危;列表默认按它排序。 */
private String severity;
private String title;
private String content;
private String dedupeKey;
@@ -30,6 +30,8 @@ public class NotificationGroupVo {
private Long unreadCount;
/** 级别取组内最高(error &gt; warning &gt; info),一组里混进 error 不能被 warning 盖掉。 */
private String level;
/** 严重度取组内最高(urgent &gt; high &gt; medium &gt; low),列表默认排序依据。 */
private String severity;
/** 组内最新一条的标题与正文,作为该组的摘要行。 */
private String title;
private String content;
@@ -13,8 +13,10 @@ public class NotificationItemVo {
private String scene;
/** 类型大类(铃铛筛选用):system_error/task_error/config_error/system_notice */
private String category;
/** 级别:info/warning/error */
/** 呈现级别:info/warning/error(老客户端配色继续用它)。 */
private String level;
/** 业务严重度:urgent/high/medium/low(紧急/高危/中危/低危),列表默认排序依据。 */
private String severity;
private String title;
private String content;
/** 是否已读(前端展示用,等价于 readAt 非空) */
@@ -40,6 +40,15 @@ public class NotificationService {
public static final String LEVEL_WARNING = "warning";
public static final String LEVEL_ERROR = "error";
/** 业务严重度:列表默认按 urgent → high → medium → low 排序。 */
public static final String SEVERITY_URGENT = "urgent";
public static final String SEVERITY_HIGH = "high";
public static final String SEVERITY_MEDIUM = "medium";
public static final String SEVERITY_LOW = "low";
public static final String SORT_SEVERITY = "severity";
public static final String SORT_TIME = "time";
public static final String SCENE_SECRET_BALANCE = "secret_balance";
public static final String SCENE_SECRET_INVALID = "secret_invalid";
public static final String SCENE_TASK_FAILED = "task_failed";
@@ -78,6 +87,10 @@ public class NotificationService {
private static final int CONTENT_MAX_LENGTH = 512;
private static final int DEDUPE_KEY_MAX_LENGTH = 160;
/** 严重度排序表达式:与 {@link #severityRank} 同一口径,数据库侧分页必须同序。 */
private static final String SEVERITY_ORDER_SQL =
"CASE severity WHEN 'urgent' THEN 0 WHEN 'high' THEN 1 WHEN 'medium' THEN 2 WHEN 'low' THEN 3 ELSE 2 END ASC";
private final UserNotificationMapper userNotificationMapper;
/**
@@ -109,12 +122,15 @@ public class NotificationService {
return false;
}
String normalizedAudience = normalize(audience).isEmpty() ? AUDIENCE_USER : audience;
String normalizedScene = normalize(scene).isEmpty() ? SCENE_SYSTEM : normalize(scene);
String normalizedLevel = normalize(level).isEmpty() ? LEVEL_WARNING : normalize(level);
UserNotificationEntity row = new UserNotificationEntity();
row.setUserId(userId);
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.setScene(normalizedScene);
row.setLevel(normalizedLevel);
row.setSeverity(severityOf(normalizedScene, normalizedLevel));
row.setTitle(truncate(title, TITLE_MAX_LENGTH));
row.setContent(truncate(content == null ? "" : content, CONTENT_MAX_LENGTH));
row.setDedupeKey(truncate(key, DEDUPE_KEY_MAX_LENGTH));
@@ -126,8 +142,9 @@ public class NotificationService {
log.warn("[notification] 推送落库失败 userId={} scene={} err={}", userId, scene, ex.getMessage(), ex);
return false;
}
log.info("[notification] 已推送 id={} userId={} audience={} scene={} level={} title={}",
row.getId(), userId, row.getAudience(), row.getScene(), row.getLevel(), row.getTitle());
log.info("[notification] 已推送 id={} userId={} audience={} scene={} level={} severity={} title={}",
row.getId(), userId, row.getAudience(), row.getScene(), row.getLevel(),
row.getSeverity(), row.getTitle());
return true;
}
@@ -158,11 +175,14 @@ public class NotificationService {
if (nextContent.equals(existing.getContent()) && nextTitle.equals(existing.getTitle())) {
return false;
}
String normalizedScene = normalize(scene).isEmpty() ? SCENE_SYSTEM : normalize(scene);
String normalizedLevel = normalize(level).isEmpty() ? LEVEL_WARNING : normalize(level);
userNotificationMapper.update(null, new LambdaUpdateWrapper<UserNotificationEntity>()
.eq(UserNotificationEntity::getId, existing.getId())
.set(UserNotificationEntity::getTitle, nextTitle)
.set(UserNotificationEntity::getContent, nextContent)
.set(UserNotificationEntity::getLevel, normalize(level).isEmpty() ? LEVEL_WARNING : level));
.set(UserNotificationEntity::getLevel, normalizedLevel)
.set(UserNotificationEntity::getSeverity, severityOf(normalizedScene, normalizedLevel)));
log.info("[notification] 同键通知已刷新 id={} userId={} scene={} dedupeKey={}",
existing.getId(), userId, scene, key);
return true;
@@ -192,10 +212,16 @@ public class NotificationService {
long total = totalValue == null ? 0L : totalValue;
long offset = Math.max(0L, (safePage - 1) * safeSize);
LambdaQueryWrapper<UserNotificationEntity> listWrapper = baseWrapper(userId, audience, onlyUnread, safe);
// 默认按严重度分档、同档内按时间倒序;time=纯时间倒序。分页在 SQL 侧完成,排序必须同源。
if (isTimeSort(safe.getSort())) {
listWrapper.orderByDesc(UserNotificationEntity::getId)
.last("limit " + offset + "," + safeSize);
} else {
listWrapper.last("ORDER BY " + SEVERITY_ORDER_SQL + ", id DESC limit " + offset + "," + safeSize);
}
List<UserNotificationEntity> rows = total == 0 ? List.of()
: userNotificationMapper.selectList(baseWrapper(userId, audience, onlyUnread, safe)
.orderByDesc(UserNotificationEntity::getId)
.last("limit " + offset + "," + safeSize));
: userNotificationMapper.selectList(listWrapper);
NotificationPageVo vo = new NotificationPageVo();
List<NotificationItemVo> items = new ArrayList<>(rows.size());
@@ -207,9 +233,10 @@ public class NotificationService {
vo.setPage(safePage);
vo.setPageSize(safeSize);
vo.setUnreadCount(unreadCount(userId, audience));
log.info("[notification] 列表查询 userId={} audience={} page={} size={} onlyUnread={} category={} keyword={} 起={} 止={} 命中={}",
log.info("[notification] 列表查询 userId={} audience={} page={} size={} onlyUnread={} category={} keyword={} 起={} 止={} sort={} 命中={}",
userId, audience, safePage, safeSize, onlyUnread, normalize(safe.getCategory()),
normalize(safe.getKeyword()), safe.getStartDate(), safe.getEndDate(), total);
normalize(safe.getKeyword()), safe.getStartDate(), safe.getEndDate(),
sortLabel(safe.getSort()), total);
return vo;
}
@@ -231,7 +258,8 @@ public class NotificationService {
baseWrapper(userId, audience, Boolean.TRUE.equals(safe.getOnlyUnread()), safe)
.select(UserNotificationEntity::getId, UserNotificationEntity::getScene,
UserNotificationEntity::getSubjectUserId, UserNotificationEntity::getLevel,
UserNotificationEntity::getCreatedAt, UserNotificationEntity::getReadAt)
UserNotificationEntity::getSeverity, UserNotificationEntity::getCreatedAt,
UserNotificationEntity::getReadAt)
.orderByDesc(UserNotificationEntity::getId));
// 行按 id 倒序进来 ⇒ 每组第一次出现就是该组的最新一条(最终展示顺序另见下面显式排序)。
@@ -250,6 +278,7 @@ public class NotificationService {
group.setRowCount(0L);
group.setUnreadCount(0L);
group.setLevel(row.getLevel());
group.setSeverity(normalizeSeverity(row.getSeverity(), row.getScene(), row.getLevel()));
grouped.put(key, group);
}
group.setRowCount(group.getRowCount() + 1);
@@ -259,13 +288,23 @@ public class NotificationService {
if (levelRank(row.getLevel()) > levelRank(group.getLevel())) {
group.setLevel(row.getLevel());
}
String rowSeverity = normalizeSeverity(row.getSeverity(), row.getScene(), row.getLevel());
if (severityRank(rowSeverity) > severityRank(group.getSeverity())) {
group.setSeverity(rowSeverity);
}
}
// 展示顺序显式按「自然日倒序 → 组内最新 id 倒序」。不靠"id 大就等于时间新":
// 补录、时钟回拨都会让两者倒挂,那样最该看到的一组会被排到最后一页。
// 默认「严重度倒序 → 自然日倒序 → 组内最新 id 倒序」;time=纯「自然日倒序 → 最新 id 倒序」。
// 不靠"id 大就等于时间新":补录、时钟回拨都会让两者倒挂,那样最该看到的一组会被排到最后一页。
List<NotificationGroupVo> all = new ArrayList<>(grouped.values());
all.sort(Comparator.comparing(NotificationGroupVo::getDay, Comparator.reverseOrder())
.thenComparing(NotificationGroupVo::getLatestId, Comparator.reverseOrder()));
Comparator<NotificationGroupVo> timeOrder =
Comparator.comparing(NotificationGroupVo::getDay, Comparator.reverseOrder())
.thenComparing(NotificationGroupVo::getLatestId, Comparator.reverseOrder());
all.sort(isTimeSort(safe.getSort())
? timeOrder
: Comparator.comparingInt((NotificationGroupVo group) -> severityRank(group.getSeverity()))
.reversed()
.thenComparing(timeOrder));
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()));
@@ -279,8 +318,9 @@ public class NotificationService {
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());
log.info("[notification] 聚合列表 userId={} audience={} page={} size={} sort={} 明细行={} 组数={} 未读组={}",
userId, audience, safePage, safeSize, sortLabel(safe.getSort()),
rows.size(), all.size(), vo.getUnreadGroupCount());
return vo;
}
@@ -315,6 +355,70 @@ public class NotificationService {
return LEVEL_WARNING.equals(level) ? 1 : 0;
}
/**
* 业务严重度唯一推导口径:scene 优先,level 只在同 scene 内区分轻重
* (secret_balance 的 warning=余量偏低 / error=欠费停服)。
* 迁移 V161 的回填 CASE 与此逐条一致,改这里必须同步改迁移注释。
*/
public static String severityOf(String scene, String level) {
String s = normalize(scene);
String l = normalize(level);
if (SCENE_SERVICE_DOWN.equals(s)) {
return SEVERITY_URGENT;
}
if (SCENE_SECRET_BALANCE.equals(s)) {
return LEVEL_ERROR.equals(l) ? SEVERITY_URGENT : SEVERITY_MEDIUM;
}
if (SCENE_MAIXIANG_ANOMALY.equals(s) || SCENE_SECRET_INVALID.equals(s)
|| SCENE_TASK_FAILED.equals(s)) {
return SEVERITY_HIGH;
}
if (SCENE_TASK_PARTIAL.equals(s)) {
return SEVERITY_MEDIUM;
}
if (SCENE_SYSTEM.equals(s)) {
return SEVERITY_LOW;
}
if (LEVEL_ERROR.equals(l)) {
return SEVERITY_URGENT;
}
if (LEVEL_WARNING.equals(l)) {
return SEVERITY_HIGH;
}
if (LEVEL_INFO.equals(l)) {
return SEVERITY_LOW;
}
return SEVERITY_MEDIUM;
}
/** urgent=3 / high=2 / medium=1 / low=0;未知一律按中危。 */
public static int severityRank(String severity) {
return switch (normalize(severity)) {
case SEVERITY_URGENT -> 3;
case SEVERITY_HIGH -> 2;
case SEVERITY_LOW -> 0;
default -> 1;
};
}
/** 行上已有合法值时以它为准(允许人工修库);空/非法值回退到 scene+level 推导。 */
static String normalizeSeverity(String severity, String scene, String level) {
String value = normalize(severity);
if (SEVERITY_URGENT.equals(value) || SEVERITY_HIGH.equals(value)
|| SEVERITY_MEDIUM.equals(value) || SEVERITY_LOW.equals(value)) {
return value;
}
return severityOf(scene, level);
}
private static boolean isTimeSort(String sort) {
return SORT_TIME.equalsIgnoreCase(normalize(sort));
}
private static String sortLabel(String sort) {
return isTimeSort(sort) ? SORT_TIME : SORT_SEVERITY;
}
/** 分组键:场景 × 自然日 × 主体用户;subjectUserId 为 null 时所有未标注行自成一组。 */
private record GroupKey(String scene, LocalDate day, Long subjectUserId) {
}
@@ -516,6 +620,7 @@ public class NotificationService {
vo.setScene(row.getScene());
vo.setCategory(categoryOf(row.getScene()));
vo.setLevel(row.getLevel());
vo.setSeverity(normalizeSeverity(row.getSeverity(), row.getScene(), row.getLevel()));
vo.setTitle(row.getTitle());
vo.setContent(row.getContent());
vo.setRead(row.getReadAt() != null);
@@ -0,0 +1,68 @@
-- =============================================================
-- 迁移 V161__notification_severity
--
-- 1. 变更目的:给站内通知补「严重度」一列(2026-10-21 需求)。
-- 用户原话:「通知功能优化加个紧急、高危、中危、低危的状态,排序默认按这个排,
-- 也可以支持按时间排序 2 种,客户端和后台管理都加」。
-- 此前表里只有 `level`(info/warning/error),它是**呈现级别**不是业务严重度:
-- task_partial 与 task_failed 都可能是 warning,但前者是交付不完整、后者是任务失败;
-- 直接拿 level 当四级严重度会把两者压成同一档。故新增独立列,不回改 level——
-- 老客户端的配色/图标按 level 走,改 level 的取值等于把它们一起打碎。
--
-- 2. 严重度口径(服务端唯一来源 NotificationService.severityOf):
-- urgent 紧急:service_down(下游服务停摆)、secret_balance + error(代理欠费)
-- high 高危:task_failed、secret_invalid、maixiang_anomaly(任务/密钥/调度异常)
-- medium 中危:task_partial、secret_balance + warning(余量偏低)
-- low 低危:system(普通系统通知)
-- 未登记 scene 兜底:error→urgent、warning→high、info→low、其余 medium。
--
-- 3. 存量回填:按 scene + level 推导(与 Java 侧同一张表),不拿正则解析历史文案。
-- 只回填空值/空串/默认值 medium 的行;已经是 urgent/high/low 的行不动。
--
-- 4. 锁表风险:低。带 DEFAULT 的 ADD COLUMN 在 MySQL 8 走 INSTANT(不重建表)。
-- 刻意不加二级索引:查询过滤条件恒为 user_id + audience,V116 的
-- idx_user_audience_read 已覆盖;严重度只有四个值,宽索引买不到排序收益。
--
-- 5. 验证 SQL(迁移后跑,不许只看启动日志的 Successfully applied):
-- SHOW COLUMNS FROM `biz_user_notification` LIKE 'severity';
-- -> 期望 1 行:Type=varchar(16),Null=NO,Default=medium
-- SELECT severity, COUNT(*) FROM biz_user_notification GROUP BY severity;
-- -> 期望只出现 urgent/high/medium/low 四个值
-- SELECT id, scene, level, severity FROM biz_user_notification ORDER BY id DESC LIMIT 10;
-- -> 抽查:service_down 应为 urgent,task_failed 应为 high,system 应为 low
--
-- 6. 可重跑性:照 V146/V155/V157/V158 惯例,加列前先查 information_schema;
-- 迁移中途失败时 flyway repair + 重启会从第一条语句重跑,裸 ADD COLUMN 会撞 1060。
-- 回填语句本身幂等(只改 medium/空值,重算结果相同)。
--
-- 7. 回滚(人工补丁,写成注释以免被 Flyway 当迁移执行):
-- ALTER TABLE `biz_user_notification` DROP COLUMN `severity`;
-- 仅回滚 jar 不需要 DROP:旧 jar 的实体没有这一列,INSERT 不会写它。
-- =============================================================
SET @has_col := (
SELECT COUNT(*) FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
AND TABLE_NAME = 'biz_user_notification'
AND COLUMN_NAME = 'severity'
);
SET @ddl := IF(@has_col = 0,
'ALTER TABLE `biz_user_notification` ADD COLUMN `severity` varchar(16) NOT NULL DEFAULT ''medium'' COMMENT ''严重度:urgent=紧急/high=高危/medium=中危/low=低危'' AFTER `level`',
'SELECT ''biz_user_notification.severity already exists, skipped'' AS note');
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
UPDATE `biz_user_notification`
SET `severity` = CASE
WHEN `scene` = 'service_down' THEN 'urgent'
WHEN `scene` = 'secret_balance' AND `level` = 'error' THEN 'urgent'
WHEN `scene` IN ('maixiang_anomaly', 'secret_invalid', 'task_failed') THEN 'high'
WHEN `scene` IN ('task_partial', 'secret_balance') THEN 'medium'
WHEN `scene` = 'system' THEN 'low'
WHEN `level` = 'error' THEN 'urgent'
WHEN `level` = 'warning' THEN 'high'
WHEN `level` = 'info' THEN 'low'
ELSE 'medium'
END
WHERE `severity` IS NULL OR `severity` = '' OR `severity` = 'medium';
@@ -37,7 +37,7 @@ 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),
"task_partial", LocalDate.of(2026, 9, 12), 1160L, false);
"task_partial", LocalDate.of(2026, 9, 12), 1160L, false, NotificationService.SORT_TIME);
verify(notificationService).summary(24L, NotificationService.AUDIENCE_ADMIN);
ArgumentCaptor<NotificationPageQuery> queryCaptor = ArgumentCaptor.forClass(NotificationPageQuery.class);
@@ -55,6 +55,7 @@ class AdminNotificationControllerTest {
assertThat(query.getDay()).isEqualTo(LocalDate.of(2026, 9, 12));
assertThat(query.getSubjectUserId()).isEqualTo(1160L);
assertThat(query.getSubjectUnlabelled()).isFalse();
assertThat(query.getSort()).isEqualTo(NotificationService.SORT_TIME);
}
/** 聚合视图与单条列表读的是同一份"谁的副本",这里守 groups 这条新出口别绕过管理员维度。 */
@@ -62,10 +63,11 @@ class AdminNotificationControllerTest {
void groupsUseOperatorIdAndAdminAudience() {
when(adminAuthSupport.requireConsoleOperator(request)).thenReturn(admin(24L));
controller.groups(request, 1L, 20L, false, null, null, null, null);
controller.groups(request, 1L, 20L, false, null, null, null, null, NotificationService.SORT_SEVERITY);
verify(notificationService).groups(eq(24L), eq(NotificationService.AUDIENCE_ADMIN),
argThat(query -> query.getPage().equals(1L) && query.getPageSize().equals(20L)));
argThat(query -> query.getPage().equals(1L) && query.getPageSize().equals(20L)
&& NotificationService.SORT_SEVERITY.equals(query.getSort())));
}
@Test
@@ -35,7 +35,7 @@ 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),
"task_failed", LocalDate.of(2026, 9, 5));
"task_failed", LocalDate.of(2026, 9, 5), NotificationService.SORT_TIME);
verify(notificationService).summary(1095L, NotificationService.AUDIENCE_USER);
ArgumentCaptor<NotificationPageQuery> queryCaptor = ArgumentCaptor.forClass(NotificationPageQuery.class);
@@ -50,6 +50,7 @@ class NotificationControllerTest {
assertThat(query.getEndDate()).isEqualTo(LocalDate.of(2026, 9, 13));
assertThat(query.getScene()).isEqualTo("task_failed");
assertThat(query.getDay()).isEqualTo(LocalDate.of(2026, 9, 5));
assertThat(query.getSort()).isEqualTo(NotificationService.SORT_TIME);
// 桌面端的主体用户就是本人,接口不暴露 subjectUserId,展开只靠 场景+自然日
assertThat(query.getSubjectUserId()).isNull();
}
@@ -156,6 +156,33 @@ class NotificationGroupTest {
List.of(headline(6, "t", "c")));
assertThat(groups().getGroups().get(0).getLevel()).isEqualTo("error");
// 严重度同样取组内最高:service_down 不论 level 都是紧急
assertThat(groups().getGroups().get(0).getSeverity())
.isEqualTo(NotificationService.SEVERITY_URGENT);
}
/** 默认按严重度:高危组即使更旧也排在中危组前面;切 time 才回到自然日倒序。 */
@Test
void defaultGroupOrderPutsHigherSeverityFirstAndTimeSortRestoresDayOrder() {
stub(List.of(
row(9, "task_partial", 1160L, LocalDate.of(2026, 10, 13), "warning", null),
row(8, "task_failed", 1160L, LocalDate.of(2026, 10, 12), "warning", null)),
List.of(headline(9, "t", "c"), headline(8, "t", "c")));
NotificationGroupPageVo bySeverity = groups();
assertThat(bySeverity.getGroups()).extracting(NotificationGroupVo::getScene)
.containsExactly("task_failed", "task_partial");
assertThat(bySeverity.getGroups()).extracting(NotificationGroupVo::getSeverity)
.containsExactly(NotificationService.SEVERITY_HIGH, NotificationService.SEVERITY_MEDIUM);
NotificationPageQuery timeQuery = new NotificationPageQuery();
timeQuery.setSort(NotificationService.SORT_TIME);
NotificationGroupPageVo byTime = service.groups(24L, NotificationService.AUDIENCE_ADMIN, timeQuery);
assertThat(byTime.getGroups()).extracting(NotificationGroupVo::getScene)
.containsExactly("task_partial", "task_failed");
assertThat(byTime.getGroups()).extracting(NotificationGroupVo::getDay)
.containsExactly(LocalDate.of(2026, 10, 13), LocalDate.of(2026, 10, 12));
}
@Test
@@ -70,6 +70,7 @@ class NotificationServiceTest {
assertThat(row.getAudience()).isEqualTo("user");
assertThat(row.getScene()).isEqualTo("secret_balance");
assertThat(row.getLevel()).isEqualTo("error");
assertThat(row.getSeverity()).isEqualTo(NotificationService.SEVERITY_URGENT);
assertThat(row.getTitle()).isEqualTo("代理欠费");
assertThat(row.getContent()).isEqualTo("余额不足");
assertThat(row.getDedupeKey()).isEqualTo("secret_balance:7:proxy:20260913");
@@ -335,6 +336,96 @@ class NotificationServiceTest {
.isEqualTo(NotificationService.CATEGORY_CONFIG_ERROR);
}
/** 列表项还必须带严重度:后端是唯一推导源,前端不再各自按 scene/level 猜。 */
@Test
void pageItemsCarrySeverity() {
UserNotificationEntity row = new UserNotificationEntity();
row.setId(9L);
row.setScene(NotificationService.SCENE_TASK_FAILED);
row.setLevel(NotificationService.LEVEL_WARNING);
when(mapper.selectCount(any())).thenReturn(1L, 0L);
when(mapper.selectList(any())).thenReturn(List.of(row));
NotificationPageVo page = service.page(7L, NotificationService.AUDIENCE_USER,
NotificationPageQuery.of(1L, 20L, false, null, null, null, null));
assertThat(page.getItems().get(0).getSeverity())
.isEqualTo(NotificationService.SEVERITY_HIGH);
}
/** 四级严重度的唯一推导口径:scene 优先,level 区分同场景轻重。 */
@Test
void severityMapsScenesAndLevelsToFourBands() {
assertThat(NotificationService.severityOf(NotificationService.SCENE_SERVICE_DOWN,
NotificationService.LEVEL_WARNING)).isEqualTo(NotificationService.SEVERITY_URGENT);
assertThat(NotificationService.severityOf(NotificationService.SCENE_SECRET_BALANCE,
NotificationService.LEVEL_ERROR)).isEqualTo(NotificationService.SEVERITY_URGENT);
assertThat(NotificationService.severityOf(NotificationService.SCENE_SECRET_BALANCE,
NotificationService.LEVEL_WARNING)).isEqualTo(NotificationService.SEVERITY_MEDIUM);
assertThat(NotificationService.severityOf(NotificationService.SCENE_TASK_FAILED,
NotificationService.LEVEL_WARNING)).isEqualTo(NotificationService.SEVERITY_HIGH);
assertThat(NotificationService.severityOf(NotificationService.SCENE_SECRET_INVALID,
NotificationService.LEVEL_WARNING)).isEqualTo(NotificationService.SEVERITY_HIGH);
assertThat(NotificationService.severityOf(NotificationService.SCENE_MAIXIANG_ANOMALY,
NotificationService.LEVEL_WARNING)).isEqualTo(NotificationService.SEVERITY_HIGH);
assertThat(NotificationService.severityOf(NotificationService.SCENE_TASK_PARTIAL,
NotificationService.LEVEL_WARNING)).isEqualTo(NotificationService.SEVERITY_MEDIUM);
assertThat(NotificationService.severityOf(NotificationService.SCENE_SYSTEM,
NotificationService.LEVEL_INFO)).isEqualTo(NotificationService.SEVERITY_LOW);
// 未登记 scene 不让通知失去分档:按 level 兜底
assertThat(NotificationService.severityOf("legacy_scene", NotificationService.LEVEL_ERROR))
.isEqualTo(NotificationService.SEVERITY_URGENT);
assertThat(NotificationService.severityOf("legacy_scene", NotificationService.LEVEL_INFO))
.isEqualTo(NotificationService.SEVERITY_LOW);
assertThat(NotificationService.severityOf(null, null))
.isEqualTo(NotificationService.SEVERITY_MEDIUM);
assertThat(NotificationService.severityRank(NotificationService.SEVERITY_URGENT))
.isGreaterThan(NotificationService.severityRank(NotificationService.SEVERITY_HIGH));
assertThat(NotificationService.severityRank(NotificationService.SEVERITY_HIGH))
.isGreaterThan(NotificationService.severityRank(NotificationService.SEVERITY_MEDIUM));
assertThat(NotificationService.severityRank(NotificationService.SEVERITY_MEDIUM))
.isGreaterThan(NotificationService.severityRank(NotificationService.SEVERITY_LOW));
}
/** 默认排序必须在 SQL 侧按严重度分档;分页不能先按 id 取一页再在内存里排。 */
@Test
@SuppressWarnings("unchecked")
void pageDefaultSortUsesSeverityCase() {
when(mapper.selectCount(any())).thenReturn(1L, 0L);
when(mapper.selectList(any())).thenReturn(List.of());
service.page(7L, NotificationService.AUDIENCE_USER,
NotificationPageQuery.of(1L, 20L, false, null, null, null, null));
ArgumentCaptor<LambdaQueryWrapper<UserNotificationEntity>> captor =
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(mapper).selectList(captor.capture());
assertThat(captor.getValue().getSqlSegment())
.contains("CASE severity")
.contains("'urgent'")
.contains("'low'");
}
/** 切到时间排序时不能再套严重度 CASE,否则「按时间」只是同一档内的局部排序。 */
@Test
@SuppressWarnings("unchecked")
void pageTimeSortDoesNotUseSeverityCase() {
when(mapper.selectCount(any())).thenReturn(1L, 0L);
when(mapper.selectList(any())).thenReturn(List.of());
NotificationPageQuery query = NotificationPageQuery.of(1L, 20L, false, null, null, null, null);
query.setSort(NotificationService.SORT_TIME);
service.page(7L, NotificationService.AUDIENCE_USER, query);
ArgumentCaptor<LambdaQueryWrapper<UserNotificationEntity>> captor =
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
verify(mapper).selectList(captor.capture());
assertThat(captor.getValue().getSqlSegment())
.doesNotContain("CASE severity")
.contains("ORDER BY")
.contains("id DESC");
}
@Test
@SuppressWarnings("unchecked")
void summaryAndUnreadCountScopeByReceiverAndAudience() {
@@ -35,11 +35,29 @@ export const NOTIFICATION_CATEGORY_OPTIONS: ReadonlyArray<{
export type NotificationLevel = 'info' | 'warning' | 'error'
/** 业务严重度:紧急 / 高危 / 中危 / 低危(后端按 scene + level 推导,前端只展示与排序)。 */
export type NotificationSeverity = 'urgent' | 'high' | 'medium' | 'low'
/** 列表排序:默认按严重度;time=按时间倒序。 */
export type NotificationSortMode = 'severity' | 'time'
export const NOTIFICATION_SEVERITY_LABELS: Readonly<Record<NotificationSeverity, string>> = {
urgent: '紧急',
high: '高危',
medium: '中危',
low: '低危',
}
/** 优先级顺序:排序/筛选选项都从这里取,避免两份顺序漂移。 */
export const NOTIFICATION_SEVERITY_ORDER: readonly NotificationSeverity[] = ['urgent', 'high', 'medium', 'low']
export interface NotificationItem {
id: number
scene: string
category: string
level: string
/** 业务严重度;旧后端不返回时前端按 level 兜底。 */
severity?: string
title: string
content: string
read: boolean
@@ -72,6 +90,8 @@ export interface NotificationGroup {
rowCount: number
unreadCount: number
level: string
/** 组内最高严重度。 */
severity?: string
title: string
content: string
createdAt: string | null
@@ -108,6 +128,8 @@ export interface NotificationListParams {
category?: string
startDate?: string
endDate?: string
/** 排序:severity(默认)或 time;默认值不下发,由后端兜底。 */
sort?: NotificationSortMode
/** 展开聚合组:两个条件取自该组自己返回的值,原样回传(空表示不限制)。 */
scene?: string
day?: string
@@ -144,6 +166,10 @@ export function buildNotificationListQuery(
if (params.endDate) {
query.endDate = params.endDate
}
// severity 是后端默认值,不必下发;只有切到时间排序时才带参,减少老后端/日志噪音。
if (params.sort === 'time') {
query.sort = 'time'
}
if (params.scene) {
query.scene = params.scene
}
@@ -124,6 +124,25 @@
{{ option.label }}
</button>
</div>
<div class="bell-sort-chips" role="group" aria-label="通知排序">
<span class="bell-sort-label">排序</span>
<button
type="button"
class="bell-chip"
:class="{ 'is-active': sortMode === 'severity' }"
@click="setSortMode('severity')"
>
严重度
</button>
<button
type="button"
class="bell-chip"
:class="{ 'is-active': sortMode === 'time' }"
@click="setSortMode('time')"
>
时间
</button>
</div>
<div class="bell-search-days">
<el-date-picker
:model-value="dateRange"
@@ -179,7 +198,8 @@
<ul v-else class="bell-list">
<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-if="sortMode === 'time' && startsNewDay(index)" class="bell-day-head">{{ formatDayLabel(group.day) }}</li>
<li
class="bell-item bell-group"
:class="[`bell-item--${itemLevel(group)}`, { 'bell-group--open': isExpanded(group) }]"
@@ -188,6 +208,9 @@
<NotificationLevelIcon :level="itemLevel(group)" />
<div class="bell-item-main">
<div class="bell-item-head">
<span class="bell-severity-tag" :class="`bell-severity-tag--${itemSeverity(group)}`">
{{ severityLabel(group) }}
</span>
<span class="bell-item-title" :title="group.title">{{ group.title }}</span>
<span
class="bell-item-dot"
@@ -217,6 +240,9 @@
<NotificationLevelIcon :level="itemLevel(item)" />
<div class="bell-item-main">
<div class="bell-item-head">
<span class="bell-severity-tag" :class="`bell-severity-tag--${itemSeverity(item)}`">
{{ severityLabel(item) }}
</span>
<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>
@@ -275,6 +301,8 @@ import { NOTIFICATION_CATEGORY_OPTIONS } from '@/shared/api/types/modules/notifi
import {
PANEL_PAGE_SIZES as PAGE_SIZES,
itemLevel,
itemSeverity,
severityLabel,
startsNewDay as groupStartsNewDay,
useNotificationBellPanel,
} from '@/shared/composables/useNotificationBellPanel'
@@ -329,6 +357,8 @@ const {
resetFilters,
rowCount,
selectCategory,
setSortMode,
sortMode,
toggleGroup,
total,
totalPages,
@@ -718,6 +748,18 @@ onUnmounted(() => {
font-weight: 500;
}
.bell-sort-chips {
display: flex;
align-items: center;
gap: 6px;
}
.bell-sort-label {
margin-right: 2px;
color: var(--bell-text-mute);
font-size: 11px;
}
.bell-search-days {
display: flex;
align-items: center;
@@ -933,6 +975,56 @@ onUnmounted(() => {
white-space: nowrap;
}
.bell-severity-tag {
flex: 0 0 auto;
padding: 1px 6px;
border: 1px solid currentColor;
border-radius: 999px;
font-size: 10.5px;
font-weight: 600;
line-height: 1.5;
}
.bell-severity-tag--urgent {
background: rgba(255, 123, 123, 0.12);
color: #ff7b7b;
}
.bell-severity-tag--high {
background: rgba(240, 187, 97, 0.12);
color: #f0bb61;
}
.bell-severity-tag--medium {
background: rgba(110, 168, 255, 0.12);
color: #6ea8ff;
}
.bell-severity-tag--low {
background: rgba(147, 161, 179, 0.12);
color: #93a1b3;
}
.bell-panel--light .bell-severity-tag--urgent {
background: #fdecec;
color: #c92a2a;
}
.bell-panel--light .bell-severity-tag--high {
background: #fdf3e2;
color: #b26a12;
}
.bell-panel--light .bell-severity-tag--medium {
background: #eaf2fb;
color: #2f6fb3;
}
.bell-panel--light .bell-severity-tag--low {
background: #f1f4f7;
color: #6b7c8e;
}
.bell-item--unread .bell-item-title {
color: var(--bell-text);
font-weight: 700;
@@ -12,6 +12,7 @@ import { computed, onUnmounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
NOTIFICATION_SEVERITY_LABELS,
fetchNotificationGroups,
fetchNotificationList,
fetchNotificationSummary,
@@ -20,6 +21,8 @@ import {
type NotificationGroup,
type NotificationItem,
type NotificationListParams,
type NotificationSeverity,
type NotificationSortMode,
} from '@/shared/api/types/modules/notification'
import {
hasNewNotification,
@@ -51,10 +54,14 @@ export function normalizedDayRange(range: [string, string] | null): { startDate?
}
/** 下钻条件:三维缺一维就会把别的主体的行混进这一组的明细(同场景同一天有好几组)。 */
export function detailQueryFor(group: NotificationGroup): NotificationListParams {
export function detailQueryFor(
group: NotificationGroup,
sort: NotificationSortMode = 'severity',
): NotificationListParams {
return {
page: 1,
pageSize: PANEL_DETAIL_LIMIT,
sort,
scene: group.scene,
day: group.day,
subjectUserId: group.subjectUserId,
@@ -106,6 +113,22 @@ export function itemLevel(item: { level: string }): 'error' | 'warning' | 'info'
return item.level === 'error' || item.level === 'info' ? item.level : 'warning'
}
/** 严重度兜底:新后端直接给 severity;旧后端没这列时按 level 推,绝不让标签空白。 */
export function itemSeverity(item: { severity?: string | null; level?: string | null }): NotificationSeverity {
const value = item.severity
if (value === 'urgent' || value === 'high' || value === 'medium' || value === 'low') {
return value
}
if (item.level === 'error') return 'urgent'
if (item.level === 'info') return 'low'
return 'high'
}
/** 中文标签:紧急/高危/中危/低危。 */
export function severityLabel(item: { severity?: string | null; level?: string | null }): string {
return NOTIFICATION_SEVERITY_LABELS[itemSeverity(item)]
}
export function useNotificationBellPanel(options: { uid: () => string }) {
const uid = options.uid
@@ -122,6 +145,8 @@ export function useNotificationBellPanel(options: { uid: () => string }) {
const keyword = ref('')
const dateRange = ref<[string, string] | null>(null)
const category = ref('')
/** 默认按严重度;用户可切「按时间」。 */
const sortMode = ref<NotificationSortMode>('severity')
const expandedKey = ref('')
const details = ref<NotificationItem[]>([])
const detailTotal = ref(0)
@@ -180,6 +205,7 @@ export function useNotificationBellPanel(options: { uid: () => string }) {
pageSize: pageSize.value,
keyword: keyword.value,
category: category.value,
sort: sortMode.value,
...normalizedDayRange(dateRange.value),
})
const applied = applyGroupsPage(result, {
@@ -221,7 +247,7 @@ export function useNotificationBellPanel(options: { uid: () => string }) {
expandedKey.value = key
detailLoading.value = true
try {
const result = await fetchNotificationList(detailQueryFor(group))
const result = await fetchNotificationList(detailQueryFor(group, sortMode.value))
// 请求期间用户可能已经收了另一组:晚到的结果不能盖掉当前展开的那组
if (expandedKey.value !== key) return
details.value = Array.isArray(result?.items) ? result.items : []
@@ -255,6 +281,16 @@ export function useNotificationBellPanel(options: { uid: () => string }) {
void loadPage(1)
}
/** 排序切换:重复点同一个不重复请求;切换后回到第一页并收起明细。 */
function setSortMode(value: NotificationSortMode) {
if (sortMode.value === value) {
return
}
sortMode.value = value
console.log('[notification] 排序切换为', value === 'time' ? '按时间' : '按严重度')
void loadPage(1)
}
/** 类型筛选:重复点同一个不重复请求;切换后回到第一页。 */
function selectCategory(value: string) {
if (category.value === value) {
@@ -370,6 +406,8 @@ export function useNotificationBellPanel(options: { uid: () => string }) {
resetFilters,
rowCount,
selectCategory,
setSortMode,
sortMode,
toggleGroup,
total,
totalPages,
@@ -40,6 +40,7 @@ const api = vi.hoisted(() => ({
vi.mock('element-plus', () => ({ ElMessage: message }))
vi.mock('@/shared/api/types/modules/notification.ts', () => ({
NOTIFICATION_CATEGORY_OPTIONS: [],
NOTIFICATION_SEVERITY_LABELS: { urgent: '紧急', high: '高危', medium: '中危', low: '低危' },
fetchNotificationSummary: api.fetchNotificationSummary,
fetchNotificationGroups: api.fetchNotificationGroups,
fetchNotificationList: api.fetchNotificationList,
@@ -174,6 +175,49 @@ describe('NotificationBell:三处失败的用户可见性', () => {
expect(message.error).not.toHaveBeenCalled()
expect(document.querySelectorAll('.bell-item')).toHaveLength(0)
})
it('默认展示四级严重度并按严重度请求;切「时间」后带 sort=time 重查并恢复日期头', async () => {
api.fetchNotificationGroups.mockResolvedValue({
groups: [
group({ latestId: 9, severity: 'urgent', level: 'error', day: '2026-09-13' }),
group({ latestId: 8, subjectUserId: 1160, severity: 'low', level: 'info', day: '2026-09-12' }),
],
total: 2,
rowCount: 2,
unreadGroupCount: 2,
unreadCount: 2,
})
await openPanel()
expect(Array.from(document.querySelectorAll('.bell-severity-tag')).map((el) => el.textContent?.trim()))
.toEqual(['紧急', '低危'])
expect(api.fetchNotificationGroups.mock.calls[0][0].sort).toBe('severity')
// 严重度排序会跨天交错,不挂日期头
expect(document.querySelectorAll('.bell-day-head')).toHaveLength(0)
// 展开明细也要带同一种排序,否则会出现「列表按严重度、明细又按时间」
api.fetchNotificationList.mockResolvedValue({
items: [notification({ id: 9, severity: 'urgent' })],
total: 1,
page: 1,
pageSize: 50,
unreadCount: 1,
})
await expandFirstGroup()
expect(api.fetchNotificationList.mock.calls.at(-1)?.[0].sort).toBe('severity')
const timeButton = Array.from(document.querySelectorAll<HTMLElement>('.bell-sort-chips button'))
.find((button) => button.textContent?.includes('时间'))
expect(timeButton).toBeTruthy()
timeButton!.click()
await flushPromises()
expect(api.fetchNotificationGroups.mock.calls.at(-1)?.[0].sort).toBe('time')
expect(document.querySelectorAll('.bell-day-head')).toHaveLength(2)
await expandFirstGroup()
expect(api.fetchNotificationList.mock.calls.at(-1)?.[0].sort).toBe('time')
})
})
describe('NotificationBell:聚合两级与红点口径', () => {
@@ -127,6 +127,12 @@ test('buildNotificationListQuery:关键字去空白、空条件不下发、分
})
/** 类型筛选项必须与后端四个大类逐一对应,漏一个用户就永远筛不到那类通知。 */
test('排序参数:默认由后端按严重度,只有切时间排序才下发 sort=time', () => {
assert.equal('sort' in buildNotificationListQuery(), false, '默认 severity 不下发,后端默认即严重度')
assert.equal(buildNotificationListQuery({ sort: 'severity' }).sort, undefined)
assert.equal(buildNotificationListQuery({ sort: 'time' }).sort, 'time')
})
test('类型筛选项覆盖后端四个大类且标签非空', () => {
assert.deepEqual(
NOTIFICATION_CATEGORY_OPTIONS.map((option) => option.value),
@@ -18,7 +18,9 @@ import {
applyMarkReadToCounts,
detailQueryFor,
itemLevel,
itemSeverity,
normalizedDayRange,
severityLabel,
startsNewDay,
} from '@/shared/composables/useNotificationBellPanel'
@@ -112,4 +114,21 @@ describe('用户端通知面板层纯函数', () => {
expect(itemLevel({ level: 'warn' })).toBe('warning')
expect(itemLevel({ level: '' })).toBe('warning')
})
it('四级严重度:后端给值原样用,旧后端缺字段按 level 兜底,绝不出现空标签', () => {
expect(itemSeverity({ severity: 'urgent', level: 'warning' })).toBe('urgent')
expect(itemSeverity({ severity: 'high' })).toBe('high')
expect(itemSeverity({ severity: 'medium' })).toBe('medium')
expect(itemSeverity({ severity: 'low' })).toBe('low')
expect(itemSeverity({ level: 'error' })).toBe('urgent')
expect(itemSeverity({ level: 'info' })).toBe('low')
expect(itemSeverity({ level: 'warning' })).toBe('high')
expect(itemSeverity({ level: '' })).toBe('high')
expect(itemSeverity({ severity: 'fatal', level: 'warning' })).toBe('high')
expect(severityLabel({ severity: 'urgent' })).toBe('紧急')
expect(severityLabel({ severity: 'high' })).toBe('高危')
expect(severityLabel({ severity: 'medium' })).toBe('中危')
expect(severityLabel({ severity: 'low' })).toBe('低危')
})
})