优化通知栏,通知实时同步功能
This commit is contained in:
@@ -4,6 +4,14 @@ Frontend module: Vue 3 / Vite 5 / TypeScript SPA.
|
||||
|
||||
---
|
||||
|
||||
## Code Style
|
||||
|
||||
- **No emoji in UI strings.** Plain Chinese text for labels, buttons, status.
|
||||
- **No emoji in code comments or docstrings.** Plain text only.
|
||||
- **Keep CLAUDE.md current** — whenever code is modified, added, deleted, or any file change affects the module structure, build, conventions, or component patterns, update this file (and the root `CLAUDE.md` if cross-cutting) in the same commit to reflect the new state. Stale documentation is a bug.
|
||||
|
||||
---
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
@@ -55,7 +63,9 @@ Pre-commit: `lint-staged` runs `eslint --fix` on `*.ts`/`*.vue` via `yorkie` git
|
||||
- `src/store/importTasks.ts`: separate store for import task tracking (computed getters: `activeTasks`, `hasActiveTasks`, `recentTasks`).
|
||||
- `src/utils/router.ts`: converts backend menu records → Vue router records, supports iframe/external links with `openStyle` flags.
|
||||
|
||||
Layout is event-driven: `src/layout/` shell + `mitt` event bus (`src/utils/emits.ts`). The `EMitt` enum defines 13 events for sidebar, theme, tabs, layout changes. **Trace both the Pinia store and mitt events** when changing navigation/sidebar/tabs/theme.
|
||||
Layout is event-driven: `src/layout/` shell + `mitt` event bus (`src/utils/emits.ts`). The `EMitt` enum defines events for sidebar, theme, tabs, layout changes. **Trace both the Pinia store and mitt events** when changing navigation/sidebar/tabs/theme.
|
||||
|
||||
Header right side: notification bell (combined badge) → `expand` (user menu). The old `import-task-indicator.vue` has been removed in favor of the notification center drawer.
|
||||
|
||||
## Common page pattern: `useView` hook
|
||||
|
||||
@@ -104,8 +114,8 @@ All helper functions must accept `number | null` and return `"—"` or `""` for
|
||||
### 2. Heavy libraries must use dynamic imports
|
||||
`html2canvas`, `jspdf`, and `echarts` are NOT imported at module level. Load them via `await import()` only when triggered by user action. This saves ~600KB from the initial bundle.
|
||||
|
||||
### 3. Google Fonts go in index.html, not scoped styles
|
||||
Never use `@import url("https://fonts.googleapis.com/...")` inside Vue scoped styles. Use `<link rel="preconnect">` + `<link rel="stylesheet">` in `index.html`.
|
||||
### 3. Fonts are self-hosted — no external network dependency
|
||||
Fonts (Noto Sans SC, JetBrains Mono) are bundled via `@fontsource/*` packages, imported in `src/main.ts`. Do NOT add Google Fonts `<link>` tags or `@import` back — the system runs on intranet where external network may be unavailable. To add a new font weight, import the corresponding fontsource CSS file in `main.ts`.
|
||||
|
||||
### 4. Export must show user feedback
|
||||
Always show `ElLoading.service` fullscreen and `ElMessage` success/failure. Disable the export button during rendering.
|
||||
@@ -113,9 +123,62 @@ Always show `ElLoading.service` fullscreen and `ElMessage` success/failure. Disa
|
||||
### 5. Deep watchers on filter objects are banned
|
||||
Never use `watch(filters, callback, { deep: true })`. Derive a precise computed trigger key (e.g. `dataHash`, `filteredHash`, `extremesVersion`) and watch that instead.
|
||||
|
||||
## Import progress polling pattern
|
||||
## Notification center
|
||||
|
||||
The global notification system (`src/components/alert-marquee/index.vue`) aggregates two feed types:
|
||||
|
||||
| Feed | Source | Clickable? |
|
||||
|---|---|---|
|
||||
| System alerts | `useAlertMarquee.ts` composable (polls `/sys/alert/active/since` every 30s) | Yes — opens detail dialog |
|
||||
| Import tasks | `useImportTaskStore` Pinia store | No — shows real-time progress inline |
|
||||
|
||||
### Components & composables
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `src/composables/useAlertMarquee.ts` | Module-level singleton: message queue, drawer toggle, detail dialog state, scrollbar position. Real-time delivery: SSE (`/sys/alert/stream`) primary + 10s polling fallback. Exports danger-specific computed: `dangerMessages`, `latestDangerMessage`, `dangerCount`, `hasDangerMessages` |
|
||||
| `src/composables/useFloatingDrag.ts` | Pointer Events drag logic: `setPointerCapture`, viewport clamping, deferred `isDragging` (activates only on >3px move), `dragMoved` flag to distinguish drag vs click |
|
||||
| `src/components/alert-marquee/index.vue` | Floating scrollbar (640px wide, centered top, draggable) + `el-drawer` notification center + `el-dialog` detail popup |
|
||||
| `src/layout/header/base-header.vue` | Bell button with combined badge (alerts + active import tasks), toggles drawer |
|
||||
| `src/store/importTasks.ts` | Import task CRUD: `addTask`, `updateTask`, `removeTask`, `clearCompleted`; getters: `activeTasks`, `recentTasks` |
|
||||
|
||||
### Level-based routing
|
||||
|
||||
- **danger (紧急)**: triggers the floating scrollbar + appears in notification center drawer + bell badge
|
||||
- **warning / info (警告 / 提示)**: notification center drawer + bell badge only (no scrollbar)
|
||||
- The bell badge in base-header always shows total count (all levels + active import tasks)
|
||||
|
||||
### Floating scrollbar behavior
|
||||
|
||||
- Visible only when logged in (`appStore.state.appIsLogin`) and has danger-level alerts (`hasDangerMessages`)
|
||||
- Positioned centered at top (`y: 56` below header), draggable to reposition, re-centers on window resize
|
||||
- Shows latest alert headline + count badge
|
||||
- **Close button** hides the bar; **auto-reappears** when new danger alerts arrive (watch on `dangerCount`)
|
||||
- **查看详情** button opens `el-dialog` with full alert text
|
||||
- The old `import-task-indicator.vue` (bell icon with popover in header) has been **removed**
|
||||
|
||||
### Import progress integration
|
||||
|
||||
1. Upload via `baseService.upload()` (FormData, no explicit Content-Type).
|
||||
2. On success, poll `GET .../import/progress/{backendTaskId}` every 3 seconds.
|
||||
3. Update Pinia store (`useImportTaskStore`) with percentage/state.
|
||||
4. Emit `refreshDataList` on completion. Header indicator (`import-task-indicator.vue`) shows active tasks with spinning badge + popover.
|
||||
2. On upload start, toast: `"导入已开始,可在通知中心查看进度"`.
|
||||
3. Poll `GET .../import/progress/{backendTaskId}` every 3 seconds.
|
||||
4. Update Pinia store (`useImportTaskStore`) — progress bar + status tag render reactively in the drawer.
|
||||
5. On completion: green checkmark; on failure: red cross + error message. Completed/failed tasks show a dismiss button.
|
||||
|
||||
### Alert management page
|
||||
|
||||
Manual alert CRUD at route `sys/system-alert`:
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `src/views/sys/system-alert.vue` | List page: `useView`-based, search by level/title/sourceType, batch delete, per-row withdraw |
|
||||
| `src/views/sys/system-alert-add-or-update.vue` | Add/edit dialog: level (info/warning/danger), title, content (textarea), sourceType, expireTime (datetime picker) |
|
||||
|
||||
Backend endpoints under `/sys/alert`:
|
||||
- `GET /page` — paginated list (`sys:alert:page`)
|
||||
- `GET /{id}` — detail (`sys:alert:info`)
|
||||
- `POST /` — create (`sys:alert:save`)
|
||||
- `PUT /` — update (`sys:alert:update`)
|
||||
- `DELETE /` — batch delete (`sys:alert:delete`)
|
||||
- `PUT /{id}/withdraw` — soft-withdraw (`sys:alert:update`)
|
||||
- `GET /active`, `GET /active/since` — frontend polling (no permission required)
|
||||
|
||||
@@ -5,13 +5,6 @@
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>气象数据 - 管理系统</title>
|
||||
<!-- Preload fonts to avoid blocking render (moved from home.vue @import) -->
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com" />
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
|
||||
<link
|
||||
href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@300;400;500;600;700;900&family=JetBrains+Mono:wght@400;600&display=swap"
|
||||
rel="stylesheet"
|
||||
/>
|
||||
<script>
|
||||
//全局钩子
|
||||
window.SITE_CONFIG = {
|
||||
|
||||
Generated
+155
-141
File diff suppressed because it is too large
Load Diff
@@ -21,6 +21,8 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "2.3.1",
|
||||
"@fontsource/jetbrains-mono": "^5.2.8",
|
||||
"@fontsource/noto-sans-sc": "^5.2.9",
|
||||
"@vueuse/core": "9.1.1",
|
||||
"@wangeditor/editor": "5.1.1",
|
||||
"@wangeditor/editor-for-vue": "^5.1.12",
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from "@element-plus/icons-vue";
|
||||
import { useAlertMarquee, type AlertMessage } from "@/composables/useAlertMarquee";
|
||||
import { useImportTaskStore, type ImportTask } from "@/store/importTasks";
|
||||
import { useAppStore } from "@/store";
|
||||
import { useFloatingDrag } from "@/composables/useFloatingDrag";
|
||||
|
||||
const {
|
||||
@@ -19,6 +20,9 @@ const {
|
||||
latestMessage,
|
||||
messageCount,
|
||||
hasMessages,
|
||||
latestDangerMessage,
|
||||
dangerCount,
|
||||
hasDangerMessages,
|
||||
drawerVisible,
|
||||
detailTarget,
|
||||
detailVisible,
|
||||
@@ -48,19 +52,27 @@ function dismissScrollbar(): void {
|
||||
}
|
||||
|
||||
function onViewDetail(): void {
|
||||
if (latestMessage.value) {
|
||||
showDetail(latestMessage.value);
|
||||
if (latestDangerMessage.value) {
|
||||
showDetail(latestDangerMessage.value);
|
||||
}
|
||||
}
|
||||
|
||||
// 监听消息数量变化:有新通知时重新显示滚动条
|
||||
watch(messageCount, (now, prev) => {
|
||||
// 监听紧急通知数量变化:有新紧急通知时重新显示滚动条
|
||||
watch(dangerCount, (now, prev) => {
|
||||
if (now > prev) {
|
||||
scrollbarDismissed.value = false;
|
||||
}
|
||||
});
|
||||
|
||||
const showScrollbar = computed(() => hasMessages.value && !scrollbarDismissed.value);
|
||||
// 紧急通知全部清空/过期后,重置 scrollbar 状态,确保不会残留
|
||||
watch(hasDangerMessages, (val) => {
|
||||
if (!val) {
|
||||
scrollbarDismissed.value = true;
|
||||
}
|
||||
});
|
||||
|
||||
const appStore = useAppStore();
|
||||
const showScrollbar = computed(() => appStore.state.appIsLogin && hasDangerMessages.value && !scrollbarDismissed.value);
|
||||
|
||||
// ---- 拖拽时跳过按钮点击 ----
|
||||
|
||||
@@ -211,10 +223,10 @@ function handleClearAll(): void {
|
||||
<div class="alert-scrollbar__text-wrap">
|
||||
<span
|
||||
class="alert-scrollbar__text"
|
||||
:class="{ 'is-scroll': latestMessage && latestMessage.content.length > 60 }"
|
||||
>{{ latestMessage?.content ?? "" }}</span>
|
||||
:class="{ 'is-scroll': latestDangerMessage && latestDangerMessage.content.length > 60 }"
|
||||
>{{ latestDangerMessage?.content ?? "" }}</span>
|
||||
</div>
|
||||
<span class="alert-scrollbar__badge">{{ messageCount }}</span>
|
||||
<span class="alert-scrollbar__badge">{{ dangerCount }}</span>
|
||||
<button class="alert-scrollbar__btn-detail" @click.stop="onViewDetail">查看详情</button>
|
||||
<button class="alert-scrollbar__btn-close" @click.stop="dismissScrollbar">关闭</button>
|
||||
</div>
|
||||
@@ -414,7 +426,7 @@ function handleClearAll(): void {
|
||||
}
|
||||
|
||||
.alert-scrollbar__text.is-scroll {
|
||||
animation: scrollbar-marquee 12s linear infinite;
|
||||
animation: scrollbar-marquee 20s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes scrollbar-marquee {
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
// composables/useAlertMarquee.ts
|
||||
// 紧急通知状态管理 — 模块级单例
|
||||
// 管理:消息队列 / 通知中心抽屉 / 详情弹窗 / 悬浮滚动条位置
|
||||
// 后续接入后端时,只需修改 mockAlerts() 为真实 API 调用
|
||||
// 通知状态管理 — 模块级单例
|
||||
// 消息队列 / 通知中心抽屉 / 详情弹窗 / 悬浮滚动条位置
|
||||
// 获取:SSE 主通道 + 10s 轮询降级 + 每60s全量对账
|
||||
|
||||
import { ref, computed } from "vue";
|
||||
import baseService from "@/service/baseService";
|
||||
import app from "@/constants/app";
|
||||
import { getToken } from "@/utils/cache";
|
||||
|
||||
export type AlertLevel = "info" | "warning" | "danger";
|
||||
|
||||
export interface AlertMessage {
|
||||
id: string;
|
||||
level: AlertLevel;
|
||||
title: string;
|
||||
content: string;
|
||||
publishTime: string;
|
||||
}
|
||||
@@ -66,6 +70,24 @@ const messageCount = computed(() => messages.value.length);
|
||||
/** 是否有通知 */
|
||||
const hasMessages = computed(() => messages.value.length > 0);
|
||||
|
||||
/** 仅紧急 (danger) 级别的通知 */
|
||||
const dangerMessages = computed(() =>
|
||||
messages.value.filter((m) => m.level === "danger")
|
||||
);
|
||||
|
||||
/** 最新一条紧急通知(悬浮滚动条展示用) */
|
||||
const latestDangerMessage = computed(() => {
|
||||
return dangerMessages.value.length > 0
|
||||
? dangerMessages.value[dangerMessages.value.length - 1]
|
||||
: null;
|
||||
});
|
||||
|
||||
/** 紧急通知数量 */
|
||||
const dangerCount = computed(() => dangerMessages.value.length);
|
||||
|
||||
/** 是否有紧急通知 */
|
||||
const hasDangerMessages = computed(() => dangerMessages.value.length > 0);
|
||||
|
||||
/** 详情弹窗是否可见 */
|
||||
const detailVisible = computed({
|
||||
get: () => detailTarget.value !== null,
|
||||
@@ -77,90 +99,50 @@ const detailVisible = computed({
|
||||
/** 按时间倒序排列的消息(最新在前,给通知中心和详情列表用) */
|
||||
const messagesReversed = computed(() => [...messages.value].reverse());
|
||||
|
||||
// ---------- Mock 数据 ----------
|
||||
// ---------- 后端 API ----------
|
||||
|
||||
let mockIdCounter = 0;
|
||||
|
||||
/**
|
||||
* 生成模拟气象预警通知
|
||||
* 后续接入后端时,替换为 baseService.get('/sys/alert/active')
|
||||
*/
|
||||
async function mockAlerts(): Promise<AlertMessage[]> {
|
||||
mockIdCounter++;
|
||||
const now = new Date();
|
||||
const ts = now.toLocaleTimeString("zh-CN", { hour12: false });
|
||||
|
||||
const templates: Omit<AlertMessage, "id" | "publishTime">[] = [
|
||||
{
|
||||
level: "danger",
|
||||
content: `【暴雨红色预警】省气象台${now.getHours()}时发布:预计未来6小时内将有特大暴雨,降雨量可达200毫米以上,请做好防汛准备。`
|
||||
},
|
||||
{
|
||||
level: "warning",
|
||||
content: `【台风蓝色预警】第${mockIdCounter}号台风"海燕"正在向东南沿海靠近,中心风力12级,请沿海地区密切关注。`
|
||||
},
|
||||
{
|
||||
level: "info",
|
||||
content: `【高温橙色预警】预计未来三天最高气温将达38℃以上,请做好防暑降温工作,避免高温时段户外作业。`
|
||||
},
|
||||
{
|
||||
level: "danger",
|
||||
content: `【山洪灾害红色预警】受持续降雨影响,东部山区发生山洪灾害风险极高,请立即转移安置危险区域群众。`
|
||||
},
|
||||
{
|
||||
level: "warning",
|
||||
content: `【大风黄色预警】受冷空气影响,预计今夜至明天将有8-10级大风,伴有沙尘天气,请注意防风防沙。`
|
||||
},
|
||||
{
|
||||
level: "info",
|
||||
content: `【系统维护通知】计划于${now.getMonth() + 1}月${now.getDate() + 2}日凌晨2:00-4:00进行数据系统例行维护,届时查询功能可能短暂中断。`
|
||||
},
|
||||
{
|
||||
level: "warning",
|
||||
content: `【寒潮蓝色预警】北方强冷空气南下,预计48小时内气温将下降12-14℃,最低气温可达-10℃,请注意防寒保暖。`
|
||||
},
|
||||
{
|
||||
level: "info",
|
||||
content: `【雷电黄色预警】预计今天下午将出现雷电活动,并伴有短时强降水和短时大风,请注意防范。`
|
||||
}
|
||||
];
|
||||
|
||||
// 随机选取 1-3 条
|
||||
const count = 1 + Math.floor(Math.random() * 3);
|
||||
const shuffled = [...templates].sort(() => Math.random() - 0.5).slice(0, count);
|
||||
|
||||
return shuffled.map((t, i) => ({
|
||||
...t,
|
||||
id: `alert_${now.getTime()}_${mockIdCounter}_${i}`,
|
||||
publishTime: ts
|
||||
}));
|
||||
async function fetchNotifications(): Promise<AlertMessage[]> {
|
||||
const lastId = messages.value.length > 0
|
||||
? messages.value[messages.value.length - 1].id
|
||||
: getLastSeenId() || "0";
|
||||
const res = await baseService.get(`/sys/alert/active/since?since=${lastId}`);
|
||||
if (res.code === 0 && Array.isArray(res.data)) {
|
||||
return res.data.map((item: AlertMessage) => ({
|
||||
...item,
|
||||
content: item.title ? `【${item.title}】${item.content}` : item.content
|
||||
}));
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
// ---------- 轮询控制 ----------
|
||||
/** 全量对账:从服务端拉取所有活跃通知ID,清除本地已撤回/已删除的通知 */
|
||||
async function reconcileAlerts(): Promise<void> {
|
||||
try {
|
||||
const res = await baseService.get("/sys/alert/active");
|
||||
if (res.code === 0 && Array.isArray(res.data)) {
|
||||
const serverIds = new Set((res.data as AlertMessage[]).map((a) => a.id));
|
||||
const before = messages.value.length;
|
||||
messages.value = messages.value.filter((m) => serverIds.has(m.id));
|
||||
if (messages.value.length < before && messages.value.length > 0) {
|
||||
const maxId = messages.value.reduce((max, m) => (m.id > max ? m.id : max), messages.value[0].id);
|
||||
setLastSeenId(maxId);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 静默失败
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- SSE 实时推送 + 轮询降级 ----------
|
||||
|
||||
let eventSource: EventSource | null = null;
|
||||
let pollingTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let started = false;
|
||||
|
||||
// ---------- API ----------
|
||||
|
||||
/**
|
||||
* 拉取通知。当前使用 mock 数据,后续改为:
|
||||
* const res = await baseService.get('/sys/alert/active')
|
||||
* return res.data ?? []
|
||||
*/
|
||||
async function fetchNotifications(): Promise<AlertMessage[]> {
|
||||
// TODO: 替换为真实 API 调用
|
||||
// import baseService from "@/service/baseService";
|
||||
// const res = await baseService.get("/sys/alert/active");
|
||||
// return res.code === 0 ? (res.data as AlertMessage[]) : [];
|
||||
return mockAlerts();
|
||||
}
|
||||
|
||||
/** 检测并处理新通知 */
|
||||
function checkNewAlerts(newMsgs: AlertMessage[]): void {
|
||||
/** 合并新通知到队列 */
|
||||
function mergeNewAlerts(newMsgs: AlertMessage[]): void {
|
||||
if (newMsgs.length === 0) return;
|
||||
|
||||
// 合并去重
|
||||
const existingIds = new Set(messages.value.map((m) => m.id));
|
||||
for (const msg of newMsgs) {
|
||||
if (!existingIds.has(msg.id)) {
|
||||
@@ -168,13 +150,112 @@ function checkNewAlerts(newMsgs: AlertMessage[]): void {
|
||||
}
|
||||
}
|
||||
|
||||
// FIFO 截断
|
||||
if (messages.value.length > MAX_QUEUE) {
|
||||
messages.value = messages.value.slice(messages.value.length - MAX_QUEUE);
|
||||
}
|
||||
}
|
||||
|
||||
// 有新通知 → 只更新队列,不主动展开侧栏
|
||||
// 用户通过顶栏铃铛手动打开通知中心
|
||||
/** 建立 SSE 实时推送连接 */
|
||||
function initSse(): void {
|
||||
let token: string;
|
||||
try {
|
||||
token = getToken();
|
||||
if (!token) return;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
const baseUrl = app.api || "";
|
||||
const url = `${baseUrl}/sys/alert/stream?token=${encodeURIComponent(token)}`;
|
||||
|
||||
eventSource = new EventSource(url);
|
||||
|
||||
eventSource.addEventListener("alert", (e: MessageEvent) => {
|
||||
try {
|
||||
const alert = JSON.parse(e.data) as AlertMessage;
|
||||
mergeNewAlerts([alert]);
|
||||
} catch {
|
||||
// JSON 解析失败,忽略
|
||||
}
|
||||
});
|
||||
|
||||
eventSource.addEventListener("alert-withdrawn", (e: MessageEvent) => {
|
||||
try {
|
||||
const { id } = JSON.parse(e.data) as { id: string };
|
||||
removeAlert(id);
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
});
|
||||
|
||||
eventSource.addEventListener("alert-deleted", (e: MessageEvent) => {
|
||||
try {
|
||||
const { ids } = JSON.parse(e.data) as { ids: string[] };
|
||||
for (const id of ids) {
|
||||
removeAlert(id);
|
||||
}
|
||||
} catch {
|
||||
// 忽略
|
||||
}
|
||||
});
|
||||
|
||||
eventSource.onerror = () => {
|
||||
// SSE 连接失败,关闭并降级为轮询
|
||||
closeSse();
|
||||
startPollingFallback();
|
||||
};
|
||||
}
|
||||
|
||||
/** 关闭 SSE 连接 */
|
||||
function closeSse(): void {
|
||||
if (eventSource) {
|
||||
eventSource.close();
|
||||
eventSource = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 降级轮询(SSE 失败时自动启动,每 10 秒增量拉取 + 每 60 秒全量对账) */
|
||||
function startPollingFallback(): void {
|
||||
if (pollingTimer !== null) return;
|
||||
let tick = 0;
|
||||
pollingTimer = setInterval(async () => {
|
||||
try {
|
||||
const data = await fetchNotifications();
|
||||
mergeNewAlerts(data);
|
||||
tick++;
|
||||
if (tick % 6 === 0) {
|
||||
await reconcileAlerts();
|
||||
}
|
||||
} catch {
|
||||
// 静默失败
|
||||
}
|
||||
}, 10000);
|
||||
}
|
||||
|
||||
/** 启动通知获取:先 REST API 拉存量,再建立 SSE 连接 */
|
||||
async function startPolling(_intervalMs?: number): Promise<void> {
|
||||
if (started) return;
|
||||
started = true;
|
||||
|
||||
// 先通过 REST API 拉取存量通知
|
||||
try {
|
||||
const data = await fetchNotifications();
|
||||
mergeNewAlerts(data);
|
||||
} catch {
|
||||
// 静默失败
|
||||
}
|
||||
|
||||
// 尝试建立 SSE 连接(失败则降级为轮询)
|
||||
initSse();
|
||||
}
|
||||
|
||||
function stopPolling(): void {
|
||||
closeSse();
|
||||
if (pollingTimer !== null) {
|
||||
clearInterval(pollingTimer);
|
||||
pollingTimer = null;
|
||||
}
|
||||
started = false;
|
||||
}
|
||||
|
||||
// ---------- 通知中心抽屉 ----------
|
||||
@@ -245,38 +326,6 @@ function setPosition(pos: { x: number; y: number }): void {
|
||||
position.value = pos;
|
||||
}
|
||||
|
||||
// ---------- 轮询 ----------
|
||||
|
||||
async function startPolling(intervalMs = 30000): Promise<void> {
|
||||
if (started) return;
|
||||
started = true;
|
||||
|
||||
// 立即拉取一次
|
||||
try {
|
||||
const data = await fetchNotifications();
|
||||
checkNewAlerts(data);
|
||||
} catch {
|
||||
// 静默失败
|
||||
}
|
||||
|
||||
pollingTimer = setInterval(async () => {
|
||||
try {
|
||||
const data = await fetchNotifications();
|
||||
checkNewAlerts(data);
|
||||
} catch {
|
||||
// 静默失败
|
||||
}
|
||||
}, intervalMs);
|
||||
}
|
||||
|
||||
function stopPolling(): void {
|
||||
if (pollingTimer !== null) {
|
||||
clearInterval(pollingTimer);
|
||||
pollingTimer = null;
|
||||
}
|
||||
started = false;
|
||||
}
|
||||
|
||||
// ---------- composable 导出 ----------
|
||||
|
||||
export function useAlertMarquee() {
|
||||
@@ -287,6 +336,11 @@ export function useAlertMarquee() {
|
||||
latestMessage,
|
||||
messageCount,
|
||||
hasMessages,
|
||||
// 紧急通知(悬浮滚动条用)
|
||||
dangerMessages,
|
||||
latestDangerMessage,
|
||||
dangerCount,
|
||||
hasDangerMessages,
|
||||
// 通知中心
|
||||
drawerVisible,
|
||||
toggleDrawer,
|
||||
@@ -306,7 +360,7 @@ export function useAlertMarquee() {
|
||||
clearAll,
|
||||
// 轮询
|
||||
fetchNotifications,
|
||||
checkNewAlerts,
|
||||
mergeNewAlerts,
|
||||
startPolling,
|
||||
stopPolling
|
||||
};
|
||||
|
||||
@@ -145,9 +145,7 @@ export function useWeatherFilter(opts: UseWeatherFilterOptions) {
|
||||
return (
|
||||
FILTER_KEYS.some((k) => f[k]?.op) ||
|
||||
f.rainLevel.length > 0 ||
|
||||
f.decades.length > 0 ||
|
||||
f.yearRange[0] !== resolveStart() ||
|
||||
f.yearRange[1] !== resolveEnd()
|
||||
f.decades.length > 0
|
||||
);
|
||||
});
|
||||
|
||||
@@ -156,7 +154,6 @@ export function useWeatherFilter(opts: UseWeatherFilterOptions) {
|
||||
let c = FILTER_KEYS.filter((k) => f[k]?.op).length;
|
||||
if (f.rainLevel.length) c++;
|
||||
if (f.decades.length) c++;
|
||||
if (f.yearRange[0] !== resolveStart() || f.yearRange[1] !== resolveEnd()) c++;
|
||||
return c;
|
||||
});
|
||||
|
||||
@@ -168,7 +165,6 @@ export function useWeatherFilter(opts: UseWeatherFilterOptions) {
|
||||
if (!matchOp(row.tmax, f.tmaxF)) return false;
|
||||
if (!matchOp(row.tmin, f.tminF)) return false;
|
||||
if (!matchOp(row.tavg, f.tavgF)) return false;
|
||||
if (row.year < f.yearRange[0] || row.year > f.yearRange[1]) return false;
|
||||
if (f.decades.length > 0 && !f.decades.includes(Math.floor(row.year / 10) * 10)) return false;
|
||||
if (f.rainLevel.length > 0 && !f.rainLevel.includes(row._rainLevel ?? "")) return false;
|
||||
return true;
|
||||
|
||||
@@ -1,3 +1,13 @@
|
||||
// Self-hosted fonts (no external network dependency, compatible with intranet deployment)
|
||||
import "@fontsource/noto-sans-sc/300.css";
|
||||
import "@fontsource/noto-sans-sc/400.css";
|
||||
import "@fontsource/noto-sans-sc/500.css";
|
||||
import "@fontsource/noto-sans-sc/600.css";
|
||||
import "@fontsource/noto-sans-sc/700.css";
|
||||
import "@fontsource/noto-sans-sc/900.css";
|
||||
import "@fontsource/jetbrains-mono/400.css";
|
||||
import "@fontsource/jetbrains-mono/600.css";
|
||||
|
||||
import "@/assets/icons/iconfont/iconfont.js";
|
||||
import RenDeptTree from "@/components/sys-dept-tree";
|
||||
import RenRadioGroup from "@/components/sys-radio-group";
|
||||
|
||||
@@ -233,27 +233,9 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="filter-group">
|
||||
<div class="fg-title"><span class="fg-dot year-dot"></span> 年份条件</div>
|
||||
<div class="fg-title"><span class="fg-dot year-dot"></span> 年代筛选</div>
|
||||
<div class="fg-row">
|
||||
<span class="fg-label">年份范围</span>
|
||||
<el-input-number
|
||||
v-model="filters.yearRange[0]"
|
||||
:min="MIN_YEAR"
|
||||
:max="currentYear"
|
||||
size="small"
|
||||
style="width: 10ch"
|
||||
/>
|
||||
<span class="fg-sep">~</span>
|
||||
<el-input-number
|
||||
v-model="filters.yearRange[1]"
|
||||
:min="MIN_YEAR"
|
||||
:max="currentYear"
|
||||
size="small"
|
||||
style="width: 10ch"
|
||||
/>
|
||||
</div>
|
||||
<div class="fg-row">
|
||||
<span class="fg-label">年代筛选</span>
|
||||
<span class="fg-label">年代</span>
|
||||
<div class="level-chips">
|
||||
<span
|
||||
v-for="d in availableDecades"
|
||||
@@ -709,7 +691,6 @@ function rowMatchesFilter(row: WeatherDataRow, f: typeof filters.value): boolean
|
||||
if (f.tavgF.op === "lte" && n > f.tavgF.val) return false;
|
||||
if (f.tavgF.op === "range" && (n < (f.tavgF.min ?? -Infinity) || n > (f.tavgF.max ?? Infinity))) return false;
|
||||
}
|
||||
if (row.year < f.yearRange[0] || row.year > f.yearRange[1]) return false;
|
||||
if (f.decades.length > 0 && !f.decades.includes(Math.floor(row.year / 10) * 10)) return false;
|
||||
if (f.rainLevel.length > 0 && !f.rainLevel.includes(rainLevelLabel(row.rainfall))) return false;
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
<template>
|
||||
<el-dialog v-model="visible" :title="!dataForm.id ? '新增通知' : '修改通知'" :close-on-click-modal="false" :close-on-press-escape="false">
|
||||
<el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="100px">
|
||||
<el-form-item prop="level" label="级别">
|
||||
<el-select v-model="dataForm.level" placeholder="级别">
|
||||
<el-option label="提示" value="info"></el-option>
|
||||
<el-option label="警告" value="warning"></el-option>
|
||||
<el-option label="紧急" value="danger"></el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item prop="title" label="标题">
|
||||
<el-input v-model="dataForm.title" placeholder="标题"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="content" label="内容">
|
||||
<el-input v-model="dataForm.content" type="textarea" :rows="5" placeholder="通知正文"></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item prop="sourceType" label="来源类型">
|
||||
<el-select v-model="dataForm.sourceType" placeholder="来源类型">
|
||||
<el-option label="手动发布" value="manual"></el-option>
|
||||
<el-option label="导入任务" value="import"></el-option>
|
||||
<el-option label="定时任务" value="schedule"></el-option>
|
||||
<el-option label="数据源监测" value="datasource"></el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item prop="expireTime" label="过期时间">
|
||||
<el-date-picker
|
||||
v-model="dataForm.expireTime"
|
||||
type="datetime"
|
||||
placeholder="过期时间(选填)"
|
||||
value-format="YYYY-MM-DD HH:mm:ss"
|
||||
style="width: 100%"
|
||||
></el-date-picker>
|
||||
</el-form-item>
|
||||
<el-form-item v-if="dataForm.id" label="发布时间">
|
||||
<span>{{ dataForm.publishTime }}</span>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<template v-slot:footer>
|
||||
<el-button @click="visible = false">取消</el-button>
|
||||
<el-button type="primary" @click="dataFormSubmitHandle()">确定</el-button>
|
||||
</template>
|
||||
</el-dialog>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { reactive, ref } from "vue";
|
||||
import baseService from "@/service/baseService";
|
||||
import { ElMessage } from "element-plus";
|
||||
|
||||
const emit = defineEmits(["refreshDataList"]);
|
||||
|
||||
const visible = ref(false);
|
||||
const dataFormRef = ref();
|
||||
|
||||
const defaultForm = () => ({
|
||||
id: "",
|
||||
level: "info",
|
||||
title: "",
|
||||
content: "",
|
||||
sourceType: "manual",
|
||||
expireTime: "",
|
||||
publishTime: ""
|
||||
});
|
||||
|
||||
const dataForm = reactive(defaultForm());
|
||||
|
||||
const rules = ref({
|
||||
level: [{ required: true, message: "必填项不能为空", trigger: "change" }],
|
||||
title: [{ required: true, message: "必填项不能为空", trigger: "blur" }],
|
||||
content: [{ required: true, message: "必填项不能为空", trigger: "blur" }]
|
||||
});
|
||||
|
||||
const init = (id?: string) => {
|
||||
visible.value = true;
|
||||
Object.assign(dataForm, defaultForm());
|
||||
|
||||
if (dataFormRef.value) {
|
||||
dataFormRef.value.resetFields();
|
||||
}
|
||||
|
||||
if (id) {
|
||||
getInfo(id);
|
||||
}
|
||||
};
|
||||
|
||||
const getInfo = (id: string) => {
|
||||
baseService.get(`/sys/alert/${id}`).then((res) => {
|
||||
Object.assign(dataForm, res.data);
|
||||
});
|
||||
};
|
||||
|
||||
const dataFormSubmitHandle = () => {
|
||||
dataFormRef.value.validate((valid: boolean) => {
|
||||
if (!valid) {
|
||||
return false;
|
||||
}
|
||||
(!dataForm.id ? baseService.post : baseService.put)("/sys/alert", {
|
||||
...dataForm,
|
||||
id: dataForm.id || undefined,
|
||||
expireTime: dataForm.expireTime || undefined,
|
||||
publishTime: undefined
|
||||
}).then(() => {
|
||||
ElMessage.success({
|
||||
message: "成功",
|
||||
duration: 500,
|
||||
onClose: () => {
|
||||
visible.value = false;
|
||||
emit("refreshDataList");
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
defineExpose({ init });
|
||||
</script>
|
||||
@@ -0,0 +1,128 @@
|
||||
<template>
|
||||
<div class="mod-sys__alert">
|
||||
<el-form :inline="true" :model="state.dataForm" @keyup.enter="state.getDataList()">
|
||||
<el-form-item>
|
||||
<el-select v-model="state.dataForm.level" placeholder="级别" clearable>
|
||||
<el-option label="提示" value="info"></el-option>
|
||||
<el-option label="警告" value="warning"></el-option>
|
||||
<el-option label="紧急" value="danger"></el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-input v-model="state.dataForm.title" placeholder="标题" clearable></el-input>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-select v-model="state.dataForm.sourceType" placeholder="来源类型" clearable>
|
||||
<el-option label="手动发布" value="manual"></el-option>
|
||||
<el-option label="导入任务" value="import"></el-option>
|
||||
<el-option label="定时任务" value="schedule"></el-option>
|
||||
<el-option label="数据源监测" value="datasource"></el-option>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button @click="state.getDataList()">查询</el-button>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button v-if="state.hasPermission('sys:alert:save')" type="primary" @click="addOrUpdateHandle()">新增</el-button>
|
||||
</el-form-item>
|
||||
<el-form-item>
|
||||
<el-button v-if="state.hasPermission('sys:alert:delete')" type="danger" @click="state.deleteHandle()">删除</el-button>
|
||||
</el-form-item>
|
||||
</el-form>
|
||||
<el-table
|
||||
v-loading="state.dataListLoading"
|
||||
:data="state.dataList"
|
||||
border
|
||||
@selection-change="state.dataListSelectionChangeHandle"
|
||||
@sort-change="state.dataListSortChangeHandle"
|
||||
style="width: 100%"
|
||||
>
|
||||
<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
|
||||
<el-table-column prop="id" label="ID" header-align="center" align="center" width="180" show-overflow-tooltip></el-table-column>
|
||||
<el-table-column prop="level" label="级别" sortable="custom" header-align="center" align="center" width="80">
|
||||
<template v-slot="scope">
|
||||
<el-tag v-if="scope.row.level === 'danger'" size="small" type="danger">紧急</el-tag>
|
||||
<el-tag v-else-if="scope.row.level === 'warning'" size="small" type="warning">警告</el-tag>
|
||||
<el-tag v-else size="small" type="info">提示</el-tag>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="title" label="标题" header-align="center" align="center" width="200" show-overflow-tooltip></el-table-column>
|
||||
<el-table-column prop="content" label="内容" header-align="center" show-overflow-tooltip></el-table-column>
|
||||
<el-table-column prop="sourceType" label="来源类型" header-align="center" align="center" width="110">
|
||||
<template v-slot="scope">
|
||||
<span v-if="scope.row.sourceType === 'manual'">手动发布</span>
|
||||
<span v-else-if="scope.row.sourceType === 'import'">导入任务</span>
|
||||
<span v-else-if="scope.row.sourceType === 'schedule'">定时任务</span>
|
||||
<span v-else-if="scope.row.sourceType === 'datasource'">数据源监测</span>
|
||||
<span v-else>{{ scope.row.sourceType }}</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column prop="publishTime" label="发布时间" sortable="custom" header-align="center" align="center" width="170"></el-table-column>
|
||||
<el-table-column prop="expireTime" label="过期时间" sortable="custom" header-align="center" align="center" width="170">
|
||||
<template v-slot="scope">
|
||||
<span v-if="scope.row.expireTime">{{ scope.row.expireTime }}</span>
|
||||
<span v-else style="color: #999">--</span>
|
||||
</template>
|
||||
</el-table-column>
|
||||
<el-table-column label="操作" fixed="right" header-align="center" align="center" width="200">
|
||||
<template v-slot="scope">
|
||||
<el-button v-if="state.hasPermission('sys:alert:update')" type="primary" link @click="addOrUpdateHandle(scope.row.id)">修改</el-button>
|
||||
<el-button v-if="state.hasPermission('sys:alert:delete')" type="danger" link @click="state.deleteHandle(scope.row.id)">删除</el-button>
|
||||
<el-button v-if="state.hasPermission('sys:alert:update')" type="warning" link @click="withdrawHandle(scope.row.id)">撤回</el-button>
|
||||
</template>
|
||||
</el-table-column>
|
||||
</el-table>
|
||||
<el-pagination
|
||||
:current-page="state.page"
|
||||
:page-sizes="[10, 20, 50, 100]"
|
||||
:page-size="state.limit"
|
||||
:total="state.total"
|
||||
layout="total, sizes, prev, pager, next, jumper"
|
||||
@size-change="state.pageSizeChangeHandle"
|
||||
@current-change="state.pageCurrentChangeHandle"
|
||||
>
|
||||
</el-pagination>
|
||||
<!-- 弹窗, 新增 / 修改 -->
|
||||
<add-or-update ref="addOrUpdateRef" @refreshDataList="state.getDataList"></add-or-update>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import useView from "@/hooks/useView";
|
||||
import { reactive, ref, toRefs } from "vue";
|
||||
import baseService from "@/service/baseService";
|
||||
import { ElMessage, ElMessageBox } from "element-plus";
|
||||
import AddOrUpdate from "./system-alert-add-or-update.vue";
|
||||
|
||||
const view = reactive({
|
||||
getDataListURL: "/sys/alert/page",
|
||||
getDataListIsPage: true,
|
||||
deleteURL: "/sys/alert",
|
||||
deleteIsBatch: true,
|
||||
dataForm: {
|
||||
level: "",
|
||||
title: "",
|
||||
sourceType: ""
|
||||
}
|
||||
});
|
||||
|
||||
const state = reactive({ ...useView(view), ...toRefs(view) });
|
||||
|
||||
const addOrUpdateRef = ref();
|
||||
const addOrUpdateHandle = (id?: string) => {
|
||||
addOrUpdateRef.value.init(id);
|
||||
};
|
||||
|
||||
const withdrawHandle = (id: string) => {
|
||||
ElMessageBox.confirm("确定要撤回该通知吗?撤回后前端将不再展示。", "提示", {
|
||||
confirmButtonText: "确定",
|
||||
cancelButtonText: "取消",
|
||||
type: "warning"
|
||||
}).then(() => {
|
||||
baseService.put(`/sys/alert/${id}/withdraw`).then(() => {
|
||||
ElMessage.success("撤回成功");
|
||||
state.getDataList();
|
||||
});
|
||||
});
|
||||
};
|
||||
</script>
|
||||
Reference in New Issue
Block a user