feat(认证/通知): 单设备登录互踢 + 站内通知铃铛系统
- 单设备登录:登录成功即 last-login-wins 绑定 users.machine;非超管旧 token 在下一次受保护请求抛 4011 下线,超管豁免;仅认 token 内签名 deviceId,不用请求头。 前端两端接入踢下线跳转(?kicked=1 提示),V118 清空历史 machine - 站内通知:新增 notification 模块(任务失败扫描 / 密钥欠费 / 下游服务探测三类来源), 前后台铃铛组件 + 轮询;后台列表按主管数据范围(UserDataScopeSupport)过滤;V116 建表 均已于 2026-09-13 部署上线,此次补提交源码(此前仅存在于已部署 JAR/构建产物中)
This commit is contained in:
@@ -209,6 +209,12 @@ export const API_ENDPOINTS = {
|
||||
migrate: '/api/user-secrets/migrate',
|
||||
proxyBalance: '/api/user-secrets/proxy-balance',
|
||||
},
|
||||
notification: {
|
||||
summary: '/api/notifications/summary',
|
||||
list: '/api/notifications',
|
||||
read: '/api/notifications/{id}/read',
|
||||
readAll: '/api/notifications/read-all',
|
||||
},
|
||||
collectData: {
|
||||
parse: '/api/collect-data/parse',
|
||||
countryPreference: '/api/collect-data/country-preference',
|
||||
|
||||
@@ -5,6 +5,7 @@ import axios, {
|
||||
type AxiosResponse,
|
||||
type InternalAxiosRequestConfig,
|
||||
} from 'axios'
|
||||
import { handleKicked, isKickedPayload } from '../auth/kick-handler.ts'
|
||||
|
||||
export interface LegacyApiSuccess<T> {
|
||||
success: true
|
||||
@@ -50,6 +51,27 @@ export function extractErrorMessage(error: unknown) {
|
||||
return error instanceof Error ? error.message : '请求失败'
|
||||
}
|
||||
|
||||
/** 从 axios 错误对象里取响应体(兼容真实 AxiosError 与测试桩)。 */
|
||||
function responsePayloadOf(error: unknown): unknown {
|
||||
return (error as { response?: { data?: unknown } } | null | undefined)?.response?.data
|
||||
}
|
||||
|
||||
/** 响应成功分支:Java 业务错误是 HTTP 200 + body.code,互踢下线必须在这里也判。 */
|
||||
export function onResponseFulfilled(response: AxiosResponse): AxiosResponse {
|
||||
if (isKickedPayload(response.data)) {
|
||||
handleKicked()
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
/** 响应失败分支:折叠为 Error 之前先判互踢下线(HTTP 401 等状态码路径)。 */
|
||||
export function onResponseRejected(error: unknown): Promise<never> {
|
||||
if (isKickedPayload(responsePayloadOf(error))) {
|
||||
handleKicked()
|
||||
}
|
||||
return Promise.reject(new Error(extractErrorMessage(error)))
|
||||
}
|
||||
|
||||
function createHttpClient(): AxiosInstance {
|
||||
const instance = axios.create({
|
||||
withCredentials: true,
|
||||
@@ -74,10 +96,7 @@ function createHttpClient(): AxiosInstance {
|
||||
return config
|
||||
})
|
||||
|
||||
instance.interceptors.response.use(
|
||||
(response: AxiosResponse) => response,
|
||||
(error: unknown) => Promise.reject(new Error(extractErrorMessage(error))),
|
||||
)
|
||||
instance.interceptors.response.use(onResponseFulfilled, onResponseRejected)
|
||||
|
||||
return instance
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import { get, post, type JavaApiResponse, unwrapJavaResponse } from '../../http.ts'
|
||||
import { buildJavaUrl } from '../../url.ts'
|
||||
import { API_ENDPOINTS } from '../../endpoints.ts'
|
||||
|
||||
/** 通知场景:密钥欠费 / 密钥失效 / 任务失败 / 服务异常 / 系统。 */
|
||||
export type NotificationScene = 'secret_balance' | 'secret_invalid' | 'task_failed' | 'service_down' | 'system'
|
||||
|
||||
export type NotificationLevel = 'info' | 'warning' | 'error'
|
||||
|
||||
export interface NotificationItem {
|
||||
id: number
|
||||
scene: string
|
||||
level: string
|
||||
title: string
|
||||
content: string
|
||||
read: boolean
|
||||
readAt: string | null
|
||||
createdAt: string | null
|
||||
}
|
||||
|
||||
export interface NotificationPage {
|
||||
items: NotificationItem[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
unreadCount: number
|
||||
}
|
||||
|
||||
export interface NotificationSummary {
|
||||
unreadCount: number
|
||||
latestId: number
|
||||
}
|
||||
|
||||
/** 铃铛轮询:未读数 + 最新通知 id(latestId 增大表示有新通知)。 */
|
||||
export function fetchNotificationSummary() {
|
||||
return unwrapJavaResponse(
|
||||
get<JavaApiResponse<NotificationSummary>>(buildJavaUrl(API_ENDPOINTS.notification.summary)),
|
||||
)
|
||||
}
|
||||
|
||||
export function fetchNotificationList(params: { page?: number; pageSize?: number; onlyUnread?: boolean } = {}) {
|
||||
return unwrapJavaResponse(
|
||||
get<JavaApiResponse<NotificationPage>>(
|
||||
buildJavaUrl(API_ENDPOINTS.notification.list, {
|
||||
page: params.page ?? 1,
|
||||
pageSize: params.pageSize ?? 20,
|
||||
onlyUnread: params.onlyUnread ? 'true' : 'false',
|
||||
}),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
export function markNotificationRead(id: number) {
|
||||
return unwrapJavaResponse(
|
||||
post<JavaApiResponse<boolean>>(
|
||||
buildJavaUrl(API_ENDPOINTS.notification.read.replace('{id}', encodeURIComponent(String(id)))),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
export function markAllNotificationsRead() {
|
||||
return unwrapJavaResponse(
|
||||
post<JavaApiResponse<number>>(buildJavaUrl(API_ENDPOINTS.notification.readAll)),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* 单设备登录(互踢)下线处理。
|
||||
*
|
||||
* 账号在新设备登录后,旧设备的下一次受保护请求会拿到 code=4011;
|
||||
* 这里统一做四件事:清本地登录态 → 关闭自动登录 → 通知桌面端清 current_uid → 跳登录页。
|
||||
*
|
||||
* 关闭自动登录是关键:否则本机每次启动都会静默重登,把对方又顶下线(两台机器来回互踢)。
|
||||
* 记住的账号密码保留,手动点一次即可重新登录(此时顶掉对方,最后登录者胜)。
|
||||
*/
|
||||
|
||||
const AUTH_TOKEN_KEY = 'aiimage_auth_token'
|
||||
const UID_KEY = 'uid'
|
||||
const USERNAME_KEY = 'username'
|
||||
const AUTO_LOGIN_KEY = 'aiimage_auto_login'
|
||||
|
||||
/** 登录页据此标记显示"已被顶下线"警示(路由守卫会吞掉 query,故用 localStorage 兜底)。 */
|
||||
export const KICK_NOTICE_KEY = 'aiimage_kick_notice'
|
||||
|
||||
/** 服务端「已在其他设备登录」业务码,与后端 DeviceSessionPolicy.CODE_KICKED 对齐。 */
|
||||
export const KICKED_CODE = 4011
|
||||
|
||||
/** 本次页面生命周期内是否已发起跳转(并发 4011 只跳一次;整页跳转后 window 重建自然重置)。 */
|
||||
type KickWindow = Window & { __aiimageKickRedirected?: boolean }
|
||||
|
||||
/** 响应体(Java 错误信封 HTTP 200 + body.code)是否为互踢下线。 */
|
||||
export function isKickedPayload(payload: unknown): boolean {
|
||||
if (!payload || typeof payload !== 'object') {
|
||||
return false
|
||||
}
|
||||
return (payload as { code?: unknown }).code === KICKED_CODE
|
||||
}
|
||||
|
||||
/** 清桌面端 Python 侧的登录用户标记(未登录/换号后任务回退全局代理池)。 */
|
||||
function clearDesktopCurrentUid(): void {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
const apply = () => {
|
||||
try {
|
||||
const bridge = (
|
||||
window as unknown as {
|
||||
pywebview?: { api?: { save_config?: (data: Record<string, unknown>) => Promise<unknown> } }
|
||||
}
|
||||
).pywebview
|
||||
if (bridge?.api && typeof bridge.api.save_config === 'function') {
|
||||
void bridge.api.save_config({ current_uid: '' })
|
||||
}
|
||||
} catch {
|
||||
/* 网页形态无 pywebview 桥,忽略 */
|
||||
}
|
||||
}
|
||||
apply()
|
||||
// 被顶下线常发生在页面刚加载时,此刻 pywebview 桥可能尚未就绪(调用会被丢弃):
|
||||
// 等桥就绪事件后再补一次。重复写同值幂等;网页形态该事件不会触发。
|
||||
try {
|
||||
window.addEventListener('pywebviewready', apply, { once: true })
|
||||
} catch {
|
||||
/* 忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
/** 被顶下线:清登录态并回登录页;并发/重复触发安全(清理可重复,跳转只发一次)。 */
|
||||
export function handleKicked(): void {
|
||||
if (typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
try {
|
||||
const storage = window.localStorage
|
||||
storage.removeItem(AUTH_TOKEN_KEY)
|
||||
storage.removeItem(UID_KEY)
|
||||
storage.removeItem(USERNAME_KEY)
|
||||
storage.setItem(AUTO_LOGIN_KEY, '0')
|
||||
storage.setItem(KICK_NOTICE_KEY, '1')
|
||||
} catch {
|
||||
/* 忽略存储异常 */
|
||||
}
|
||||
clearDesktopCurrentUid()
|
||||
// 先清 uid 再整页跳转:否则路由守卫会把"已登录"的用户带回首页
|
||||
try {
|
||||
const kickWindow = window as KickWindow
|
||||
if (!kickWindow.__aiimageKickRedirected && !window.location.pathname.startsWith('/login')) {
|
||||
kickWindow.__aiimageKickRedirected = true
|
||||
console.log('[auth] 账号已在其他设备登录,本设备下线,跳转登录页')
|
||||
window.location.assign('/login?kicked=1')
|
||||
}
|
||||
} catch {
|
||||
/* 忽略跳转异常 */
|
||||
}
|
||||
}
|
||||
@@ -46,7 +46,7 @@
|
||||
<div class="secret-card-head">
|
||||
<div>
|
||||
<div class="secret-card-title">代理设置</div>
|
||||
<div class="secret-card-desc">供客户端任务连接代理服务。</div>
|
||||
<div class="secret-card-desc">供客户端任务连接代理服务,支持静态代理地址或代理服务商的提取链接。</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -57,7 +57,7 @@
|
||||
v-model="proxyUrl"
|
||||
class="secret-input"
|
||||
type="text"
|
||||
placeholder="请输入代理地址"
|
||||
placeholder="如 http://user:pass@host:port 或代理提取链接"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
:disabled="!proxyReady || busy"
|
||||
@@ -454,8 +454,9 @@ async function loadBalance() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存:逐模块保存非空输入(空输入保留服务端原值),代理仅在改动时保存;
|
||||
* 保存后对有输入值的模块自动检测一次,让用户立即知道密钥是否可用。
|
||||
* 保存:逐模块保存非空输入(空输入保留服务端原值),代理仅在改动时保存。
|
||||
* 保存后不再自动检测(2026-09-13 起检测一律由用户手动点击触发),
|
||||
* 保存会把检测状态重置为未检测,需用户点「检测」确认可用性。
|
||||
*/
|
||||
async function saveAll(options: { requireAll?: boolean } = {}): Promise<boolean> {
|
||||
if (busy.value || proxyLoading.value) return false
|
||||
@@ -491,15 +492,7 @@ async function saveAll(options: { requireAll?: boolean } = {}): Promise<boolean>
|
||||
await syncProxyToServer(nextProxyUrl)
|
||||
}
|
||||
|
||||
// 保存成功的模块立即自动检测,结果直接反映在卡片状态行
|
||||
for (const module of pendingModules) {
|
||||
const moduleKey = module.moduleKey as ApiSecretModuleKey
|
||||
try {
|
||||
ensureModuleState(module.moduleKey).result = await checkApiSecret(moduleKey)
|
||||
} catch (error) {
|
||||
console.warn('[api-secret] 保存后自动检测失败:', error)
|
||||
}
|
||||
}
|
||||
// 保存后不再自动检测:检测一律由用户手动点击「检测」触发
|
||||
refreshSnapshots()
|
||||
return true
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,533 @@
|
||||
<template>
|
||||
<div ref="rootRef" class="notification-bell" :class="`notification-bell--${theme}`">
|
||||
<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>
|
||||
|
||||
<div v-if="panelOpen" class="bell-panel" 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 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">暂无通知</div>
|
||||
<ul v-else class="bell-list">
|
||||
<li
|
||||
v-for="item in 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>
|
||||
</ul>
|
||||
|
||||
<div class="bell-panel-foot">
|
||||
<button v-if="hasMore" type="button" class="bell-more" :disabled="loading" @click="loadMore">
|
||||
{{ loading ? '加载中...' : '加载更多' }}
|
||||
</button>
|
||||
<span v-else-if="items.length" class="bell-foot-note">已显示全部</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
|
||||
import {
|
||||
fetchNotificationList,
|
||||
fetchNotificationSummary,
|
||||
markAllNotificationsRead,
|
||||
markNotificationRead,
|
||||
type NotificationItem,
|
||||
} from '@/shared/api/types/modules/notification.ts'
|
||||
import {
|
||||
NOTIFICATION_POLL_INTERVAL_MS,
|
||||
currentNotificationUid,
|
||||
formatNotificationTime,
|
||||
formatUnreadBadge,
|
||||
hasNewNotification,
|
||||
readLastNotifiedId,
|
||||
writeLastNotifiedId,
|
||||
} from '@/shared/utils/notification-bell.ts'
|
||||
|
||||
const PAGE_SIZE = 20
|
||||
|
||||
/** 顶栏主题:工具页/配置页深色(dark),桌面入口首页浅色(light)。 */
|
||||
const props = withDefaults(defineProps<{ theme?: 'dark' | 'light' }>(), {
|
||||
theme: 'dark',
|
||||
})
|
||||
const theme = computed(() => props.theme)
|
||||
|
||||
const rootRef = ref<HTMLElement | null>(null)
|
||||
const uid = currentNotificationUid()
|
||||
|
||||
const unreadCount = ref(0)
|
||||
const items = ref<NotificationItem[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const panelOpen = ref(false)
|
||||
const loading = ref(false)
|
||||
const markingAll = ref(false)
|
||||
const loadError = ref('')
|
||||
|
||||
const badgeText = computed(() => formatUnreadBadge(unreadCount.value))
|
||||
const hasMore = computed(() => items.value.length < total.value)
|
||||
|
||||
let pollTimer: number | null = null
|
||||
|
||||
/** 拉未读数:发现新通知提醒一次(localStorage 记录已提醒过的最大 id,避免重复弹)。 */
|
||||
async function refreshSummary() {
|
||||
try {
|
||||
const summary = await fetchNotificationSummary()
|
||||
unreadCount.value = Number(summary?.unreadCount ?? 0)
|
||||
const latestId = Number(summary?.latestId ?? 0)
|
||||
if (hasNewNotification(latestId, readLastNotifiedId(uid))) {
|
||||
ElMessage.warning('收到新的告警通知,请点击右上角铃铛查看')
|
||||
writeLastNotifiedId(uid, latestId)
|
||||
console.log('[notification] 检测到新通知 latestId=', latestId)
|
||||
}
|
||||
} catch (error) {
|
||||
// 通知接口失败静默降级:不显示红点、不打扰用户
|
||||
console.warn('[notification] 未读数刷新失败(静默降级):', error)
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPage(targetPage: number) {
|
||||
if (loading.value) return
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await fetchNotificationList({ page: targetPage, pageSize: PAGE_SIZE })
|
||||
const list = Array.isArray(result?.items) ? result.items : []
|
||||
items.value = targetPage <= 1 ? list : [...items.value, ...list]
|
||||
total.value = Number(result?.total ?? items.value.length)
|
||||
unreadCount.value = Number(result?.unreadCount ?? unreadCount.value)
|
||||
page.value = targetPage
|
||||
loadError.value = ''
|
||||
if (targetPage <= 1) {
|
||||
const latest = items.value.length ? Number(items.value[0].id) : 0
|
||||
if (latest > 0) {
|
||||
writeLastNotifiedId(uid, Math.max(readLastNotifiedId(uid), latest))
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// 列表加载失败在面板内提示,不弹全局消息打扰用户
|
||||
console.warn('[notification] 通知列表加载失败:', error)
|
||||
loadError.value = error instanceof Error ? error.message : '通知加载失败'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function loadMore() {
|
||||
if (!hasMore.value) return
|
||||
void loadPage(page.value + 1)
|
||||
}
|
||||
|
||||
function togglePanel() {
|
||||
panelOpen.value = !panelOpen.value
|
||||
if (panelOpen.value) {
|
||||
void loadPage(1)
|
||||
}
|
||||
}
|
||||
|
||||
async function onItemClick(item: NotificationItem) {
|
||||
if (item.read) return
|
||||
try {
|
||||
await markNotificationRead(item.id)
|
||||
item.read = true
|
||||
unreadCount.value = Math.max(0, unreadCount.value - 1)
|
||||
} catch (error) {
|
||||
console.warn('[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('[notification] 全部已读失败:', error)
|
||||
ElMessage.error(error instanceof Error ? error.message : '操作失败')
|
||||
} finally {
|
||||
markingAll.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function formatTime(value: string | null) {
|
||||
return formatNotificationTime(value)
|
||||
}
|
||||
|
||||
/** 点击组件外部关闭面板。 */
|
||||
function onDocumentMouseDown(event: MouseEvent) {
|
||||
if (!panelOpen.value) return
|
||||
const root = rootRef.value
|
||||
if (root && event.target instanceof Node && !root.contains(event.target)) {
|
||||
panelOpen.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 页面回到前台时立即刷新一次未读数。 */
|
||||
function onVisibilityChange() {
|
||||
if (typeof document !== 'undefined' && document.visibilityState === 'visible') {
|
||||
void refreshSummary()
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener('mousedown', onDocumentMouseDown)
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
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)
|
||||
if (pollTimer != null) {
|
||||
window.clearInterval(pollTimer)
|
||||
pollTimer = null
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.notification-bell {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.bell-trigger {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: 8px;
|
||||
background: transparent;
|
||||
color: #c8d2e2;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s ease, color 0.15s ease;
|
||||
}
|
||||
|
||||
.bell-trigger:hover,
|
||||
.bell-trigger--active {
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: #f5f8fc;
|
||||
}
|
||||
|
||||
.bell-icon {
|
||||
width: 19px;
|
||||
height: 19px;
|
||||
}
|
||||
|
||||
.bell-badge {
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
right: 1px;
|
||||
min-width: 16px;
|
||||
height: 16px;
|
||||
padding: 0 4px;
|
||||
box-sizing: border-box;
|
||||
border-radius: 999px;
|
||||
background: #e5484d;
|
||||
color: #fff;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
line-height: 16px;
|
||||
text-align: center;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.bell-panel {
|
||||
position: absolute;
|
||||
top: calc(100% + 10px);
|
||||
right: 0;
|
||||
z-index: 3200;
|
||||
width: 360px;
|
||||
max-width: calc(100vw - 32px);
|
||||
max-height: 440px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border: 1px solid #2c3540;
|
||||
border-radius: 12px;
|
||||
background: #171b20;
|
||||
box-shadow: 0 18px 48px rgba(0, 0, 0, 0.55);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.bell-panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 12px 14px;
|
||||
border-bottom: 1px solid #262d35;
|
||||
}
|
||||
|
||||
.bell-panel-title {
|
||||
color: #eef4fb;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.bell-read-all {
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: #8dc4ff;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.bell-read-all:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.bell-empty {
|
||||
padding: 32px 0;
|
||||
color: #7f8a96;
|
||||
font-size: 13px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.bell-empty--error {
|
||||
color: #ff9b9b;
|
||||
}
|
||||
|
||||
.bell-list {
|
||||
flex: 1;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.bell-item {
|
||||
padding: 11px 14px;
|
||||
border-bottom: 1px solid #222830;
|
||||
cursor: pointer;
|
||||
transition: background 0.12s ease;
|
||||
}
|
||||
|
||||
.bell-item:hover {
|
||||
background: #1d242c;
|
||||
}
|
||||
|
||||
.bell-item--unread {
|
||||
background: #1b232e;
|
||||
}
|
||||
|
||||
.bell-item--unread .bell-item-title::before {
|
||||
content: '';
|
||||
display: inline-block;
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
margin-right: 7px;
|
||||
border-radius: 50%;
|
||||
background: #e5484d;
|
||||
vertical-align: 1px;
|
||||
}
|
||||
|
||||
.bell-item--error .bell-item-title {
|
||||
color: #ffb4b4;
|
||||
}
|
||||
|
||||
.bell-item--warning .bell-item-title {
|
||||
color: #f0c674;
|
||||
}
|
||||
|
||||
.bell-item--info .bell-item-title {
|
||||
color: #8dc4ff;
|
||||
}
|
||||
|
||||
.bell-item-head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.bell-item-title {
|
||||
color: #dce6f0;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.bell-item-time {
|
||||
flex-shrink: 0;
|
||||
color: #6f7a86;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.bell-item-content {
|
||||
margin-top: 4px;
|
||||
color: #9aa6b3;
|
||||
font-size: 12px;
|
||||
line-height: 1.55;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.bell-panel-foot {
|
||||
border-top: 1px solid #262d35;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.bell-more {
|
||||
width: 100%;
|
||||
padding: 9px 0;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: #8dc4ff;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.bell-more:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.bell-foot-note {
|
||||
display: block;
|
||||
padding: 8px 0;
|
||||
color: #6f7a86;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
/* ---- 浅色主题(桌面入口首页顶栏) ---- */
|
||||
.notification-bell--light .bell-trigger {
|
||||
color: #555;
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-trigger:hover,
|
||||
.notification-bell--light .bell-trigger--active {
|
||||
background: rgba(0, 0, 0, 0.06);
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-panel {
|
||||
border-color: #e2e8f0;
|
||||
background: #ffffff;
|
||||
box-shadow: 0 18px 48px rgba(31, 45, 61, 0.18);
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-panel-head {
|
||||
border-bottom-color: #edf1f5;
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-panel-title {
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-read-all {
|
||||
color: #4c5bd4;
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-empty {
|
||||
color: #999;
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-item {
|
||||
border-bottom-color: #f0f3f7;
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-item:hover {
|
||||
background: #f7f9fc;
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-item--unread {
|
||||
background: #f2f6ff;
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-item-title {
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-item--error .bell-item-title {
|
||||
color: #c0392b;
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-item--warning .bell-item-title {
|
||||
color: #a8793e;
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-item--info .bell-item-title {
|
||||
color: #4c5bd4;
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-item-time {
|
||||
color: #9aa6b3;
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-item-content {
|
||||
color: #667085;
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-panel-foot {
|
||||
border-top-color: #edf1f5;
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-more {
|
||||
color: #4c5bd4;
|
||||
}
|
||||
|
||||
.notification-bell--light .bell-foot-note {
|
||||
color: #9aa6b3;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* 铃铛通知纯逻辑:未读徽标文案、新通知判定、「已提醒过」去重记录、时间展示。
|
||||
* 轮询调度与渲染在 NotificationBell.vue;这里只放可单测的纯函数与存储读写。
|
||||
*/
|
||||
|
||||
/** 未读轮询间隔(60 秒)。 */
|
||||
export const NOTIFICATION_POLL_INTERVAL_MS = 60_000
|
||||
|
||||
const NOTIFIED_KEY_PREFIX = 'notification:last-notified-id'
|
||||
|
||||
/** 未读徽标文案:0 或非法值显示空串,>99 显示 99+。 */
|
||||
export function formatUnreadBadge(count: number | null | undefined): string {
|
||||
const value = Number(count ?? 0)
|
||||
if (!Number.isFinite(value) || value <= 0) {
|
||||
return ''
|
||||
}
|
||||
return value > 99 ? '99+' : String(Math.floor(value))
|
||||
}
|
||||
|
||||
/** 是否出现新通知:latestId 大于上次已提醒过的 id。 */
|
||||
export function hasNewNotification(
|
||||
latestId: number | null | undefined,
|
||||
lastNotifiedId: number | null | undefined,
|
||||
): boolean {
|
||||
const latest = Number(latestId ?? 0)
|
||||
const notified = Number(lastNotifiedId ?? 0)
|
||||
if (!Number.isFinite(latest) || latest <= 0) {
|
||||
return false
|
||||
}
|
||||
return latest > (Number.isFinite(notified) && notified > 0 ? notified : 0)
|
||||
}
|
||||
|
||||
function storageKey(uid: string): string {
|
||||
return `${NOTIFIED_KEY_PREFIX}:${uid || '0'}`
|
||||
}
|
||||
|
||||
/** 读取当前用户「已提醒过的最大通知 id」(多页面/多会话共享)。 */
|
||||
export function readLastNotifiedId(uid: string): number {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(storageKey(uid))
|
||||
const value = Number(raw ?? 0)
|
||||
return Number.isFinite(value) && value > 0 ? value : 0
|
||||
} catch {
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
export function writeLastNotifiedId(uid: string, id: number): void {
|
||||
try {
|
||||
if (Number.isFinite(id) && id > 0) {
|
||||
window.localStorage.setItem(storageKey(uid), String(Math.floor(id)))
|
||||
}
|
||||
} catch {
|
||||
/* 存储不可用时静默忽略(退化为每次都提醒,不影响功能) */
|
||||
}
|
||||
}
|
||||
|
||||
/** 当前登录用户 uid(未登录返回 '0')。 */
|
||||
export function currentNotificationUid(): string {
|
||||
try {
|
||||
return window.localStorage.getItem('uid') || '0'
|
||||
} catch {
|
||||
return '0'
|
||||
}
|
||||
}
|
||||
|
||||
/** 通知时间展示:今天只显示 HH:mm;昨天显示「昨天 HH:mm」;更早显示 MM-DD HH:mm。 */
|
||||
export function formatNotificationTime(
|
||||
value: string | null | undefined,
|
||||
now: Date = new Date(),
|
||||
): string {
|
||||
if (!value) {
|
||||
return ''
|
||||
}
|
||||
const date = new Date(value)
|
||||
if (Number.isNaN(date.getTime())) {
|
||||
return ''
|
||||
}
|
||||
const pad = (input: number) => String(input).padStart(2, '0')
|
||||
const hourMinute = `${pad(date.getHours())}:${pad(date.getMinutes())}`
|
||||
const sameDay =
|
||||
date.getFullYear() === now.getFullYear() &&
|
||||
date.getMonth() === now.getMonth() &&
|
||||
date.getDate() === now.getDate()
|
||||
if (sameDay) {
|
||||
return hourMinute
|
||||
}
|
||||
const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1)
|
||||
const isYesterday =
|
||||
date.getFullYear() === yesterday.getFullYear() &&
|
||||
date.getMonth() === yesterday.getMonth() &&
|
||||
date.getDate() === yesterday.getDate()
|
||||
if (isYesterday) {
|
||||
return `昨天 ${hourMinute}`
|
||||
}
|
||||
return `${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${hourMinute}`
|
||||
}
|
||||
Reference in New Issue
Block a user