1. 更新框架
2. 修复框架更新后导致的问题
3. 消息系统升级
This commit is contained in:
李琦
2026-08-10 20:08:50 +08:00
parent f0a33a628b
commit b82754e36b
33 changed files with 5202 additions and 886 deletions

View File

@@ -1,15 +1,15 @@
<script lang="ts" setup>
/**
* 管理端基础布局:铃铛站内信轮询 + 动作宿主挂载
*/
import type { NotificationItem } from '@vben/layouts';
import {computed, onUnmounted, ref, watch} from 'vue';
import { computed, onUnmounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { AuthenticationLoginExpiredModal } from '@vben/common-ui';
// import { VBEN_DOC_URL, VBEN_GITHUB_URL } from '@vben/constants';
import { AuthenticationLoginExpiredModal, VbenIcon } from '@vben/common-ui';
import { useWatermark } from '@vben/hooks';
// import { BookOpenText, CircleHelp, MdiGithub } from '@vben/icons';
// import { CircleHelp } from '@vben/icons';
// import { BookOpenText, CircleHelp, SvgGithubIcon } from '@vben/icons';
import { $t } from '@vben/locales';
import {
BasicLayout,
LockScreen,
@@ -18,173 +18,165 @@ import {
} from '@vben/layouts';
import { preferences, usePreferences } from '@vben/preferences';
import { useAccessStore, useUserStore } from '@vben/stores';
// import { openWindow } from '@vben/utils';
import {
Bell,
CalendarClock,
Megaphone,
Users,
} from 'lucide-vue-next';
import { notification } from 'ant-design-vue';
import { Bell, Users } from 'lucide-vue-next';
// import { $t } from '#/locales';
import DoctorTransferFloat from '#/components/doctor-transfer-float/DoctorTransferFloat.vue';
import HeaderVipBadge from '#/components/vip/HeaderVipBadge.vue';
import { useAuthStore } from '#/store';
import LoginForm from '#/views/_core/authentication/login.vue';
import SwitchAccountModal from '#/layouts/components/SwitchAccountModal.vue';
import { useRouter } from 'vue-router';
import {getNoticeListApi, readAllApi} from "#/views/notice/api";
import {formatTimeToRelative} from "#/util/tool";
import {notification} from "ant-design-vue";
import { $t } from "@vben/locales";
import { useAuthStore } from '#/store';
import { formatTimeToRelative } from '#/util/tool';
import LoginForm from '#/views/_core/authentication/login.vue';
import NoticeActionHost from '#/views/notice/action/NoticeActionHost.vue';
import {
emitNoticeRefresh,
onNoticeRefresh,
openNoticeAction,
} from '#/views/notice/action/bus';
import { resolveNoticeColor } from '#/views/notice/action/types';
import {
getNoticeListApi,
getNoticeUnreadCountApi,
readAllApi,
readApi,
} from '#/views/notice/api';
const router = useRouter();
const switchAccountModalRef = ref<InstanceType<typeof SwitchAccountModal>>();
// 样式相关
const typeIcons = {
0: Megaphone,
1: Bell,
2: CalendarClock,
};
const typeColors = {
0: 'text-sky-500',
1: 'text-amber-500',
2: 'text-emerald-500',
};
const typeBgColors = {
0: 'bg-sky-50',
1: 'bg-amber-50',
2: 'bg-emerald-50',
};
const typeBorderColors = {
0: 'border-sky-200',
1: 'border-amber-200',
2: 'border-emerald-200',
};
const notifications = ref<NotificationItem[]>([]);
const unreadCount = ref(0);
// 获取消息列表数据
/** 拉取未读列表 + 角标数字 */
const getNoticeList = async () => {
try {
const res = await getNoticeListApi({
status: 0,
});
let message = '未读消息';
if (res.items.length > 0) {
if (res.items.length > notifications.value.length) {
if (notifications.value.length === 0) {
message = '新消息';
}
notification.info({
message: `您有${message}`,
description: `您有 ${res.items.length}${message}请注意查收`,
duration: 5,
});
}
notifications.value = res.items.map(item => ({
id: item.id,
icon: typeIcons[item.type],
// 将API返回的数据映射到组件需要的格式
message: item.title,
title: getMessageTypeName(item.type),
date: formatTimeToRelative(item.created_at),
color: typeColors[item.type],
isRead: item.status
}));
} else {
notifications.value = [];
const [res, countRes] = await Promise.all([
getNoticeListApi({ status: 0, page: 1, pageSize: 20 }),
getNoticeUnreadCountApi().catch(() => null),
]);
const items = res?.items || [];
const prevLen = notifications.value.length;
if (items.length > prevLen && prevLen > 0) {
notification.info({
message: '您有新消息',
description: `您有 ${items.length} 条未读消息请注意查收`,
duration: 5,
});
}
notifications.value = items.map((item: any) => {
const color = resolveNoticeColor(item.type_color);
return {
id: item.id,
// Notification 默认用组件当 icon我们走自定义 content 槽,这里占位即可
icon: Bell as any,
message: item.detail || item.type_name || '',
title: item.title || '通知',
date: formatTimeToRelative(item.created_at),
color: color.text,
colorBg: color.bg,
isRead: Number(item.status) === 1,
status: item.status,
type_code: item.type_code,
type_name: item.type_name,
type_icon: item.type_icon,
type_color: item.type_color,
action_type: item.action_type,
action_payload: item.action_payload,
detail: item.detail,
content: item.content,
edit_type: item.edit_type,
priority: item.priority,
raw: item,
};
});
unreadCount.value = Number(
countRes?.count ?? res?.unread_total ?? items.length,
);
} catch (error) {
console.error('获取消息列表失败:', error);
}
};
getNoticeList();
// 每隔二十秒刷新一次
let intervalId = setInterval(getNoticeList, 20_000);
// 封装定时器重启逻辑
const restartInterval = () => {
clearInterval(intervalId);
getNoticeList(); // 立即获取最新数据
getNoticeList();
intervalId = setInterval(getNoticeList, 20_000);
};
// 处理跨标签页修改
const handleStorageChange = (event) => {
const handleStorageChange = (event: StorageEvent) => {
if (event.key === 'readStatus') {
restartInterval();
}
};
// 处理当前标签页修改(核心新增部分)
const handleLocalChange = () => {
restartInterval();
};
// 添加双重监听
window.addEventListener('storage', handleStorageChange); // 跨标签页监听
const originalSetItem = localStorage.setItem.bind(localStorage);
// 拦截当前页的 localStorage.setItem 操作
localStorage.setItem = (key, value) => {
originalSetItem(key, value);
if (key === 'readStatus') {
handleLocalChange(); // 手动触发当前页回调
restartInterval();
}
};
// 组件卸载时清理
window.addEventListener('storage', handleStorageChange);
const stopRefreshListen = onNoticeRefresh(() => restartInterval());
onUnmounted(() => {
clearInterval(intervalId);
window.removeEventListener('storage', handleStorageChange);
localStorage.setItem = originalSetItem; // 恢复原始方法
localStorage.setItem = originalSetItem;
stopRefreshListen();
});
// 消息类型定义
const messageTypes = [
{ id: -1, name: '全部消息' },
{ id: 0, name: '系统公告', icon: Megaphone },
{ id: 1, name: '系统通知', icon: Bell },
{ id: 2, name: '周报提醒', icon: CalendarClock },
];
// 根据类型ID获取类型名称
const getMessageTypeName = (typeId) => {
const type = messageTypes.find(t => t.id === typeId);
return type ? type.name : '未知类型';
};
const goNoticeList = () => {
// TODO 跳转通知列表
router.push('/notice/list');
};
// 处理消息点击
const handleItemClick = (item) => {
notifications.value.forEach((value) => {
if (value.id === item.id) {
value.status = 1;
value.isRead = 1;
}
/** 从铃铛列表移除并扣减角标 */
function removeFromBell(item: NotificationItem) {
notifications.value = notifications.value.filter((n) => n.id !== item.id);
unreadCount.value = Math.max(0, unreadCount.value - 1);
}
/** 行点击:立刻取消未读并打开场景 */
const handleItemClick = async (item: NotificationItem) => {
const raw = (item as any).raw || item;
const wasUnread = !item.isRead;
item.isRead = true;
if (wasUnread) {
removeFromBell(item);
}
await openNoticeAction({
...raw,
id: item.id,
status: wasUnread ? 0 : 1,
});
router.push(`/notice/detail/${item.id}`);
};
const handleClick = async (item: NotificationItem) => {
await handleItemClick(item);
};
/** 勾选已读:只标已读,不打开详情 */
async function handleMarkRead(item: NotificationItem) {
if (item.isRead) return;
item.isRead = true;
removeFromBell(item);
try {
await readApi(Number(item.id));
emitNoticeRefresh();
} catch {
/* ignore */
}
}
const userStore = useUserStore();
const authStore = useAuthStore();
const accessStore = useAccessStore();
const { destroyWatermark, updateWatermark } = useWatermark();
const { isDark } = usePreferences();
const showDot = computed(() =>
notifications.value.some((item) => !item.isRead),
);
const showDot = computed(() => unreadCount.value > 0);
/** 与原先悬浮窗一致:有 doctor_id 且绑定门店才显示传方入口 */
const showDoctorTransfer = computed(() => {
const info = userStore.userInfo as Record<string, any> | null | undefined;
if (!info) return false;
@@ -220,7 +212,20 @@ async function handleLogout() {
function handleNoticeClear() {
readAllApi().then(() => {
notifications.value = [];
// 成功后可以重新获取数据或者直接更新本地状态
unreadCount.value = 0;
notification.success({
message: '标记成功',
duration: 2,
});
emitNoticeRefresh();
});
}
/** 全部已读:必须走后端 API */
function handleMakeAll() {
readAllApi().then(() => {
notifications.value = [];
unreadCount.value = 0;
notification.success({
message: '标记成功',
duration: 2,
@@ -228,72 +233,21 @@ function handleNoticeClear() {
});
}
function markRead(id: number | string) {
const item = notifications.value.find((item) => item.id === id);
if (item) {
item.isRead = true;
}
}
function remove(id: number | string) {
notifications.value = notifications.value.filter((item) => item.id !== id);
}
function handleMakeAll() {
notifications.value.forEach((item) => (item.isRead = true));
}
const viewAll = () => {};
const handleClick = (item: NotificationItem) => {
// 如果通知项有链接,点击时跳转
if (item.link) {
navigateTo(item.link, item.query, item.state);
}
};
function navigateTo(
link: string,
query?: Record<string, any>,
state?: Record<string, any>,
) {
if (link.startsWith('http://') || link.startsWith('https://')) {
// 外部链接,在新标签页打开
window.open(link, '_blank');
} else {
// 内部路由链接,支持 query 参数和 state
router.push({
path: link,
query: query || {},
state,
});
}
}
watch(
() => ({
enable: preferences.app.watermark,
content: preferences.app.watermarkContent,
isDark: isDark.value,
}),
async ({ enable, content, isDark: isDarkValue }) => {
async ({ enable }) => {
if (enable) {
const watermarkColor = isDarkValue
? 'rgba(255, 255, 255, 0.12)'
: 'rgba(0, 0, 0, 0.12)';
await updateWatermark({
// 这里更改水印内容
// content: `${userStore.userInfo?.nick_name || import.meta.env.VITE_APP_TITLE}`,
content: `${userStore.userInfo?.nick_name}\r\n${userStore.userInfo?.phone || import.meta.env.VITE_APP_TITLE}`,
});
} else {
destroyWatermark();
}
},
{
immediate: true,
},
{ immediate: true },
);
</script>
@@ -321,13 +275,54 @@ watch(
<template #notification>
<Notification
:dot="showDot"
:count="unreadCount"
:notifications="notifications"
@clear="handleNoticeClear"
@make-all="handleMakeAll"
@read="handleItemClick"
@read="handleMarkRead"
@view-all="goNoticeList"
@on-click="handleClick"
/>
>
<template #content="{ item }">
<span
v-if="!item.isRead"
class="absolute top-2 right-2 size-2 rounded-sm bg-primary"
></span>
<span
class="relative flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-xl"
:class="[(item as any).colorBg || 'bg-muted', (item as any).color]"
>
<VbenIcon
v-if="(item as any).type_icon"
:icon="(item as any).type_icon"
class="size-5"
/>
<Bell v-else class="size-5" />
</span>
<div class="min-w-0 flex-1 pr-8 leading-none">
<div class="mb-1 flex items-center gap-2">
<span
v-if="(item as any).type_name"
class="truncate text-[11px] font-semibold"
:class="(item as any).color"
>
{{ (item as any).type_name }}
</span>
</div>
<p class="truncate text-sm font-semibold text-foreground">
{{ item.title }}
</p>
<p
v-if="item.message"
class="mt-1 line-clamp-2 text-xs text-muted-foreground"
>
{{ item.message }}
</p>
<p class="mt-1 text-xs text-muted-foreground">{{ item.date }}</p>
</div>
</template>
</Notification>
<NoticeActionHost />
</template>
<template #extra>
<AuthenticationLoginExpiredModal