Files
crawler-plugin/admin-frontend-vue/src/components/NotificationBell.vue
T
huangzd1997 6d46506726 fix: 全维度审查修复(安全/正确性/性能/稳定性/客户端/前端)
安全
- /api/ziniao/** 五个匿名接口加管理员鉴权(此前可匿名换取任意员工店铺登录令牌)
- 删除 Flask 遗留后门:默认密码建超管 + 每次启动写生产 users 表(服务端与客户端各一份)
- 进度/详情接口归属过滤:新增 TaskProgressOwnershipSupport,11 模块 progress/light 与
  /tasks/batch 接入,DTO 补 userId,前端 13 个查询封装补传(未传时后端不过滤,兼容旧端)
- 代理提取链接(含账密)不再明文入日志(新增 common/util/SecretMasking)
- 全局异常兜底不再回传原始异常信息;内部令牌比较改常量时间
- 登录加失败计数与锁定(10 次锁 15 分钟);品牌源文件下载加 SSRF 防护
- AdminApiGuardFilter 覆盖前缀从 2 扩到 15(开关默认 false,行为不变,为收紧做准备)
- 生产关闭 springdoc/knife4j(/doc.html 匿名可读全部接口定义)

正确性
- 40901/40902 拆分:锁竞争不再被伪装成 success=true(此前客户端停止重试、分片静默丢失)
- 假成功收敛:集采明细批量写失败改为抛出、去重 worker 异常标失败、4 个 worker 改判
  success 字段、publish 空 ASIN 行参与批次 flush、巡店删除全失败带 error 上报
- 客户端心跳 discard 移入 finally(7 模块,失败路径不再留僵尸 RUNNING 任务)
- 状态机条件更新:跟价停止循环、集采 activate/fail、imagevideo 归档回填、店铺匹配提交

性能
- 前端入口包 JS 1.05MB→204KB、CSS 355KB→10.7KB(Element Plus 改按需 + el-config-provider)
- 载荷引用计数按指针里的 taskId 收敛(原 JSON 列 IN 全表扫且逐行调用)
- 店铺明细多值批量 INSERT;快照 upsert 预载缓存;结果文件列改单条 UPDATE
- 新增迁移 V120(补 3 个缺失索引)/V121(删 4 个被覆盖的冗余索引)/V122(URL 前缀索引)

稳定性
- 新增 common/util/ThreadPools 有界线程池替换 5 处无界队列(防堆积 OOM)
- Redis 锁释放改 Lua 原子校验(原裸 delete 会误删他人已过期的锁)
- imagevideo 加死节点接管;锁续期失败重试;调度池 4→16;openStream 全部加超时
- 事务内远程对象删除移到提交后;启动恢复锁按实例命名

客户端
- 不再 taskkill /f /im chrome.exe(改为按调试端口精准回收,不杀用户自己的浏览器)
- 密码检测不再无条件杀紫鸟进程;品牌检测加全局互斥(代理池不再互相覆盖)
- base_dir 统一到 exe 目录(原被 os.getcwd() 覆盖,日志/缓存会分裂两个目录)
- 缓存加定时清理;图片下载加超时;mkstemp 句柄托管

测试
- 同步更新受影响的契约测试(构造器签名/条件更新/方法改名/新增接口方法等)
- 修复 FaultInjectionTest 等 3 处 mock 未 stub 流式 read 导致的读循环 OOM
- mvn test 2795 个测试全绿
2026-09-14 04:15:36 +08:00

684 lines
17 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<div ref="rootRef" class="admin-notification-bell">
<button
type="button"
class="bell-trigger"
:class="{ 'bell-trigger--active': panelOpen }"
:title="unreadCount > 0 ? `通知(${unreadCount} 条未读)` : '通知'"
aria-label="通知"
@click="togglePanel"
>
<svg
class="bell-icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9" />
<path d="M13.73 21a2 2 0 0 1-3.46 0" />
</svg>
<span v-if="badgeText" class="bell-badge">{{ badgeText }}</span>
</button>
<!-- 面板挂到 body 上(fixed 定位):顶栏内绝对定位时会被列表页 el-select 等页面内容压住,提 z-index 无效 -->
<Teleport to="body">
<div
v-if="panelOpen"
ref="panelRef"
class="bell-panel"
:style="panelStyle"
role="dialog"
aria-label="通知列表"
>
<div class="bell-panel-head">
<span class="bell-panel-title">通知</span>
<button
v-if="unreadCount > 0"
type="button"
class="bell-read-all"
:disabled="markingAll"
@click="readAll"
>
{{ markingAll ? '处理中...' : '全部已读' }}
</button>
</div>
<div class="bell-search">
<input
v-model="keyword"
type="text"
class="bell-search-input"
placeholder="搜索标题或内容"
aria-label="搜索通知"
@input="onKeywordInput"
/>
<div class="bell-search-days">
<el-date-picker
:model-value="dateRangeValue"
type="daterange"
value-format="YYYY-MM-DD"
start-placeholder="开始日期"
end-placeholder="结束日期"
range-separator="至"
size="small"
class="bell-date-picker"
popper-class="bell-date-popper"
:clearable="true"
@update:model-value="onDateRangeChange"
@change="reload"
/>
<button v-if="hasFilter" type="button" class="bell-search-reset" @click="resetFilters">
重置
</button>
</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>
<ul v-else class="bell-list">
<template v-for="group in groupedItems" :key="group.day || 'unknown'">
<li class="bell-day-head">{{ group.label }}</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)"
>
<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>
</template>
</ul>
<div class="bell-panel-foot">
<button
type="button"
class="bell-page-btn"
:disabled="page <= 1 || loading"
@click="goPage(page - 1)"
>
上一页
</button>
<span class="bell-page-info">{{ page }} / {{ totalPages }}</span>
<button
type="button"
class="bell-page-btn"
:disabled="page >= totalPages || loading"
@click="goPage(page + 1)"
>
下一页
</button>
<span class="bell-page-total">共 {{ total }} 条</span>
</div>
</div>
</Teleport>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
fetchNotificationList,
fetchNotificationSummary,
markAllNotificationsRead,
markNotificationRead,
type AdminNotificationItem,
} from '@/api/notifications'
import { useAdminSessionStore } from '@/stores/admin-session'
import {
NOTIFICATION_POLL_INTERVAL_MS,
formatNotificationTime,
formatUnreadBadge,
groupNotificationsByDay,
hasNewNotification,
readLastNotifiedId,
writeLastNotifiedId,
} from '@/layout/notification-bell-model'
const PAGE_SIZE = 10
const session = useAdminSessionStore()
const rootRef = ref<HTMLElement | null>(null)
const panelRef = ref<HTMLElement | null>(null)
const panelStyle = ref<Record<string, string>>({})
const unreadCount = ref(0)
const items = ref<AdminNotificationItem[]>([])
const total = ref(0)
const page = ref(1)
const panelOpen = ref(false)
const loading = ref(false)
const markingAll = ref(false)
const loadError = ref('')
const keyword = ref('')
const startDate = ref('')
const endDate = ref('')
const badgeText = computed(() => formatUnreadBadge(unreadCount.value))
const groupedItems = computed(() => groupNotificationsByDay(items.value))
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / PAGE_SIZE)))
const hasFilter = computed(() => Boolean(keyword.value.trim() || startDate.value || endDate.value))
/**
* el-date-picker 的绑定桥:日期区间在内部仍用 startDate/endDate 两个 ref 表示
* (hasFilter/normalizedDayRange/resetFilters 都基于它们)。
* 此前模板写的是 v-model="dateRange",而 dateRange 从未声明 → vue-tsc 直接报 TS2339 构建失败,
* 且日期筛选完全不下发参数。
*/
const dateRangeValue = computed<[string, string] | null>(() =>
startDate.value && endDate.value ? [startDate.value, endDate.value] : null
)
function onDateRangeChange(value: [string, string] | null) {
const start = value?.[0]
const end = value?.[1]
startDate.value = start ? String(start) : ''
endDate.value = end ? String(end) : ''
}
let pollTimer: number | null = null
let searchTimer: number | null = null
function currentUid(): number | string {
return session.user?.id ?? 0
}
/** 起止日期倒挂时自动交换,避免用户只看到「没有符合条件的通知」不知原因。 */
function normalizedDayRange(): { startDate?: string; endDate?: string } {
let start = startDate.value
let end = endDate.value
if (start && end && start > end) {
const swapped = start
start = end
end = swapped
}
return { startDate: start || undefined, endDate: end || undefined }
}
/** 拉未读数:发现新通知提醒一次(localStorage 记录已提醒过的最大 id,避免重复弹)。 */
async function refreshSummary() {
try {
const summary = await fetchNotificationSummary()
unreadCount.value = Number(summary?.unreadCount ?? 0)
const latestId = Number(summary?.latestId ?? 0)
if (hasNewNotification(latestId, readLastNotifiedId(currentUid()))) {
ElMessage.warning('收到新的告警通知,请点击右上角铃铛查看')
writeLastNotifiedId(currentUid(), latestId)
console.log('[admin-notification] 检测到新通知 latestId=', latestId)
}
} catch (error) {
// 通知接口失败静默降级:不显示红点、不打扰使用者
console.warn('[admin-notification] 未读数刷新失败(静默降级):', error)
}
}
async function loadPage(targetPage: number) {
if (loading.value) return
loading.value = true
try {
const result = await fetchNotificationList({
page: targetPage,
pageSize: PAGE_SIZE,
keyword: keyword.value,
...normalizedDayRange(),
})
const list = Array.isArray(result?.items) ? result.items : []
items.value = list
total.value = Number(result?.total ?? list.length)
unreadCount.value = Number(result?.unreadCount ?? unreadCount.value)
page.value = targetPage
loadError.value = ''
// 无筛选时首页就是最新数据,顺带记录「已提醒过的最大 id」;有筛选时最新 id 不代表真实最新
if (targetPage <= 1 && !hasFilter.value && list.length) {
const latest = Number(list[0].id)
if (latest > 0) {
writeLastNotifiedId(currentUid(), Math.max(readLastNotifiedId(currentUid()), latest))
}
}
} catch (error) {
// 列表加载失败在面板内提示,不弹全局消息打扰用户
console.warn('[admin-notification] 通知列表加载失败:', error)
loadError.value = error instanceof Error ? error.message : '通知加载失败'
} finally {
loading.value = false
}
}
function goPage(targetPage: number) {
const safe = Math.min(Math.max(1, targetPage), totalPages.value)
if (safe === page.value || loading.value) return
void loadPage(safe)
}
/** 搜索/日期变化后回到第一页重新查询。 */
function reload() {
void loadPage(1)
}
/** 关键字输入防抖 300ms,避免每敲一个字都打一次接口。 */
function onKeywordInput() {
if (searchTimer != null) {
window.clearTimeout(searchTimer)
}
searchTimer = window.setTimeout(() => {
searchTimer = null
void loadPage(1)
}, 300)
}
function resetFilters() {
keyword.value = ''
startDate.value = ''
endDate.value = ''
void loadPage(1)
}
/** 面板挂到 body 后用 fixed 定位,位置按触发器实时算(右对齐在铃铛下方)。 */
function syncPanelPosition() {
const trigger = rootRef.value
if (!trigger) return
const rect = trigger.getBoundingClientRect()
panelStyle.value = {
top: `${Math.round(rect.bottom + 10)}px`,
right: `${Math.max(8, Math.round(window.innerWidth - rect.right))}px`,
}
}
function togglePanel() {
panelOpen.value = !panelOpen.value
if (panelOpen.value) {
syncPanelPosition()
void loadPage(1)
}
}
async function onItemClick(item: AdminNotificationItem) {
if (item.read) return
try {
await markNotificationRead(item.id)
item.read = true
unreadCount.value = Math.max(0, unreadCount.value - 1)
} catch (error) {
console.warn('[admin-notification] 标记已读失败:', error)
}
}
async function readAll() {
if (markingAll.value || unreadCount.value === 0) return
markingAll.value = true
try {
await markAllNotificationsRead()
for (const item of items.value) {
item.read = true
}
unreadCount.value = 0
} catch (error) {
console.warn('[admin-notification] 全部已读失败:', error)
ElMessage.error(error instanceof Error ? error.message : '操作失败')
} finally {
markingAll.value = false
}
}
function formatTime(value: string | null) {
return formatNotificationTime(value)
}
/** 点击组件外部关闭面板(面板已 Teleport 到 body,需连同面板自身一起判断)。 */
function onDocumentMouseDown(event: MouseEvent) {
if (!panelOpen.value) return
const target = event.target
if (!(target instanceof Node)) return
if (rootRef.value?.contains(target) || panelRef.value?.contains(target)) return
panelOpen.value = false
}
/** 窗口尺寸变化时重新对齐面板。 */
function onWindowResize() {
if (panelOpen.value) {
syncPanelPosition()
}
}
/** 页面回到前台时立即刷新一次未读数。 */
function onVisibilityChange() {
if (typeof document !== 'undefined' && document.visibilityState === 'visible') {
void refreshSummary()
}
}
onMounted(() => {
document.addEventListener('mousedown', onDocumentMouseDown)
document.addEventListener('visibilitychange', onVisibilityChange)
window.addEventListener('resize', onWindowResize)
void refreshSummary()
pollTimer = window.setInterval(() => {
if (typeof document !== 'undefined' && document.visibilityState !== 'visible') {
return
}
void refreshSummary()
}, NOTIFICATION_POLL_INTERVAL_MS)
})
onUnmounted(() => {
document.removeEventListener('mousedown', onDocumentMouseDown)
document.removeEventListener('visibilitychange', onVisibilityChange)
window.removeEventListener('resize', onWindowResize)
if (pollTimer != null) {
window.clearInterval(pollTimer)
pollTimer = null
}
if (searchTimer != null) {
window.clearTimeout(searchTimer)
searchTimer = null
}
})
</script>
<style scoped>
.admin-notification-bell {
position: relative;
display: inline-flex;
align-items: center;
}
.bell-trigger {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
width: 36px;
height: 36px;
padding: 0;
border: 1px solid transparent;
border-radius: 9px;
background: transparent;
color: var(--admin-muted, #5b6f83);
cursor: pointer;
transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;
}
.bell-trigger:hover,
.bell-trigger--active {
background: #edf5fb;
border-color: #cbd9e6;
color: var(--admin-primary-strong, #2f5d8b);
}
.bell-icon {
width: 20px;
height: 20px;
}
.bell-badge {
position: absolute;
top: 1px;
right: 0;
min-width: 16px;
height: 16px;
padding: 0 4px;
box-sizing: border-box;
border-radius: 999px;
background: #d64545;
color: #ffffff;
font-size: 10px;
font-weight: 700;
line-height: 16px;
text-align: center;
pointer-events: none;
}
.bell-panel {
position: fixed;
z-index: 3200;
width: 380px;
max-width: calc(100vw - 32px);
max-height: 520px;
display: flex;
flex-direction: column;
border: 1px solid var(--admin-border, #d8e3ee);
border-radius: 12px;
background: #ffffff;
box-shadow: 0 18px 48px rgba(39, 67, 94, 0.22);
overflow: hidden;
}
.bell-panel-head {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 14px;
border-bottom: 1px solid #edf1f5;
}
.bell-panel-title {
color: var(--admin-text, #24384d);
font-size: 14px;
font-weight: 700;
}
.bell-read-all {
border: none;
background: transparent;
color: var(--admin-primary-strong, #2f5d8b);
font-size: 12px;
cursor: pointer;
padding: 0;
}
.bell-read-all:disabled {
opacity: 0.55;
cursor: not-allowed;
}
.bell-empty {
padding: 36px 0;
color: #8a99a8;
font-size: 13px;
text-align: center;
}
.bell-empty--error {
color: #b23c3c;
}
.bell-list {
flex: 1;
margin: 0;
padding: 0;
list-style: none;
overflow-y: auto;
}
.bell-item {
padding: 11px 14px;
border-bottom: 1px solid #f0f3f7;
cursor: pointer;
transition: background 0.12s ease;
}
.bell-item:hover {
background: #f7f9fc;
}
.bell-item--unread {
background: #f2f6ff;
}
.bell-item--unread .bell-item-title::before {
content: '';
display: inline-block;
width: 7px;
height: 7px;
margin-right: 7px;
border-radius: 50%;
background: #d64545;
vertical-align: 1px;
}
.bell-item-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
}
.bell-item-title {
color: var(--admin-text, #24384d);
font-size: 13px;
font-weight: 700;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.bell-item--error .bell-item-title {
color: #b23c3c;
}
.bell-item--warning .bell-item-title {
color: #a8793e;
}
.bell-item--info .bell-item-title {
color: var(--admin-primary-strong, #2f5d8b);
}
.bell-item-time {
flex-shrink: 0;
color: #9aa6b3;
font-size: 11px;
}
.bell-item-content {
margin-top: 4px;
color: #667085;
font-size: 12px;
line-height: 1.55;
word-break: break-all;
}
.bell-search {
display: flex;
flex-direction: column;
gap: 6px;
padding: 10px 12px;
border-bottom: 1px solid #edf1f5;
background: #fafcfe;
}
.bell-search-input,
.bell-date-input {
height: 28px;
padding: 0 8px;
box-sizing: border-box;
border: 1px solid #d8e3ee;
border-radius: 6px;
background: #ffffff;
color: var(--admin-text, #24384d);
font-size: 12px;
outline: none;
}
.bell-search-input {
width: 100%;
}
.bell-search-input:focus,
.bell-date-input:focus {
border-color: var(--admin-primary-strong, #2f5d8b);
}
.bell-search-days {
display: flex;
align-items: center;
gap: 6px;
}
.bell-date-input {
flex: 1;
min-width: 0;
}
.bell-date-sep {
color: #8a99a8;
font-size: 12px;
}
.bell-search-reset {
flex-shrink: 0;
padding: 0 8px;
height: 28px;
border: 1px solid #d8e3ee;
border-radius: 6px;
background: #ffffff;
color: var(--admin-primary-strong, #2f5d8b);
font-size: 12px;
cursor: pointer;
}
.bell-search-reset:hover {
background: #edf5fb;
}
.bell-day-head {
padding: 6px 14px;
background: #f4f7fa;
color: #7c8b9a;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.02em;
}
.bell-panel-foot {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
padding: 7px 12px;
border-top: 1px solid #edf1f5;
}
.bell-page-btn {
padding: 3px 10px;
border: 1px solid #d8e3ee;
border-radius: 6px;
background: #ffffff;
color: var(--admin-primary-strong, #2f5d8b);
font-size: 12px;
cursor: pointer;
}
.bell-page-btn:hover:not(:disabled) {
background: #edf5fb;
}
.bell-page-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.bell-page-info {
color: var(--admin-text, #24384d);
font-size: 12px;
font-weight: 600;
}
.bell-page-total {
color: #9aa6b3;
font-size: 11px;
}
</style>