KnowledgeBase_frontend/src/store/notificationCenter/notificationCenter.slice.js

124 lines
3.7 KiB
JavaScript

import { createSlice } from '@reduxjs/toolkit';
const initialState = {
notifications: [
{
id: 1,
type: 'permission',
icon: 'bi-shield',
title: '新的权限请求',
content: '张三请求访问销售数据集',
time: '10分钟前',
hasDetail: true,
isRead: false,
},
{
id: 2,
type: 'system',
icon: 'bi-info-circle',
title: '系统更新通知',
content: '系统将在今晚23:00进行例行维护',
time: '1小时前',
hasDetail: false,
isRead: false,
},
{
id: 3,
type: 'permission',
icon: 'bi-shield',
title: '新的权限请求',
content: '李四请求访问用户数据集',
time: '2小时前',
hasDetail: true,
isRead: false,
},
{
id: 4,
type: 'system',
icon: 'bi-exclamation-circle',
title: '安全提醒',
content: '检测到异常登录行为,请及时查看',
time: '3小时前',
hasDetail: true,
isRead: false,
},
{
id: 5,
type: 'permission',
icon: 'bi-shield',
title: '权限变更通知',
content: '管理员修改了您的数据访问权限',
time: '1天前',
hasDetail: true,
isRead: false,
},
],
unreadCount: 5,
isConnected: false,
};
const notificationCenterSlice = createSlice({
name: 'notificationCenter',
initialState,
reducers: {
clearNotifications: (state) => {
state.notifications = [];
state.unreadCount = 0;
},
addNotification: (state, action) => {
// 检查通知是否已存在
const exists = state.notifications.some((n) => n.id === action.payload.id);
if (!exists) {
// 将新通知添加到列表的开头
state.notifications.unshift(action.payload);
// 如果通知未读,增加未读计数
if (!action.payload.isRead) {
state.unreadCount += 1;
}
}
},
markNotificationAsRead: (state, action) => {
const notification = state.notifications.find((n) => n.id === action.payload);
if (notification && !notification.isRead) {
notification.isRead = true;
state.unreadCount = Math.max(0, state.unreadCount - 1);
}
},
markAllNotificationsAsRead: (state) => {
state.notifications.forEach((notification) => {
notification.isRead = true;
});
state.unreadCount = 0;
},
setWebSocketConnected: (state, action) => {
state.isConnected = action.payload;
},
removeNotification: (state, action) => {
const notificationIndex = state.notifications.findIndex((n) => n.id === action.payload);
if (notificationIndex !== -1) {
const notification = state.notifications[notificationIndex];
if (!notification.isRead) {
state.unreadCount = Math.max(0, state.unreadCount - 1);
}
state.notifications.splice(notificationIndex, 1);
}
},
},
});
export const {
clearNotifications,
addNotification,
markNotificationAsRead,
markAllNotificationsAsRead,
setWebSocketConnected,
removeNotification,
} = notificationCenterSlice.actions;
export default notificationCenterSlice.reducer;