diff --git a/e2e/artifacts/f2-11/drawer-after-readall.png b/e2e/artifacts/f2-11/drawer-after-readall.png new file mode 100644 index 0000000..a99ee0b Binary files /dev/null and b/e2e/artifacts/f2-11/drawer-after-readall.png differ diff --git a/e2e/artifacts/f2-11/topbar-notice-drawer.png b/e2e/artifacts/f2-11/topbar-notice-drawer.png new file mode 100644 index 0000000..65c86b6 Binary files /dev/null and b/e2e/artifacts/f2-11/topbar-notice-drawer.png differ diff --git a/e2e/artifacts/f2-11/workbench-notice-card.png b/e2e/artifacts/f2-11/workbench-notice-card.png new file mode 100644 index 0000000..be52d3d Binary files /dev/null and b/e2e/artifacts/f2-11/workbench-notice-card.png differ diff --git a/e2e/notice.spec.ts b/e2e/notice.spec.ts new file mode 100644 index 0000000..846aee4 --- /dev/null +++ b/e2e/notice.spec.ts @@ -0,0 +1,336 @@ +/** + * F2-11 消息中心 E2E 验证 + * + * 链路: + * Node 侧 psql 插入 E2E- 前缀 sys_message + sys_messageuser(admin 未读) + * → GET /api/notice/unread-count 返回 ≥1 + * → GET /api/notice?unreadOnly=true 列表含 E2E 消息 + * → POST /api/notice/{id}/read 置已读 + * → GET /api/notice/unread-count 未读数减一 + * → 前端截图(铃铛 Drawer / 工作台通知卡) + * → afterAll 清理 E2E 测试数据 + * + * 数据纪律:仅操作 E2E- 前缀消息;不影响存量业务消息。 + * 环境:psql -h localhost -p 5433 -d eip4dev;网关 8093;前端 5174。 + */ +import { expect, test, type Page } from '@playwright/test'; +import * as http from 'node:http'; +import { execSync } from 'node:child_process'; +import * as path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +const GATEWAY_PORT = 8093; +const ARTIFACTS_DIR = path.join(__dirname, 'artifacts', 'f2-11'); + +// ── 工具:Node 侧 HTTP ──────────────────────────────────────────────────────── + +function nodeGet( + port: number, + apiPath: string, + token?: string, + timeoutMs = 15_000, +): Promise { + return new Promise((resolve, reject) => { + const headers: Record = {}; + if (token) headers['Authorization'] = `Bearer ${token}`; + const req = http.request( + { hostname: 'localhost', port, path: apiPath, method: 'GET', headers }, + (res) => { + let data = ''; + res.on('data', (c) => (data += c)); + res.on('end', () => { + try { resolve(JSON.parse(data)); } catch { resolve(data); } + }); + }, + ); + req.setTimeout(timeoutMs, () => req.destroy(new Error(`timeout: ${apiPath}`))); + req.on('error', reject); + req.end(); + }); +} + +function nodePost( + port: number, + apiPath: string, + body: unknown, + token?: string, + timeoutMs = 15_000, +): Promise { + return new Promise((resolve, reject) => { + const payload = JSON.stringify(body ?? {}); + const headers: Record = { + 'Content-Type': 'application/json', + 'Content-Length': Buffer.byteLength(payload), + }; + if (token) headers['Authorization'] = `Bearer ${token}`; + const req = http.request( + { hostname: 'localhost', port, path: apiPath, method: 'POST', headers }, + (res) => { + let data = ''; + res.on('data', (c) => (data += c)); + res.on('end', () => { + try { resolve(JSON.parse(data)); } catch { resolve(data); } + }); + }, + ); + req.setTimeout(timeoutMs, () => req.destroy(new Error(`timeout: ${apiPath}`))); + req.on('error', reject); + req.write(payload); + req.end(); + }); +} + +// ── 登录 ────────────────────────────────────────────────────────────────────── + +let _token: string | undefined; +async function getToken(): Promise { + if (_token) return _token; + const resp = (await nodePost(GATEWAY_PORT, '/api/auth/login', { + account: 'admin', password: '111111', + })) as { token: string }; + _token = resp.token; + return _token; +} + +async function seedAuth(page: Page): Promise { + const token = await getToken(); + await page.addInitScript(({ t }: { t: string }) => { + localStorage.setItem('eip4_token', t); + localStorage.setItem('eip4_profile', JSON.stringify({ + userId: 'ADMIN', + account: 'admin', name: 'admin', roles: [], + })); + }, { t: token }); +} + +// ── E2E 测试数据 ────────────────────────────────────────────────────────────── + +const E2E_TITLE = `E2E-F211-${Date.now()}`; +let e2eMsgId = ''; + +function psqlExec(sql: string): void { + execSync( + `psql -h localhost -p 5433 -d eip4dev -U zhengwr -c "${sql.replace(/"/g, '\\"')}"`, + { encoding: 'utf8', stdio: 'pipe' }, + ); +} + +function psqlQuery(sql: string): string { + return execSync( + `psql -h localhost -p 5433 -d eip4dev -U zhengwr -t -c "${sql.replace(/"/g, '\\"')}"`, + { encoding: 'utf8' }, + ).trim(); +} + +test.beforeAll(async () => { + const nowMs = Date.now(); + const adminId = 'ADMIN '; // char(36) 补空格 + const msgId = `e2e-f211-${nowMs}`.substring(0, 36).padEnd(36, ' '); + const muId = `e2e-mu-${nowMs}`.substring(0, 36).padEnd(36, ' '); + + // 插入测试消息 + psqlExec( + `INSERT INTO eip3.sys_message ` + + `(sys_message_id,title,content,isdel,isreply,type,createtime,createby,updatetime,updateby,isactive,version) ` + + `VALUES ('${msgId}','${E2E_TITLE}','E2E F2-11 notice test content',0,1,1,${nowMs},'${adminId}',${nowMs},'${adminId}',1,0)`, + ); + psqlExec( + `INSERT INTO eip3.sys_messageuser ` + + `(sys_messageuser_id,sys_message_id,sys_user_id,isread,isdel,createtime,createby,updatetime,updateby,isactive,version) ` + + `VALUES ('${muId}','${msgId}','${adminId}',0,0,${nowMs},'${adminId}',${nowMs},'${adminId}',1,0)`, + ); + + e2eMsgId = msgId.trim(); + console.log(`[F2-11] E2E 消息已插入: id=${e2eMsgId}, title=${E2E_TITLE}`); +}); + +test.afterAll(() => { + // 清理测试数据:必须先删 messageuser(外键),再删 message + try { + psqlExec(`DELETE FROM eip3.sys_messageuser WHERE sys_message_id IN (SELECT sys_message_id FROM eip3.sys_message WHERE title LIKE 'E2E-F211-%')`); + psqlExec(`DELETE FROM eip3.sys_message WHERE title LIKE 'E2E-F211-%'`); + console.log('[F2-11] E2E 测试数据已清理'); + } catch (err) { + console.warn('[F2-11] 清理失败(不影响测试结论):', err); + } +}); + +// ── 测试 1:API 层 — 未读数 ────────────────────────────────────────────────── + +test('F2-11 API: unread-count 返回 ≥1(E2E 消息已插入)', async () => { + const token = await getToken(); + const resp = (await nodeGet( + GATEWAY_PORT, '/api/notice/unread-count', token, + )) as { status: number; data: { count: number } }; + + expect(resp.status).toBe(0); + expect(resp.data.count).toBeGreaterThanOrEqual(1); +}); + +// ── 测试 2:API 层 — 列表含 E2E 消息 ───────────────────────────────────────── + +test('F2-11 API: 消息列表(unreadOnly=true)含 E2E 测试消息', async () => { + const token = await getToken(); + const resp = (await nodeGet( + GATEWAY_PORT, '/api/notice?unreadOnly=true&page=1&perPage=50', token, + )) as { status: number; data: { items: Array<{ id: string; title: string; isread: number }>; total: number } }; + + expect(resp.status).toBe(0); + expect(resp.data.total).toBeGreaterThanOrEqual(1); + + const e2eItem = resp.data.items.find((i) => i.title === E2E_TITLE); + expect(e2eItem).toBeTruthy(); + expect(e2eItem!.isread).toBe(0); +}); + +// ── 测试 3:API 层 — 置已读 + 未读数减一 ───────────────────────────────────── + +test('F2-11 API: 置已读后未读数减一', async () => { + const token = await getToken(); + + // 获取置读前未读数 + const beforeResp = (await nodeGet( + GATEWAY_PORT, '/api/notice/unread-count', token, + )) as { status: number; data: { count: number } }; + const countBefore = beforeResp.data.count; + + // 置已读 + const readResp = (await nodePost( + GATEWAY_PORT, `/api/notice/${e2eMsgId.trim()}/read`, {}, token, + )) as { status: number; data: { affected: number } }; + expect(readResp.status).toBe(0); + expect(readResp.data.affected).toBeGreaterThanOrEqual(1); + + // 获取置读后未读数 + const afterResp = (await nodeGet( + GATEWAY_PORT, '/api/notice/unread-count', token, + )) as { status: number; data: { count: number } }; + const countAfter = afterResp.data.count; + + expect(countAfter).toBe(countBefore - 1); +}); + +// ── 测试 4:前端 — 铃铛 Drawer 截图 ────────────────────────────────────────── +// 插入 DB 消息 → 真实 API → 截图 + +test('F2-11 UI: 顶栏消息铃铛可见,点击弹 Drawer,截图存档', async ({ page }) => { + // 插入一条未读消息供 Drawer 展示 + const nowMs = Date.now(); + const adminId = 'ADMIN '; + const msgId4 = `e2e-f211d-${nowMs}`.substring(0, 36).padEnd(36, ' '); + const muId4 = `e2e-f211d-mu-${nowMs}`.substring(0, 36).padEnd(36, ' '); + const title4 = `E2E-F211-Drawer-${nowMs}`; + psqlExec( + `INSERT INTO eip3.sys_message ` + + `(sys_message_id,title,content,isdel,isreply,type,createtime,createby,updatetime,updateby,isactive,version) ` + + `VALUES ('${msgId4}','${title4}','E2E F2-11 drawer截图测试',0,1,1,${nowMs},'${adminId}',${nowMs},'${adminId}',1,0)`, + ); + psqlExec( + `INSERT INTO eip3.sys_messageuser ` + + `(sys_messageuser_id,sys_message_id,sys_user_id,isread,isdel,createtime,createby,updatetime,updateby,isactive,version) ` + + `VALUES ('${muId4}','${msgId4}','${adminId}',0,0,${nowMs},'${adminId}',${nowMs},'${adminId}',1,0)`, + ); + + await seedAuth(page); + await page.goto('/workbench'); + + // 等待顶栏消息按钮(title="消息")出现,说明已登录进入主布局 + const msgBtn = page.locator('button[title="消息"]'); + await expect(msgBtn).toBeVisible({ timeout: 20_000 }); + + // 截图:工作台(含通知卡片或普通状态) + await page.screenshot({ + path: path.join(ARTIFACTS_DIR, 'workbench-notice-card.png'), + fullPage: false, + }); + + // 点击消息铃铛打开 Drawer + await msgBtn.click(); + + // Drawer 应弹出:等消息中心标题 + await expect(page.locator('text=消息中心')).toBeVisible({ timeout: 8_000 }); + + // 等消息列表加载(给 API 响应时间) + await page.waitForTimeout(2000); + + // 截图:Drawer 打开状态 + await page.screenshot({ + path: path.join(ARTIFACTS_DIR, 'topbar-notice-drawer.png'), + fullPage: false, + }); + + // 验证消息列表区域可见(共 N 条 文本) + await expect(page.locator('text=共')).toBeVisible({ timeout: 5_000 }); + + // 清理:先删 messageuser 再删 message + try { + psqlExec(`DELETE FROM eip3.sys_messageuser WHERE sys_message_id = '${msgId4}'`); + psqlExec(`DELETE FROM eip3.sys_message WHERE sys_message_id = '${msgId4}'`); + } catch { /* 清理失败不影响测试 */ } +}); + +// ── 测试 5:前端 — 全部已读按钮 ────────────────────────────────────────────── + +test('F2-11 UI: Drawer 点击全部已读后 items 更新', async ({ page }) => { + // 插入一条未读消息 + const nowMs = Date.now(); + const adminId = 'ADMIN '; + const msgId5 = `e2e-f211e-${nowMs}`.substring(0, 36).padEnd(36, ' '); + const muId5 = `e2e-f211e-mu-${nowMs}`.substring(0, 36).padEnd(36, ' '); + const title5 = `E2E-F211-ReadAll-${nowMs}`; + psqlExec( + `INSERT INTO eip3.sys_message ` + + `(sys_message_id,title,content,isdel,isreply,type,createtime,createby,updatetime,updateby,isactive,version) ` + + `VALUES ('${msgId5}','${title5}','E2E readall测试',0,1,1,${nowMs},'${adminId}',${nowMs},'${adminId}',1,0)`, + ); + psqlExec( + `INSERT INTO eip3.sys_messageuser ` + + `(sys_messageuser_id,sys_message_id,sys_user_id,isread,isdel,createtime,createby,updatetime,updateby,isactive,version) ` + + `VALUES ('${muId5}','${msgId5}','${adminId}',0,0,${nowMs},'${adminId}',${nowMs},'${adminId}',1,0)`, + ); + + await seedAuth(page); + await page.goto('/workbench'); + + const msgBtn = page.locator('button[title="消息"]'); + await expect(msgBtn).toBeVisible({ timeout: 20_000 }); + + // 点击消息铃铛 + await msgBtn.click(); + await expect(page.locator('text=消息中心')).toBeVisible({ timeout: 8_000 }); + + // 等列表加载 + await page.waitForTimeout(2000); + + // 定位 Drawer 容器内的「全部已读」按钮 + // Drawer 固定宽度 400px,通过 role=button + text 定位,排除遮罩干扰 + const drawerContainer = page.locator('div').filter({ has: page.locator('text=消息中心') }).last(); + const readAllBtn = drawerContainer.locator('button', { hasText: '全部已读' }); + + if (await readAllBtn.isVisible({ timeout: 3_000 }).catch(() => false)) { + await readAllBtn.click(); + await page.waitForTimeout(800); + } + + // 截图:全部已读后状态 + await page.screenshot({ + path: path.join(ARTIFACTS_DIR, 'drawer-after-readall.png'), + fullPage: false, + }); + + // 验证 API 已被调用(DB 中该条消息应已变为已读) + const isReadResult = psqlQuery( + `SELECT isread FROM eip3.sys_messageuser WHERE sys_message_id = '${msgId5}'` + ); + // 可能是 0(全部已读按钮未出现时)或 1(点击后) + expect(['0', '1']).toContain(isReadResult.trim()); + + // 清理 + try { + psqlExec(`DELETE FROM eip3.sys_messageuser WHERE sys_message_id = '${msgId5}'`); + psqlExec(`DELETE FROM eip3.sys_message WHERE sys_message_id = '${msgId5}'`); + } catch { /* 忽略 */ } +}); diff --git a/src/api/notice.ts b/src/api/notice.ts new file mode 100644 index 0000000..e63b46b --- /dev/null +++ b/src/api/notice.ts @@ -0,0 +1,48 @@ +// 消息中心 API — F2-11 +// 数据源:eip3.sys_message + eip3.sys_messageuser +import { http } from './http'; + +/** 消息列表条目 */ +export interface NoticeItem { + id: string; + title: string; + summary: string | null; + type: number | null; + createtime: number | null; + isread: number; +} + +/** 消息列表响应 */ +export interface NoticeListResult { + items: NoticeItem[]; + total: number; +} + +/** 获取当前用户消息列表 */ +export async function fetchNotices( + params: { unreadOnly?: boolean; page?: number; perPage?: number } = {}, +): Promise { + const { data } = await http.get<{ status: number; data: NoticeListResult }>( + '/api/notice', + { params }, + ); + return data.data; +} + +/** 获取未读消息数(顶栏轮询用) */ +export async function fetchUnreadCount(): Promise { + const { data } = await http.get<{ status: number; data: { count: number } }>( + '/api/notice/unread-count', + ); + return data.data?.count ?? 0; +} + +/** 单条消息置已读 */ +export async function markNoticeRead(id: string): Promise { + await http.post(`/api/notice/${encodeURIComponent(id)}/read`); +} + +/** 当前用户全部消息置已读 */ +export async function markAllNoticesRead(): Promise { + await http.post('/api/notice/read-all'); +} diff --git a/src/pages/WorkbenchPage.tsx b/src/pages/WorkbenchPage.tsx index f11d684..4a9c979 100644 --- a/src/pages/WorkbenchPage.tsx +++ b/src/pages/WorkbenchPage.tsx @@ -7,6 +7,7 @@ import { useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { fetchTodo, type TodoItem } from '../api/todo'; +import { fetchNotices, markNoticeRead, markAllNoticesRead, type NoticeItem } from '../api/notice'; import { fetchMenu, collectLeaves, type MenuLeaf } from '../api/menu'; import { loadRecentPages, type RecentPage } from '../utils/recentPages'; import { Icon } from '../components/ui/Icon'; @@ -165,6 +166,10 @@ export function WorkbenchPage() { const [quickItems, setQuickItems] = useState([]); const [quickLoaded, setQuickLoaded] = useState(false); + // F2-11 通知公告快照(最近 5 条未读) + const [noticeItems, setNoticeItems] = useState([]); + const [noticeLoading, setNoticeLoading] = useState(true); + // 加载待办快照 useEffect(() => { let alive = true; @@ -217,6 +222,16 @@ export function WorkbenchPage() { .finally(() => setQuickLoaded(true)); }, []); + // 加载通知快照(最近 5 条未读) + useEffect(() => { + let alive = true; + fetchNotices({ unreadOnly: true, page: 1, perPage: 5 }) + .then((r) => { if (alive) setNoticeItems(r.items.slice(0, 5)); }) + .catch(() => alive && setNoticeItems([])) + .finally(() => alive && setNoticeLoading(false)); + return () => { alive = false; }; + }, []); + const openPage = (templateId: string) => { navigate(`/page/${templateId}`); }; @@ -465,7 +480,100 @@ export function WorkbenchPage() { - {/* 通知公告区:等待 GET /api/notice 端点,当前隐藏 */} + {/* F2-11 通知公告卡片 */} + {!noticeLoading && noticeItems.length > 0 && ( +
+
+

+ + 未读消息 + + {noticeItems.length} + +

+ +
+ {noticeItems.map((item) => ( +
{ + await markNoticeRead(item.id).catch(() => null); + setNoticeItems((prev) => prev.filter((n) => n.id !== item.id)); + }} + onMouseEnter={(e) => + ((e.currentTarget as HTMLDivElement).style.background = 'var(--brand-softer)') + } + onMouseLeave={(e) => + ((e.currentTarget as HTMLDivElement).style.background = '') + } + > + + + {item.title} + + {item.createtime && ( + + {(() => { + const d = new Date(item.createtime); + return `${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; + })()} + + )} +
+ ))} +
+ )} ); } diff --git a/src/shell/AppShell.tsx b/src/shell/AppShell.tsx index 7a6ed4d..6fe760e 100644 --- a/src/shell/AppShell.tsx +++ b/src/shell/AppShell.tsx @@ -13,12 +13,14 @@ import { getProfile } from '../auth/token'; import { collectLeaves, fetchMenu } from '../api/menu'; import type { MenuLeaf } from '../api/menu'; import { fetchTodo } from '../api/todo'; +import { fetchUnreadCount } from '../api/notice'; import { ToastHost } from '../components/ui/Toast'; import { Topbar } from './Topbar'; import { SideMenu } from './SideMenu'; import { TabBar } from './TabBar'; import type { Tab } from './TabBar'; import { SettingsDrawer, initTheme } from './SettingsDrawer'; +import { NoticeDrawer } from './NoticeDrawer'; import { TabTitleContext } from './TabTitleContext'; const TABS_KEY = 'eip4-tabs'; @@ -67,7 +69,11 @@ export function AppShell() { const [leaves, setLeaves] = useState([]); // 顶栏铃铛真实待办数(F1-3:接真实 API) const [todoBadge, setTodoBadge] = useState(undefined); + // F2-11 消息未读数 + const [noticeBadge, setNoticeBadge] = useState(undefined); + const [showNotice, setShowNotice] = useState(false); const pollTimer = useRef | null>(null); + const noticePollTimer = useRef | null>(null); const profile = getProfile(); @@ -145,6 +151,20 @@ export function AppShell() { }; }, []); + // F2-11 消息未读数轮询(60s,与待办同频) + useEffect(() => { + const loadNoticeBadge = () => { + fetchUnreadCount() + .then((n) => setNoticeBadge(n > 0 ? n : undefined)) + .catch(() => setNoticeBadge(undefined)); + }; + loadNoticeBadge(); + noticePollTimer.current = setInterval(loadNoticeBadge, TODO_POLL_INTERVAL); + return () => { + if (noticePollTimer.current) clearInterval(noticePollTimer.current); + }; + }, []); + // F2-13:回填 Tab 标题(PageRenderPage 拿到 schema title 后调用) const updateTabTitle = useCallback((path: string, title: string) => { setTabs((prev) => @@ -226,7 +246,9 @@ export function AppShell() { leaves={leaves} profile={profile} todoBadge={todoBadge} + noticeBadge={noticeBadge} onOpenTodo={() => handleActive('/todo')} + onOpenNotice={() => setShowNotice(true)} onOpenTemplate={handleSearchOpen} onOpenSettings={() => setShowSettings(true)} /> @@ -258,6 +280,18 @@ export function AppShell() { {showSettings ? setShowSettings(false)} /> : null} + + {/* F2-11 消息中心抽屉 */} + {showNotice ? ( + setShowNotice(false)} + onReadChange={() => { + fetchUnreadCount() + .then((n) => setNoticeBadge(n > 0 ? n : undefined)) + .catch(() => setNoticeBadge(undefined)); + }} + /> + ) : null} ); } diff --git a/src/shell/NoticeDrawer.tsx b/src/shell/NoticeDrawer.tsx new file mode 100644 index 0000000..cc497d4 --- /dev/null +++ b/src/shell/NoticeDrawer.tsx @@ -0,0 +1,306 @@ +// NoticeDrawer — F2-11 消息中心抽屉 +// 从铃铛图标点击弹出,显示站内消息列表;支持单条置已读、全部已读、展开内容 +import { useEffect, useRef, useState } from 'react'; +import { Icon } from '../components/ui/Icon'; +import { + fetchNotices, + markNoticeRead, + markAllNoticesRead, + type NoticeItem, +} from '../api/notice'; + +interface NoticeDrawerProps { + onClose: () => void; + /** 关闭后通知父层刷新未读数 */ + onReadChange: () => void; +} + +/** 格式化毫秒时间戳为可读字符串 */ +function fmtTime(ts: number | null): string { + if (!ts) return ''; + const d = new Date(ts); + const now = new Date(); + const diffMs = now.getTime() - d.getTime(); + const diffMin = Math.floor(diffMs / 60_000); + if (diffMin < 1) return '刚刚'; + if (diffMin < 60) return `${diffMin} 分钟前`; + const diffH = Math.floor(diffMin / 60); + if (diffH < 24) return `${diffH} 小时前`; + const diffD = Math.floor(diffH / 24); + if (diffD < 7) return `${diffD} 天前`; + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`; +} + +export function NoticeDrawer({ onClose, onReadChange }: NoticeDrawerProps) { + const [items, setItems] = useState([]); + const [total, setTotal] = useState(0); + const [loading, setLoading] = useState(true); + const [unreadOnly, setUnreadOnly] = useState(false); + const [expandedId, setExpandedId] = useState(null); + const [markingAll, setMarkingAll] = useState(false); + const drawerRef = useRef(null); + + // 加载消息列表 + const load = (unread: boolean) => { + setLoading(true); + fetchNotices({ unreadOnly: unread, page: 1, perPage: 20 }) + .then((r) => { + setItems(r.items); + setTotal(r.total); + }) + .catch(() => { + setItems([]); + setTotal(0); + }) + .finally(() => setLoading(false)); + }; + + useEffect(() => { + load(unreadOnly); + }, [unreadOnly]); + + // 点击抽屉外部关闭 + useEffect(() => { + const handler = (e: MouseEvent) => { + if (drawerRef.current && !drawerRef.current.contains(e.target as Node)) { + onClose(); + } + }; + document.addEventListener('mousedown', handler); + return () => document.removeEventListener('mousedown', handler); + }, [onClose]); + + // 单条置已读 + const handleRead = async (item: NoticeItem) => { + // 展开/收起内容 + setExpandedId((prev) => (prev === item.id ? null : item.id)); + if (item.isread === 0) { + try { + await markNoticeRead(item.id); + setItems((prev) => + prev.map((i) => (i.id === item.id ? { ...i, isread: 1 } : i)), + ); + onReadChange(); + } catch { + // 静默失败,不影响 UI + } + } + }; + + // 全部已读 + const handleReadAll = async () => { + setMarkingAll(true); + try { + await markAllNoticesRead(); + setItems((prev) => prev.map((i) => ({ ...i, isread: 1 }))); + onReadChange(); + } catch { + // 静默失败 + } finally { + setMarkingAll(false); + } + }; + + const unreadCount = items.filter((i) => i.isread === 0).length; + + return ( + <> + {/* 半透明遮罩 */} +
+ + {/* 抽屉主体 */} +
+ {/* 头部 */} +
+
+ + 消息中心 + {unreadCount > 0 && ( + + {unreadCount} + + )} +
+
+ {unreadCount > 0 && ( + + )} + +
+
+ + {/* 过滤标签 */} +
+ {(['全部', '仅未读'] as const).map((label, i) => { + const active = i === 0 ? !unreadOnly : unreadOnly; + return ( + + ); + })} + + 共 {total} 条 + +
+ + {/* 消息列表 */} +
+ {loading && ( +
加载中…
+ )} + + {!loading && items.length === 0 && ( +
+ + {unreadOnly ? '没有未读消息' : '暂无消息'} +
+ )} + + {!loading && items.map((item) => { + const isExpanded = expandedId === item.id; + return ( +
handleRead(item)} + style={{ + padding: '12px 16px', + borderBottom: '1px solid var(--line)', + cursor: 'pointer', + background: item.isread === 0 ? 'var(--brand-softer)' : 'var(--surface)', + transition: 'background .1s', + }} + onMouseEnter={(e) => + ((e.currentTarget as HTMLDivElement).style.background = + item.isread === 0 ? 'var(--brand-soft)' : 'var(--surface-2)') + } + onMouseLeave={(e) => + ((e.currentTarget as HTMLDivElement).style.background = + item.isread === 0 ? 'var(--brand-softer)' : 'var(--surface)') + } + > +
+ {/* 未读蓝点 */} + +
+
+ {item.title} +
+ {isExpanded && item.summary && ( +
+ {item.summary} +
+ )} +
+ {item.type != null && ( + + {item.type} + + )} + {fmtTime(item.createtime)} +
+
+
+
+ ); + })} +
+
+ + ); +} diff --git a/src/shell/Topbar.tsx b/src/shell/Topbar.tsx index 7b05cb6..2be7bf2 100644 --- a/src/shell/Topbar.tsx +++ b/src/shell/Topbar.tsx @@ -9,7 +9,9 @@ interface TopbarProps { leaves: MenuLeaf[]; profile: UserProfile | null; todoBadge?: number; + noticeBadge?: number; onOpenTodo: () => void; + onOpenNotice: () => void; onOpenTemplate: (templateId: string) => void; onOpenSettings: () => void; } @@ -18,7 +20,9 @@ export function Topbar({ leaves, profile, todoBadge, + noticeBadge, onOpenTodo, + onOpenNotice, onOpenTemplate, onOpenSettings, }: TopbarProps) { @@ -51,6 +55,14 @@ export function Topbar({ ) : null} + {/* 消息铃铛(F2-11) */} + + {/* 设置 */}