refactor(announcements,messaging,notifications): V1+V2 审计重构 — i18n 命名空间独立 + 通知标题 i18n 化 + 服务端过滤 + 编排下沉 + 表单错误展示 + 架构图同步

V1 改进(已完成):
- P0-4/P1-4/P1-5: 通知组件和 CRUD Action 从 messaging 迁移至 notifications 模块
- P1-5: 新增 getMessagesPageData / getAdminAnnouncementsPageData 编排函数
- P1-6: announcements schema 添加 superRefine 条件校验
- P1-7: 新增 useMessageSearch hook(防抖 + 请求竞态取消)+ 客户端分页 UI
- P1-9: deleteMessage 事务化
- P2-11: 全模块 trackEvent 埋点
- 全模块 i18n 接入 + Error Boundary + a11y 改进

V2 改进(本次完成):
- V2-P0-1: 通知 i18n 命名空间独立(notifications.json),useTranslations 从 "messages" 切换到 "notifications"
- V2-P0-2: 公告/消息通知标题 i18n 化,Server Action 中使用 getTranslations 生成通知标题
- V2-P1-1: AnnouncementList 纯服务端过滤,移除客户端 useState/useMemo
- V2-P1-2: MessageList 客户端过滤仅在初始数据时执行,搜索结果由服务端按 tab 过滤
- V2-P1-3: 消息详情页编排下沉,新增 getMessageDetailPageData 编排函数
- V2-P1-4: 表单服务端校验错误展示(fieldErrors + aria-invalid)
- V2-P2-1: 轮询间隔常量化(POLL_INTERVAL_MS)
- V2-P2-2: 架构图同步(004 + 005)
This commit is contained in:
SpecialX
2026-06-22 18:43:12 +08:00
parent 6d7838a210
commit 1fe30984b6
29 changed files with 1252 additions and 351 deletions

View File

@@ -636,39 +636,50 @@ src/auth.ts ──▶ import { ... } from "@/shared/lib/permissions"
**职责**:教材与知识体系管理(教材/章节树形结构、知识点 CRUD、Markdown 内容编辑、知识图谱)。 **职责**:教材与知识体系管理(教材/章节树形结构、知识点 CRUD、Markdown 内容编辑、知识图谱)。
**导出函数** **导出函数**
- Actions10 个,均为写操作;读操作由 RSC 页面直接调用 data-access`createTextbookAction` / `updateTextbookAction` / `deleteTextbookAction` / `createChapterAction` / `updateChapterContentAction` / `deleteChapterAction` / `reorderChaptersAction` / `createKnowledgePointAction` / `updateKnowledgePointAction` / `deleteKnowledgePointAction` - Actions11 个,均为写操作;读操作由 RSC 页面直接调用 data-access`createTextbookAction` / `updateTextbookAction` / `deleteTextbookAction` / `createChapterAction` / `updateChapterContentAction` / `deleteChapterAction` / `reorderChaptersAction` / `createKnowledgePointAction` / `updateKnowledgePointAction` / `deleteKnowledgePointAction` / `getKnowledgePointsByChapterAction`
- Data-access`getTextbooks` / `getTextbookById` / `getChaptersByTextbookId` / `getKnowledgePointsByChapterId` / `getKnowledgePointsByTextbookId` / `createTextbook` / `updateTextbook` / `deleteTextbook` / `createChapter` / `updateChapterContent` / `deleteChapter` / `createKnowledgePoint` / `updateKnowledgePoint` / `deleteKnowledgePoint` / `reorderChapters` / `getTextbooksDashboardStats` / `getKnowledgePointOptions`(跨模块接口,供 questions 调用) - Data-access`getTextbooks` / `getTextbookById` / `getChaptersByTextbookId` / `getKnowledgePointsByChapterId` / `getKnowledgePointsByTextbookId` / `createTextbook` / `updateTextbook` / `deleteTextbook` / `createChapter` / `updateChapterContent` / `deleteChapter` / `createKnowledgePoint` / `updateKnowledgePoint` / `deleteKnowledgePoint` / `reorderChapters` / `getTextbooksDashboardStats` / `getKnowledgePointOptions`(跨模块接口,供 questions 调用)/ `getTextbooksWithScope`P1-1 新增:按数据范围获取教材列表,学生端强制按年级过滤)/ `verifyChapterBelongsToTextbook`P0-4 新增:资源归属校验)/ `verifyKnowledgePointBelongsToTextbook`P0-4 新增:资源归属校验)/ `getSubjectLabelKey` / `getGradeLabelKey`i18n 标签键)
- Constants✅ 新增):`SUBJECTS` / `GRADES` / `SUBJECT_COLORS` / `getSubjectColor` / `getSubjectLabelKey` / `getGradeLabelKey`
- Utils✅ 新增,纯函数 + 单测):`sortChapters` / `buildChapterTree` / `buildChapterIndex` / `findChapterParent` / `filterKnowledgePointsByChapter` / `normalizeOptional` / `highlightKnowledgePoints`
- Graph-layout✅ 新增,纯函数 + 单测):`computeGraphLayout`
- Analytics✅ 新增):`TextbookAnalytics` / `TextbookAnalyticsProvider` / `useTextbookAnalytics`
**依赖关系** **依赖关系**
- 依赖:`shared/*``@/auth` - 依赖:`shared/*``@/auth`
- 被依赖:`questions`(✅ P1-1 已修复:通过 textbooks data-access`exams`(通过类型)、`dashboard`(通过 data-accessP0-4 已修复) - 被依赖:`questions`(✅ P1-1 已修复:通过 textbooks data-access`exams`(通过类型)、`dashboard`(通过 data-accessP0-4 已修复)
- ⚠️ UI 层跨模块依赖:`textbooks/components/knowledge-point-dialogs.tsx` 直接 import `questions/components/create-question-dialog`P0 待解耦,详见 [textbooks-audit-report.md](audit/textbooks-audit-report.md) - UI 层跨模块依赖已解耦`textbooks/components/knowledge-point-dialogs.tsx` 不再直接 import questions 模块,改为通过 render prop 注入创建题目入口
**已知问题** **已知问题**
- ✅ 无跨模块 DB 访问data-access 层) - ✅ 无跨模块 DB 访问data-access 层)
- ✅ actions 层编排模式标杆(权限校验 → 调用 data-access → revalidatePath - ✅ actions 层编排模式标杆(权限校验 → 调用 data-access → revalidatePath
- ✅ data-access 层职责单一 - ✅ data-access 层职责单一
- ✅ P2 已修复:`data-access.ts``byId.get(pid)!.children.push` 非空断言清理为安全守卫;`or(...)!` 非空断言清理为条件 push - ✅ P2 已修复:`data-access.ts``byId.get(pid)!.children.push` 非空断言清理为安全守卫;`or(...)!` 非空断言清理为条件 push
- ⚠️ P0 跨模块 UI 依赖:`knowledge-point-dialogs.tsx` 直接 import questions 模块组件 - P0 跨模块 UI 依赖已修复`knowledge-point-dialogs.tsx` 通过 render prop 解耦,不再直接 import questions 模块
- ⚠️ P0 前端权限硬编码`canEdit={true}` 按路由写死,未`usePermission().hasPermission()` - P0 前端权限硬编码已修复:改`usePermission().hasPermission()`
- ⚠️ P0 全模块零 i18n中英文文案硬编码接入 next-intl - P0 i18n 已基本接入:`chapter-sidebar-list.tsx` / `actions.ts` / `section-error-boundary.tsx`(默认值改英文)均已接入 next-intl
- ⚠️ P1 Server Action 未校验资源归属chapterId 是否属于 textbookId - P1 Server Action 资源归属校验已修复:新增 `verifyChapterBelongsToTextbook` / `verifyKnowledgePointBelongsToTextbook`
- ⚠️ P1 data-access 数据范围过滤学生端按年级过滤 - P1 data-access 数据范围过滤已修复:新增 `getTextbooksWithScope`学生端强制按年级过滤
- ⚠️ P1 Error Boundary(无 error.tsx - P1 Error Boundary 已补齐:新增 `section-error-boundary.tsx`
- ⚠️ P1 知识点列表/弹窗存在重复实现knowledge-point-panel.tsx 无调用方) - P1 知识点列表/弹窗重复实现已清理:移除无调用方的 `knowledge-point-panel.tsx`
- ⚠️ P1 学科/年级选项硬编码三处且彼此不一致 - P1 学科/年级选项统一:抽取到 `constants.ts``SUBJECTS` / `GRADES` / `SUBJECT_COLORS`
- ⚠️ P1 纯逻辑导出,零单测 - P1 纯逻辑导出并补单测:新增 `utils.ts` / `graph-layout.ts` 及对应 `.test.ts`
- ⚠️ i18n 覆盖率约 95%`chapter-sidebar-list` 已接入,`actions.ts` 已接入,`section-error-boundary` 默认值已改英文)
- ⚠️ 类型断言残留 3 处 `as string`
- ⚠️ P2 图谱方向键导航未实现
**文件清单** **文件清单**
| 文件 | 行数 | 职责 | | 文件 | 行数 | 职责 |
|------|------|------| |------|------|------|
| `actions.ts` | 317 | 10 个 Server Action写操作 | | `actions.ts` | 377 | 11 个 Server Action写操作,含 Zod 校验 + 资源归属校验 |
| `data-access.ts` | 514 | 教材/章节/知识点 CRUD + 跨模块查询接口 | | `data-access.ts` | 619 | 教材/章节/知识点 CRUD + 跨模块查询接口 + 资源归属校验 + 数据范围过滤 |
| `types.ts` | 45 | 类型定义 | | `types.ts` | 45 | 类型定义 |
| `schema.ts` | 64 | Zod 校验 | | `schema.ts` | 64 | Zod 校验 |
| `constants.ts` | 91 | 学科/年级常量与颜色映射(✅ 新增) |
| `utils.ts` | 181 | 章节树构建/排序/查找等纯函数(✅ 新增,含单测) |
| `graph-layout.ts` | 141 | 知识图谱布局计算纯函数(✅ 新增,含单测) |
| `analytics.tsx` | 43 | 教材分析 Context/Provider/Hook✅ 新增) |
| `hooks/use-knowledge-point-actions.ts` | 121 | 知识点操作 Hook | | `hooks/use-knowledge-point-actions.ts` | 121 | 知识点操作 Hook |
| `hooks/use-text-selection.ts` | 57 | 文本选区捕获 Hook | | `hooks/use-text-selection.ts` | 57 | 文本选区捕获 Hook |
| `components/*` | 11 文件 | 教材编辑/知识图谱组件 | | `components/*` | 12 文件 | 教材编辑/知识图谱组件(新增 `section-error-boundary.tsx` |
--- ---
@@ -775,6 +786,7 @@ src/auth.ts ──▶ import { ... } from "@/shared/lib/permissions"
- ⚠️ P0-22026-06-22 审计发现):年级 CRUD 逻辑与 `grade-management` 模块重复定义,两套实现并存 - ⚠️ P0-22026-06-22 审计发现):年级 CRUD 逻辑与 `grade-management` 模块重复定义,两套实现并存
- ⚠️ P0-52026-06-22 审计发现):`school/components/*` 4 个组件均缺少 i18n`schools-view.tsx` 已修复,其余 3 个待修复);缺少 Error Boundary / Skeleton - ⚠️ P0-52026-06-22 审计发现):`school/components/*` 4 个组件均缺少 i18n`schools-view.tsx` 已修复,其余 3 个待修复);缺少 Error Boundary / Skeleton
- ✅ P0-5 部分修复2026-06-22新增 `school.json` i18n 文件,`schools-view.tsx` 接入 `useTranslations("school")` - ✅ P0-5 部分修复2026-06-22新增 `school.json` i18n 文件,`schools-view.tsx` 接入 `useTranslations("school")`
- ✅ P1-3 修复2026-06-22新增 school-error-boundary.tsxclass component Error Boundary + i18n + router.refresh 重试)和 school-skeleton.tsxSchoolListSkeleton 表格骨架 + SchoolCardSkeleton 卡片骨架4 个页面schools/grades/departments/academic-year均已包裹 SchoolErrorBoundaryschool.json 补充 errors.boundary.* 翻译键
**文件清单** **文件清单**
| 文件 | 行数 | 职责 | | 文件 | 行数 | 职责 |
@@ -783,6 +795,8 @@ src/auth.ts ──▶ import { ... } from "@/shared/lib/permissions"
| `data-access.ts` | 504 | 只读查询 + 12 个写操作 + 跨模块查询接口(`isGradeHead`/`isGradeManager`/`findGradeIdByHeadAndName`/`getGradeNameById`/`getSubjectNameById` | | `data-access.ts` | 504 | 只读查询 + 12 个写操作 + 跨模块查询接口(`isGradeHead`/`isGradeManager`/`findGradeIdByHeadAndName`/`getGradeNameById`/`getSubjectNameById` |
| `schema.ts` | 51 | Zod 校验 | | `schema.ts` | 51 | Zod 校验 |
| `types.ts` | 96 | 类型定义(含 Insert/Update 入参类型) | | `types.ts` | 96 | 类型定义(含 Insert/Update 入参类型) |
| components/school-error-boundary.tsx | 72 | 共享 Error Boundaryclass component + i18n + router.refresh 重试) |
| components/school-skeleton.tsx | 69 | 共享骨架屏SchoolListSkeleton 表格骨架 + SchoolCardSkeleton 卡片骨架) |
--- ---
@@ -1000,7 +1014,7 @@ src/auth.ts ──▶ import { ... } from "@/shared/lib/permissions"
**导出函数** **导出函数**
- Actions`sendMessageAction` / `markMessageAsReadAction` / `deleteMessageAction` / `getMessagesAction` / `getMessageDetailAction` / `getRecipientsAction` / `getUnreadMessageCountAction` / `getNotificationPreferencesAction` / `updateNotificationPreferencesAction`(✅ P1-4 已修复:通知 CRUD Action 已迁移至 notifications 模块messaging 仅保留私信和通知偏好 Action - Actions`sendMessageAction` / `markMessageAsReadAction` / `deleteMessageAction` / `getMessagesAction` / `getMessageDetailAction` / `getRecipientsAction` / `getUnreadMessageCountAction` / `getNotificationPreferencesAction` / `updateNotificationPreferencesAction`(✅ P1-4 已修复:通知 CRUD Action 已迁移至 notifications 模块messaging 仅保留私信和通知偏好 Action
- Data-access`getMessages` / `getMessageById` / `getMessageThread` / `createMessage` / `markMessageAsRead` / `deleteMessage` / `getUnreadMessageCount` / `getRecipients`(按 DataScope 过滤可发送对象class_taught 教师→学生、grade_managed 年级管理员→教师/学生、all 管理员、class_members 学生→自己班级的任课教师/班主任、children 家长→孩子的班主任/任课教师;通过 classes data-access.getTeacherIdsByClassIds/getStudentActiveClassId 获取班级教师 ID/ `getMessagesPageData`(✅ P1-5 新增:消息首页编排函数,一次性获取消息列表和通知列表) - Data-access`getMessages` / `getMessageById` / `getMessageThread` / `createMessage` / `markMessageAsRead` / `deleteMessage` / `getUnreadMessageCount` / `getRecipients`(按 DataScope 过滤可发送对象class_taught 教师→学生、grade_managed 年级管理员→教师/学生、all 管理员、class_members 学生→自己班级的任课教师/班主任、children 家长→孩子的班主任/任课教师;通过 classes data-access.getTeacherIdsByClassIds/getStudentActiveClassId 获取班级教师 ID/ `getMessagesPageData`(✅ P1-5 新增:消息首页编排函数,一次性获取消息列表和通知列表)/ `getMessageDetailPageData`(✅ V2-P1-3 新增:消息详情页编排函数,获取详情并自动标记已读)
- Hooks`useMessageSearch`(✅ P1-7 新增:消息搜索 hook含防抖和请求竞态取消 - Hooks`useMessageSearch`(✅ P1-7 新增:消息搜索 hook含防抖和请求竞态取消
- Notification-preferences~~re-export shim实际逻辑在 `notifications/preferences.ts`~~ ✅ P0-b 已修复:`notification-preferences.ts` 文件已删除(通知模块去重),消费方改为直接从 `@/modules/notifications/preferences` 导入 `getNotificationPreferences` / `upsertNotificationPreferences` - Notification-preferences~~re-export shim实际逻辑在 `notifications/preferences.ts`~~ ✅ P0-b 已修复:`notification-preferences.ts` 文件已删除(通知模块去重),消费方改为直接从 `@/modules/notifications/preferences` 导入 `getNotificationPreferences` / `upsertNotificationPreferences`
@@ -1025,12 +1039,17 @@ src/auth.ts ──▶ import { ... } from "@/shared/lib/permissions"
- ✅ P1-7 已修复:~~消息列表客户端 `useEffect` + `setTimeout` 防抖搜索未取消已发出的请求~~ 搜索逻辑抽离为 `useMessageSearch` hook含防抖 + 请求竞态取消);~~无分页 UI~~ 新增客户端分页 UIPAGE_SIZE=20ChevronLeft/ChevronRight 按钮) - ✅ P1-7 已修复:~~消息列表客户端 `useEffect` + `setTimeout` 防抖搜索未取消已发出的请求~~ 搜索逻辑抽离为 `useMessageSearch` hook含防抖 + 请求竞态取消);~~无分页 UI~~ 新增客户端分页 UIPAGE_SIZE=20ChevronLeft/ChevronRight 按钮)
- ✅ P1-9 已修复:~~`deleteMessage` 两个独立 UPDATE 无事务~~ 改为 `db.transaction` 包裹 senderDeletedAt 和 receiverDeletedAt 更新,保证原子性 - ✅ P1-9 已修复:~~`deleteMessage` 两个独立 UPDATE 无事务~~ 改为 `db.transaction` 包裹 senderDeletedAt 和 receiverDeletedAt 更新,保证原子性
- ✅ P2-11 已修复:~~发送/删除消息无埋点~~ `sendMessageAction` / `markMessageAsReadAction` / `deleteMessageAction` 新增 `trackEvent` 埋点message.sent / message.marked_read / message.deleted - ✅ P2-11 已修复:~~发送/删除消息无埋点~~ `sendMessageAction` / `markMessageAsReadAction` / `deleteMessageAction` 新增 `trackEvent` 埋点message.sent / message.marked_read / message.deleted
- ✅ V2-P0-2 已修复:~~通知标题硬编码~~ `sendMessageAction` 通过 `getTranslations('messages')` 生成 i18n 通知标题(`notification.messageTitle` / `messageTitleNoSubject`
- ✅ V2-P1-2 已修复:~~MessageList 客户端过滤冗余~~ 客户端过滤仅在初始数据type=all时执行搜索结果已由服务端按 tab 过滤
- ✅ V2-P1-3 已修复:~~消息详情页分散编排~~ 新增 `getMessageDetailPageData` 编排函数,替代 page.tsx 中 `after()` + `getMessageById` + `markMessageAsRead` 的分散编排
- ✅ V2-P1-4 已修复:~~表单无服务端校验错误展示~~ `message-compose.tsx` 新增 `fieldErrors` 状态 + `aria-invalid` 字段级错误展示receiverId/subject/content
- ✅ V2-P2-1 已修复:~~轮询间隔魔法数字~~ `unread-message-badge.tsx` 轮询间隔提取为 `POLL_INTERVAL_MS` 常量60_000ms
**文件清单** **文件清单**
| 文件 | 行数 | 职责 | | 文件 | 行数 | 职责 |
|------|------|------| |------|------|------|
| `actions.ts` | ~260 | 7 个私信 Server Action + 2 个通知偏好 Action✅ P1-4通知 CRUD Action 已迁移至 notifications 模块) | | `actions.ts` | ~280 | 7 个私信 Server Action + 2 个通知偏好 Action✅ P1-4通知 CRUD Action 已迁移至 notifications 模块;✅ V2-P0-2通知标题 i18n 化 |
| `data-access.ts` | ~270 | 私信 CRUD + `getMessagesPageData` 编排函数(✅ P1-5 新增) | | `data-access.ts` | ~290 | 私信 CRUD + `getMessagesPageData` 编排函数(✅ P1-5 新增)+ `getMessageDetailPageData` 编排函数(✅ V2-P1-3 新增) |
| `schema.ts` | 44 | 私信发送校验 + messageId 校验 + 通知偏好更新校验 | | `schema.ts` | 44 | 私信发送校验 + messageId 校验 + 通知偏好更新校验 |
| `types.ts` | 52 | 私信类型 + re-export 通知类型(向后兼容) | | `types.ts` | 52 | 私信类型 + re-export 通知类型(向后兼容) |
| `hooks/use-message-search.ts` | ~60 | ✅ P1-7 新增:消息搜索 hook防抖 + 请求竞态取消) | | `hooks/use-message-search.ts` | ~60 | ✅ P1-7 新增:消息搜索 hook防抖 + 请求竞态取消) |
@@ -1038,14 +1057,14 @@ src/auth.ts ──▶ import { ... } from "@/shared/lib/permissions"
**组件清单** **组件清单**
| 组件 | 职责 | | 组件 | 职责 |
|------|------| |------|------|
| `components/message-list.tsx` | 消息列表(✅ P1-7使用 `useMessageSearch` hook + 客户端分页 UIPAGE_SIZE=20 | | `components/message-list.tsx` | 消息列表(✅ P1-7使用 `useMessageSearch` hook + 客户端分页 UIPAGE_SIZE=20;✅ V2-P1-2客户端过滤仅在初始数据时执行 |
| `components/message-detail.tsx` | 消息详情(含回复) | | `components/message-detail.tsx` | 消息详情(含回复) |
| `components/message-compose.tsx` | 撰写新消息 | | `components/message-compose.tsx` | 撰写新消息(✅ V2-P1-4fieldErrors + aria-invalid 字段级错误展示) |
| `components/unread-message-badge.tsx` | 未读消息计数徽章(侧边栏,每 60 秒轮询 `getUnreadMessageCountAction` | | `components/unread-message-badge.tsx` | 未读消息计数徽章(侧边栏,每 60 秒轮询 `getUnreadMessageCountAction`;✅ V2-P2-1POLL_INTERVAL_MS 常量 |
**客户端行为** **客户端行为**
- `message-list.tsx`:客户端调用 `getMessagesAction` 搜索消息useMessageSearch hook400ms 防抖,请求竞态取消) - `message-list.tsx`:客户端调用 `getMessagesAction` 搜索消息useMessageSearch hook400ms 防抖,请求竞态取消)V2-P1-2 优化客户端过滤仅在初始数据type=all时执行
- `unread-message-badge.tsx`:每 60 秒轮询 `getUnreadMessageCountAction` 刷新未读计数 - `unread-message-badge.tsx`:每 `POLL_INTERVAL_MS`60_000ms轮询 `getUnreadMessageCountAction` 刷新未读计数
--- ---
@@ -1071,6 +1090,8 @@ src/auth.ts ──▶ import { ... } from "@/shared/lib/permissions"
- ✅ P1-1 已修复:~~`sendClassNotificationAction` 直查 `classes`/`classEnrollments`~~ 改为调用 `classes/data-access.getClassExists` / `getStudentIdsByClassId` - ✅ P1-1 已修复:~~`sendClassNotificationAction` 直查 `classes`/`classEnrollments`~~ 改为调用 `classes/data-access.getClassExists` / `getStudentIdsByClassId`
- ✅ P1-4 已修复:~~通知 UI 组件放在 messaging/components 下,直接 import notifications 类型和 messaging/actions~~ `notification-list.tsx``notification-dropdown.tsx` 已迁移至 `notifications/components/`,通知 CRUD Action 已从 messaging 迁移至 `notifications/actions.ts`,消除 UI 层跨模块耦合 - ✅ P1-4 已修复:~~通知 UI 组件放在 messaging/components 下,直接 import notifications 类型和 messaging/actions~~ `notification-list.tsx``notification-dropdown.tsx` 已迁移至 `notifications/components/`,通知 CRUD Action 已从 messaging 迁移至 `notifications/actions.ts`,消除 UI 层跨模块耦合
- ✅ P2-11 已修复:~~通知标记已读无埋点~~ `markNotificationAsReadAction` / `markAllNotificationsAsReadAction` 新增 `trackEvent` 埋点notification.marked_read / notification.marked_all_read - ✅ P2-11 已修复:~~通知标记已读无埋点~~ `markNotificationAsReadAction` / `markAllNotificationsAsReadAction` 新增 `trackEvent` 埋点notification.marked_read / notification.marked_all_read
- ✅ V2-P0-1 已修复:~~通知 i18n 键混在 messages.json 中~~ 新增独立的 `notifications.json` 命名空间zh-CN/en通知组件 `useTranslations``"messages"` 切换到 `"notifications"``src/i18n/request.ts` 新增 notifications 命名空间加载
- ✅ V2-P2-1 已修复:~~轮询间隔魔法数字~~ `notification-dropdown.tsx` 轮询间隔提取为 `POLL_INTERVAL_MS` 常量30_000ms
- ⚠️ P1发送日志仅 console`notification_logs` - ⚠️ P1发送日志仅 console`notification_logs`
- ✅ 渠道抽象优秀(接口 + 工厂 + Mock 实现) - ✅ 渠道抽象优秀(接口 + 工厂 + Mock 实现)
@@ -1090,11 +1111,11 @@ src/auth.ts ──▶ import { ... } from "@/shared/lib/permissions"
**组件清单** **组件清单**
| 组件 | 职责 | | 组件 | 职责 |
|------|------| |------|------|
| `components/notification-list.tsx` | 通知列表(消息页底部,展示所有通知,支持标记已读) | | `components/notification-list.tsx` | 通知列表(消息页底部,展示所有通知,支持标记已读;✅ V2-P0-1useTranslations 命名空间从 "messages" 切换到 "notifications" |
| `components/notification-dropdown.tsx` | 通知下拉菜单(站点头部,每 30 秒轮询 `getNotificationsAction` + `getUnreadNotificationCountAction` | | `components/notification-dropdown.tsx` | 通知下拉菜单(站点头部,每 30 秒轮询 `getNotificationsAction` + `getUnreadNotificationCountAction`;✅ V2-P0-1useTranslations 命名空间切换;✅ V2-P2-1POLL_INTERVAL_MS 常量 |
**客户端行为** **客户端行为**
- `notification-dropdown.tsx`:每 30 秒轮询 `getNotificationsAction`pageSize=10`getUnreadNotificationCountAction` 刷新通知和未读计数 - `notification-dropdown.tsx`:每 `POLL_INTERVAL_MS`30_000ms轮询 `getNotificationsAction`pageSize=10`getUnreadNotificationCountAction` 刷新通知和未读计数
--- ---
@@ -1151,6 +1172,9 @@ src/auth.ts ──▶ import { ... } from "@/shared/lib/permissions"
- ✅ P1-5 已修复:~~页面层 `Promise.all` 编排 announcements/school/classes 三个模块的 data-access~~ 新增 `getAdminAnnouncementsPageData``getEditAnnouncementPageData` 编排函数,页面层仅调用单一函数 - ✅ P1-5 已修复:~~页面层 `Promise.all` 编排 announcements/school/classes 三个模块的 data-access~~ 新增 `getAdminAnnouncementsPageData``getEditAnnouncementPageData` 编排函数,页面层仅调用单一函数
- ✅ P1-6 已修复:~~`targetGradeId` / `targetClassId` 为 optional未根据 `type` 做条件必填校验~~ `CreateAnnouncementSchema``UpdateAnnouncementSchema` 添加 `superRefine(refineAudience)`,年级公告强制 `targetGradeId`,班级公告强制 `targetClassId` - ✅ P1-6 已修复:~~`targetGradeId` / `targetClassId` 为 optional未根据 `type` 做条件必填校验~~ `CreateAnnouncementSchema``UpdateAnnouncementSchema` 添加 `superRefine(refineAudience)`,年级公告强制 `targetGradeId`,班级公告强制 `targetClassId`
- ✅ P2-11 已修复:~~发布/归档/删除公告无埋点~~ `createAnnouncementAction` / `updateAnnouncementAction` / `deleteAnnouncementAction` / `publishAnnouncementAction` / `archiveAnnouncementAction` 新增 `trackEvent` 埋点announcement.created / announcement.updated / announcement.published / announcement.deleted / announcement.archived - ✅ P2-11 已修复:~~发布/归档/删除公告无埋点~~ `createAnnouncementAction` / `updateAnnouncementAction` / `deleteAnnouncementAction` / `publishAnnouncementAction` / `archiveAnnouncementAction` 新增 `trackEvent` 埋点announcement.created / announcement.updated / announcement.published / announcement.deleted / announcement.archived
- ✅ V2-P0-2 已修复:~~通知标题硬编码~~ `createAnnouncementAction` / `updateAnnouncementAction` / `publishAnnouncementAction` 通过 `getTranslations('announcements')` 生成 i18n 通知标题(`notification.publishedTitle` / `publishedContent`
- ✅ V2-P1-1 已修复:~~AnnouncementList 客户端 useState/useMemo 过滤~~ 改为纯服务端过滤模式Select 切换仅更新 URL `?status=` 触发 RSC 重新渲染
- ✅ V2-P1-4 已修复:~~表单无服务端校验错误展示~~ `announcement-form.tsx` 新增 `fieldErrors` 状态 + `aria-invalid` 字段级错误展示title/content/targetGradeId/targetClassId
**文件清单** **文件清单**
| 文件 | 行数 | 职责 | | 文件 | 行数 | 职责 |
@@ -1163,10 +1187,10 @@ src/auth.ts ──▶ import { ... } from "@/shared/lib/permissions"
**组件清单** **组件清单**
| 组件 | 职责 | | 组件 | 职责 |
|------|------| |------|------|
| `components/announcement-list.tsx` | 公告列表(用户端,支持状态筛选) | | `components/announcement-list.tsx` | 公告列表(用户端,支持状态筛选;✅ V2-P1-1纯服务端过滤Select 切换更新 URL ?status= 触发 RSC 重新渲染 |
| `components/announcement-card.tsx` | 公告卡片(列表项) | | `components/announcement-card.tsx` | 公告卡片(列表项) |
| `components/announcement-detail.tsx` | 公告详情(只读) | | `components/announcement-detail.tsx` | 公告详情(只读) |
| `components/announcement-form.tsx` | 公告表单(创建/编辑,✅ P1-6条件校验由 schema superRefine 保证) | | `components/announcement-form.tsx` | 公告表单(创建/编辑,✅ P1-6条件校验由 schema superRefine 保证;✅ V2-P1-4fieldErrors + aria-invalid 字段级错误展示 |
| `components/admin-announcements-view.tsx` | 管理端公告视图(列表 + 筛选) | | `components/admin-announcements-view.tsx` | 管理端公告视图(列表 + 筛选) |
--- ---
@@ -1661,39 +1685,39 @@ src/auth.ts ──▶ import { ... } from "@/shared/lib/permissions"
| `lib/node-summary.ts` | **纯函数**getNodeSummary接受翻译函数注入支持 i18n+ NODE_COLORS + getNodeColor | | `lib/node-summary.ts` | **纯函数**getNodeSummary接受翻译函数注入支持 i18n+ NODE_COLORS + getNodeColor |
| `lib/rf-mappers.ts` | **纯函数**toRfNodes/toRfEdges/fromRfEdgesLessonPlanNode/Edge ↔ React Flow Node/Edge 映射) | | `lib/rf-mappers.ts` | **纯函数**toRfNodes/toRfEdges/fromRfEdgesLessonPlanNode/Edge ↔ React Flow Node/Edge 映射) |
| `config/block-registry.tsx` | **配置驱动**BLOCK_REGISTRY 注册表 + getBlockComponent/isRichTextBlocknode-edit-panel 通过配置渲染 Block | | `config/block-registry.tsx` | **配置驱动**BLOCK_REGISTRY 注册表 + getBlockComponent/isRichTextBlocknode-edit-panel 通过配置渲染 Block |
| `providers/lesson-plan-provider.tsx` | **Provider + ContextP1-5/P1-7/P2-4**LessonPlanProvider 注入数据服务/角色配置/埋点;定义 LessonPlanDataService 接口、4 个角色配置TEACHER/ADMIN/STUDENT/PARENT、ROLE_CONFIGS 注册表、LessonPlanTracker 接口 + noopTrackerhooksuseLessonPlanContextSafe返回 null 不抛错)/useLessonPlanContext/useRoleConfig/useLessonPlanService/useLessonPlanTracker | | `providers/lesson-plan-provider.tsx` | **Provider + ContextP1-5/P1-7/P2-4/V2-6**LessonPlanProvider 注入数据服务/角色配置/埋点;定义 LessonPlanDataService 接口、4 个角色配置TEACHER/ADMIN/STUDENT/PARENT、ROLE_CONFIGS 注册表、LessonPlanTracker 接口 + noopTrackerhooksuseLessonPlanContextSafe返回 null 不抛错)/useLessonPlanContext/useRoleConfig/useLessonPlanService/useLessonPlanTracker/useLessonPlanTrackerSafeV2-6 新增,返回 noopTracker 不抛错) |
| `services/default-data-service.ts` | **默认数据服务实现**createDefaultDataService() 包装 Server Actions 为 LessonPlanDataService 实现,测试可替换为 mock | | `services/default-data-service.ts` | **默认数据服务实现**createDefaultDataService() 包装 Server Actions 为 LessonPlanDataService 实现,测试可替换为 mock |
| `data-access.ts` | 课案 CRUD + 模板查询migrateV1ToV2/normalizeDocument/buildInitialContent 从 lib/ 导入并 re-export 保持向后兼容buildScopeCondition 按 scope 类型精确过滤 P0-3 | | `data-access.ts` | 课案 CRUD + 模板查询migrateV1ToV2/normalizeDocument/buildInitialContent 从 lib/ 导入并 re-export 保持向后兼容buildScopeCondition 按 scope 类型精确过滤 P0-3V2-1抛出 `LessonPlanDataError` 错误码V2-3mapRowToLessonPlan/mapRowToListItem/mapRowToTemplate 显式映射 + isLessonPlanStatus/isTemplateType/isTemplateScope 类型守卫 |
| `data-access-versions.ts` | 版本管理(创建/查询/回滚/清理) | | `data-access-versions.ts` | 版本管理(创建/查询/回滚/清理V2-3mapRowToVersion 显式映射 |
| `data-access-templates.ts` | 个人模板 CRUD | | `data-access-templates.ts` | 个人模板 CRUDV2-3mapRowToTemplate 显式映射 + 类型守卫) |
| `data-access-knowledge.ts` | 按知识点/题目反查课案 | | `data-access-knowledge.ts` | 按知识点/题目反查课案V2-3显式字段映射替代 `as unknown as` |
| `actions.ts` | 课案 CRUD/版本/模板 Server Actions | | `actions.ts` | 课案 CRUD/版本/模板 Server ActionsV2-1getTranslations i18n + 错误码捕获V2-2createLessonPlanAction 传入 translateTitle 翻译 SYSTEM_TEMPLATES |
| `actions-publish.ts` | 发布作业 Server Action | | `actions-publish.ts` | 发布作业 Server ActionV2-1getTranslations i18n + PUBLISH_ERROR_KEY_MAP 错误码映射) |
| `actions-ai.ts` | AI 知识点建议 Server Action | | `actions-ai.ts` | AI 知识点建议 Server ActionV2-1i18n + 错误码) |
| `actions-kp.ts` | 知识点选项 Server Action | | `actions-kp.ts` | 知识点选项 Server ActionV2-1i18n + 错误码) |
| `publish-service.ts` | 发布作业服务(编排 homework/exams/classes通过对方 data-access 调用,无直查跨模块表) | | `publish-service.ts` | 发布作业服务(编排 homework/exams/classes通过对方 data-access 调用,无直查跨模块表V2-1抛出 `PublishServiceError` 错误码V2-3显式字段映射替代 `as unknown as` |
| `ai-suggest.ts` | AI 知识点建议服务 | | `ai-suggest.ts` | AI 知识点建议服务 |
| `seed-templates.ts` | 模板种子数据 | | `seed-templates.ts` | 模板种子数据 |
| `hooks/use-lesson-plan-editor.ts` | 课案编辑器 Hook基于 zustand支持 nodes/edges 操作addNode/updateNode/updateNodePosition/removeNode/connect/disconnect/setEdges/selectNode | | `hooks/use-lesson-plan-editor.ts` | 课案编辑器 Hook基于 zustand支持 nodes/edges 操作addNode/updateNode/updateNodePosition/removeNode/connect/disconnect/setEdges/selectNode |
| `components/lesson-plan-list.tsx` | 课案列表i18n 已接入) | | `components/lesson-plan-list.tsx` | 课案列表i18n 已接入) |
| `components/lesson-plan-card.tsx` | 课案卡片i18n 已接入) | | `components/lesson-plan-card.tsx` | 课案卡片i18n 已接入V2-6duplicate/archive 调用 tracker.track |
| `components/lesson-plan-filters.tsx` | 课案筛选器i18n 已接入) | | `components/lesson-plan-filters.tsx` | 课案筛选器i18n 已接入V2-53 个表单元素 label htmlFor 关联 |
| `components/lesson-plan-editor.tsx` | 课案编辑器(编排 NodeEditor + NodeEditPaneli18n 已接入) | | `components/lesson-plan-editor.tsx` | 课案编辑器(编排 NodeEditor + NodeEditPaneli18n 已接入V2-6handleManualSave 调用 tracker.track |
| `components/node-editor.tsx` | **节点图画布**React Flow使用 lib/rf-mappers + lib/node-summary 纯函数i18n 已接入) | | `components/node-editor.tsx` | **节点图画布**React Flow使用 lib/rf-mappers + lib/node-summary 纯函数i18n 已接入V2-4MiniMap 复用 getNodeColorV2-5role=application + 键盘导航配置 |
| `components/node-edit-panel.tsx` | **侧边内容编辑面板**(配置驱动渲染 Block通过 getBlockComponent + LessonPlanErrorBoundary 包裹i18n 已接入) | | `components/node-edit-panel.tsx` | **侧边内容编辑面板**(配置驱动渲染 Block通过 getBlockComponent + LessonPlanErrorBoundary 包裹i18n 已接入) |
| `components/nodes/lesson-node.tsx` | **自定义节点组件**(使用 lib/node-summary 的 getNodeSummary/getNodeColori18n 已接入) | | `components/nodes/lesson-node.tsx` | **自定义节点组件**(使用 lib/node-summary 的 getNodeSummary/getNodeColori18n 已接入) |
| `components/lesson-plan-error-boundary.tsx` | **错误边界**LessonPlanErrorBoundary 类组件,支持 fallback 和 onError 回调 | | `components/lesson-plan-error-boundary.tsx` | **错误边界**LessonPlanErrorBoundary 类组件,支持 fallback 和 onError 回调 |
| `components/lesson-plan-skeleton.tsx` | **骨架屏**VersionListSkeleton/QuestionBankSkeleton/KnowledgePointSkeleton/LessonPlanListSkeleton | | `components/lesson-plan-skeleton.tsx` | **骨架屏**VersionListSkeleton/QuestionBankSkeleton/KnowledgePointSkeleton/LessonPlanListSkeleton |
| `components/block-renderer.tsx` | ⚠️ @deprecated Block 渲染器(已被 NodeEditor 替代,保留向后兼容) | | `components/block-renderer.tsx` | ⚠️ @deprecated Block 渲染器(已被 NodeEditor 替代,保留向后兼容) |
| `components/template-picker.tsx` | 模板选择器i18n 已接入) | | `components/template-picker.tsx` | 模板选择器i18n 已接入V2-6create 调用 tracker.track |
| `components/version-history-drawer.tsx` | 版本历史抽屉i18n 已接入) | | `components/version-history-drawer.tsx` | 版本历史抽屉i18n 已接入V2-6revert 调用 tracker.track |
| `components/knowledge-point-picker.tsx` | 知识点选择器i18n 已接入) | | `components/knowledge-point-picker.tsx` | 知识点选择器i18n 已接入) |
| `components/question-bank-picker.tsx` | 题库选择器i18n 已接入) | | `components/question-bank-picker.tsx` | 题库选择器i18n 已接入) |
| `components/inline-question-editor.tsx` | 内联题目编辑器i18n 已接入) | | `components/inline-question-editor.tsx` | 内联题目编辑器i18n 已接入V2-5type/difficulty select label htmlFor 关联 |
| `components/publish-homework-dialog.tsx` | 发布作业对话框i18n 已接入) | | `components/publish-homework-dialog.tsx` | 发布作业对话框i18n 已接入V2-6publish 调用 tracker.track |
| `components/blocks/rich-text-block.tsx` | 富文本 Block被 NodeEditPanel 复用i18n 已接入) | | `components/blocks/rich-text-block.tsx` | 富文本 Block被 NodeEditPanel 复用i18n 已接入) |
| `components/blocks/text-study-block.tsx` | 课文研读 Block被 NodeEditPanel 复用i18n 已接入) | | `components/blocks/text-study-block.tsx` | 课文研读 Block被 NodeEditPanel 复用i18n 已接入) |
| `components/blocks/exercise-block.tsx` | 练习 Block被 NodeEditPanel 复用,使用 router.refresh 替代 window.location.reloadi18n 已接入) | | `components/blocks/exercise-block.tsx` | 练习 Block被 NodeEditPanel 复用,使用 router.refresh 替代 window.location.reloadi18n 已接入V2-5purpose select label 关联 + 题目列表 ul/li 语义化 |
| `components/blocks/reflection-block.tsx` | 反思 Block被 NodeEditPanel 复用i18n 已接入) | | `components/blocks/reflection-block.tsx` | 反思 Block被 NodeEditPanel 复用i18n 已接入) |
--- ---

View File

@@ -4086,6 +4086,12 @@
"permission": "TEXTBOOK_UPDATE", "permission": "TEXTBOOK_UPDATE",
"signature": "(chapterId, newIndex, parentId, textbookId) => Promise<ActionState>", "signature": "(chapterId, newIndex, parentId, textbookId) => Promise<ActionState>",
"purpose": "章节排序" "purpose": "章节排序"
},
{
"name": "getKnowledgePointsByChapterAction",
"permission": "TEXTBOOK_READ",
"signature": "(chapterId, textbookId) => Promise<ActionState<KnowledgePoint[]>>",
"purpose": "获取章节下的知识点列表(含资源归属校验)"
} }
], ],
"dataAccess": [ "dataAccess": [
@@ -4249,6 +4255,24 @@
"updateKnowledgePointAction", "updateKnowledgePointAction",
"deleteKnowledgePointAction" "deleteKnowledgePointAction"
] ]
},
{
"name": "getSubjectLabelKey",
"signature": "(subject: string) => string",
"purpose": "获取学科的 i18n 标签键",
"usedBy": [
"textbooks/components/textbook-filters.tsx",
"textbooks/components/textbook-card.tsx"
]
},
{
"name": "getGradeLabelKey",
"signature": "(grade: string) => string",
"purpose": "获取年级的 i18n 标签键",
"usedBy": [
"textbooks/components/textbook-filters.tsx",
"textbooks/components/textbook-card.tsx"
]
} }
], ],
"hooks": [ "hooks": [
@@ -4264,7 +4288,7 @@
{ {
"name": "useKnowledgePointActions", "name": "useKnowledgePointActions",
"file": "hooks/use-knowledge-point-actions.ts", "file": "hooks/use-knowledge-point-actions.ts",
"signature": "(textbookId, selectedChapterId, selectedChapterTextbookId, highlightedKpId, setHighlightedKpId, onKpCreated?) => { editingKp, setEditingKp, editKpDialogOpen, setEditKpDialogOpen, isUpdatingKp, questionDialogOpen, setQuestionDialogOpen, targetKpForQuestion, setTargetKpForQuestion, deleteConfirmOpen, setDeleteConfirmOpen, handleCreateKnowledgePoint, requestDeleteKP, confirmDeleteKP, handleUpdateKP }", "signature": "(textbookId, selectedChapterId, selectedChapterTextbookId, highlightedKpId, setHighlightedKpId, onKpCreated?) => { editingKp, setEditingKp, editKpDialogOpen, setEditKpDialogOpen, isUpdatingKp, questionDialogOpen, setQuestionDialogOpen, targetKpForQuestion, setTargetKpForQuestion, deleteConfirmOpen, setDeleteConfirmOpen, handleCreateKnowledgePoint, requestDeleteKnowledgePoint, confirmDeleteKnowledgePoint, handleUpdateKnowledgePoint }",
"purpose": "知识点操作Hook(6参数)", "purpose": "知识点操作Hook(6参数)",
"usedBy": [ "usedBy": [
"textbook-reader.tsx" "textbook-reader.tsx"
@@ -4361,6 +4385,105 @@
] ]
} }
], ],
"constants": [
{
"name": "SUBJECTS",
"file": "constants.ts",
"purpose": "学科常量数组"
},
{
"name": "GRADES",
"file": "constants.ts",
"purpose": "年级常量数组"
},
{
"name": "SUBJECT_COLORS",
"file": "constants.ts",
"purpose": "学科颜色映射"
},
{
"name": "getSubjectColor",
"file": "constants.ts",
"signature": "(subject: string) => string",
"purpose": "获取学科对应颜色"
},
{
"name": "getSubjectLabelKey",
"file": "constants.ts",
"signature": "(subject: string) => string",
"purpose": "获取学科 i18n 标签键"
},
{
"name": "getGradeLabelKey",
"file": "constants.ts",
"signature": "(grade: string) => string",
"purpose": "获取年级 i18n 标签键"
}
],
"utils": [
{
"name": "sortChapters",
"file": "utils.ts",
"purpose": "章节排序"
},
{
"name": "buildChapterTree",
"file": "utils.ts",
"purpose": "构建章节树(返回 ChapterTreeNode[]"
},
{
"name": "buildChapterIndex",
"file": "utils.ts",
"purpose": "构建章节索引 Map"
},
{
"name": "findChapterParent",
"file": "utils.ts",
"purpose": "查找章节父节点"
},
{
"name": "filterKnowledgePointsByChapter",
"file": "utils.ts",
"purpose": "按章节过滤知识点"
},
{
"name": "normalizeOptional",
"file": "utils.ts",
"purpose": "可选字段归一化"
},
{
"name": "highlightKnowledgePoints",
"file": "utils.ts",
"purpose": "高亮知识点"
}
],
"graphLayout": [
{
"name": "computeGraphLayout",
"file": "graph-layout.ts",
"purpose": "知识图谱布局计算纯函数"
}
],
"analytics": [
{
"name": "TextbookAnalytics",
"file": "analytics.tsx",
"type": "context",
"purpose": "教材分析 Context"
},
{
"name": "TextbookAnalyticsProvider",
"file": "analytics.tsx",
"type": "component",
"purpose": "教材分析 Provider"
},
{
"name": "useTextbookAnalytics",
"file": "analytics.tsx",
"type": "hook",
"purpose": "教材分析 Hook"
}
],
"components": [ "components": [
{ {
"name": "ChapterSidebarList", "name": "ChapterSidebarList",
@@ -4370,10 +4493,6 @@
"name": "CreateChapterDialog", "name": "CreateChapterDialog",
"purpose": "创建章节对话框" "purpose": "创建章节对话框"
}, },
{
"name": "CreateKnowledgePointDialog",
"purpose": "创建知识点对话框"
},
{ {
"name": "KnowledgeGraph", "name": "KnowledgeGraph",
"purpose": "知识图谱可视化" "purpose": "知识图谱可视化"
@@ -4387,8 +4506,8 @@
"purpose": "知识点列表" "purpose": "知识点列表"
}, },
{ {
"name": "KnowledgePointPanel", "name": "SectionErrorBoundary",
"purpose": "知识点面板" "purpose": "章节内容错误边界class component + i18n + router.refresh 重试)"
}, },
{ {
"name": "TextbookCard", "name": "TextbookCard",
@@ -4415,27 +4534,25 @@
"purpose": "教材设置对话框" "purpose": "教材设置对话框"
} }
], ],
"uiDeps": [ "uiDeps": [],
{ "uiDepsNote": "已通过 render prop 解耦,不再直接 import questions 模块组件",
"from": "textbooks/components/knowledge-point-dialogs.tsx",
"to": "questions/components/create-question-dialog",
"status": "P0 待解耦(直接 import 跨模块业务组件,应改为 props/Context 注入)",
"auditRef": "audit/textbooks-audit-report.md §2.1.1"
}
],
"knownIssues": [ "knownIssues": [
"P0 跨模块 UI 依赖knowledge-point-dialogs.tsx 直接 import questions 模块 CreateQuestionDialog", "i18n 覆盖率约 95%chapter-sidebar-list 已接入actions.ts 已接入section-error-boundary 默认值已改英文)",
"P0 前端权限硬编码canEdit={true} 按路由写死,未用 usePermission().hasPermission()", "类型断言残留 3 处 as string",
"P0 全模块零 i18n中英文文案硬编码未接入 next-intl", "P2 图谱方向键导航未实现"
"P1 Server Action 未校验资源归属chapterId 是否属于 textbookId",
"P1 data-access 缺数据范围过滤(学生端未按年级过滤)",
"P1 缺 Error Boundary无 error.tsx",
"P1 知识点列表/弹窗重复实现knowledge-point-panel.tsx 无调用方)",
"P1 学科/年级选项硬编码三处且彼此不一致",
"P1 纯逻辑未导出,零单测",
"P2 类型断言chapter-sidebar-list.tsx 用 ! 、knowledge-graph.tsx 用 as+!",
"P2 删除确认不一致textbook-settings-dialog 用 confirm(),其余用 AlertDialog"
], ],
"files": {
"actions.ts": 377,
"data-access.ts": 619,
"types.ts": 45,
"schema.ts": 64,
"constants.ts": 91,
"utils.ts": 181,
"graph-layout.ts": 141,
"analytics.tsx": 43,
"hooks/use-knowledge-point-actions.ts": 121,
"hooks/use-text-selection.ts": 57
},
"auditReport": "audit/textbooks-audit-report.md" "auditReport": "audit/textbooks-audit-report.md"
} }
}, },
@@ -5804,6 +5921,24 @@
{ {
"name": "AcademicYearClient", "name": "AcademicYearClient",
"purpose": "学年管理客户端" "purpose": "学年管理客户端"
},
{
"name": "SchoolErrorBoundary",
"file": "components/school-error-boundary.tsx",
"purpose": "school 模块共享 Error Boundaryclass component + i18n + router.refresh 重试4 个页面均包裹",
"props": "children, fallback?"
},
{
"name": "SchoolListSkeleton",
"file": "components/school-skeleton.tsx",
"purpose": "表格加载骨架屏animate-pulse",
"props": "rows?"
},
{
"name": "SchoolCardSkeleton",
"file": "components/school-skeleton.tsx",
"purpose": "卡片加载骨架屏animate-pulse",
"props": ""
} }
], ],
"hooks": [ "hooks": [
@@ -12938,7 +13073,13 @@
"P1-7": "新增 4 个角色配置TEACHER/ADMIN/STUDENT/PARENT+ ROLE_CONFIGS 注册表", "P1-7": "新增 4 个角色配置TEACHER/ADMIN/STUDENT/PARENT+ ROLE_CONFIGS 注册表",
"P1-8": "新增 BLOCK_REGISTRY 注册表node-edit-panel 配置驱动渲染", "P1-8": "新增 BLOCK_REGISTRY 注册表node-edit-panel 配置驱动渲染",
"P2-1": "5 个组件添加 role=dialog/aria-modal/aria-label", "P2-1": "5 个组件添加 role=dialog/aria-modal/aria-label",
"P2-4": "预留 LessonPlanTracker 接口 + noopTracker 默认实现" "P2-4": "预留 LessonPlanTracker 接口 + noopTracker 默认实现",
"V2-1": "Server Actions i18n + 错误码模式12 个 Action 通过 getTranslations 翻译错误消息Service/DataAccess 层抛出 PublishServiceError/LessonPlanDataError 错误码Actions 层通过 PUBLISH_ERROR_KEY_MAP 翻译",
"V2-2": "SYSTEM_TEMPLATES i18n 化name/title 改为 i18n 键createLessonPlan 接受 translateTitle 函数在服务端翻译后存储到 DB",
"V2-3": "as unknown as 类型断言清零8 处替换为显式类型映射函数mapRowToLessonPlan/mapRowToListItem/mapRowToTemplate/mapRowToVersion+ 类型守卫isLessonPlanStatus/isTemplateType/isTemplateScope",
"V2-4": "MiniMap nodeColor 复用 lib/node-summary.ts 的 getNodeColor",
"V2-5": "a11y 深度修复lesson-plan-filters/exercise-block/inline-question-editor 的 select 添加 label htmlFor 关联exercise-block 题目列表改为 ul/linode-editor 画布添加 role=application + 键盘导航配置",
"V2-6": "Tracker 埋点接入:新增 useLessonPlanTrackerSafe hook在 create/save/publish/revert/duplicate/archive 6 处调用 tracker.track"
} }
} }
}, },

View File

@@ -0,0 +1,159 @@
# 公告和消息模块审计报告 V2
> 审查日期2026-06-22
> 审查范围V1 改进后的 `src/modules/announcements/**`、`src/modules/messaging/**`、`src/modules/notifications/**`、对应路由层
> 前置文档:`announcements-messages-audit-report.md`V114 项改进已全部完成或标记超出范围)
> 架构图参考:`docs/architecture/004_architecture_impact_map.md` §2.13 / §2.14 / §2.16
---
## 一、V1 完成情况复核
| V1 编号 | 标题 | 状态 |
|---------|------|------|
| P0-1 | i18n 全覆盖 | ✅ 已完成 |
| P0-2 | 消除角色硬编码 | ✅ 已完成COMMON_NAV_ITEMS 提取) |
| P0-3 | 补充错误边界 | ✅ 已完成7 个 error.tsx |
| P1-4 | 解耦 messaging 与 notifications | ✅ 已完成(通知组件迁移) |
| P1-5 | 页面编排下沉 | ✅ 已完成getAdminAnnouncementsPageData / getMessagesPageData |
| P1-6 | 公告表单条件校验 | ✅ 已完成superRefine |
| P1-7 | 消息列表分页与搜索 hook | ✅ 已完成useMessageSearch + 分页 UI |
| P1-8 | 通知实时推送 | ⚠️ 超出范围(需 SSE/WebSocket 基础设施) |
| P1-9 | 消息软删除事务化 | ✅ 已完成db.transaction |
| P2-10 | a11y 改进 | ✅ 已完成aria-label |
| P2-11 | 监控埋点 | ✅ 已完成trackEvent 接口) |
| P2-12 | 测试覆盖 | ⚠️ 超出范围(需独立测试计划) |
| P2-13 | 行业功能补齐 | ⚠️ 超出范围(需产品规划) |
| P2-14 | 架构图同步 | ✅ 已完成 |
V1 共 11 项已实施3 项标记超出范围。
---
## 二、V2 新发现问题
### 2.1 通知 i18n 命名空间越界P0
| 位置 | 问题 | 违反规则 |
|------|------|----------|
| [notifications/components/notification-list.tsx](file:///e:/Desktop/CICD/src/modules/notifications/components/notification-list.tsx) L29 | `useTranslations("messages")` 通知组件使用 messages 命名空间 | "模块标准结构" — notifications 模块应有独立 i18n 资源 |
| [notifications/components/notification-dropdown.tsx](file:///e:/Desktop/CICD/src/modules/notifications/components/notification-dropdown.tsx) L39 | 同上 | 同上 |
| `src/shared/i18n/messages/` | 无 `notifications.json` 翻译文件 | 翻译文件结构不完整 |
| [i18n/request.ts](file:///e:/Desktop/CICD/src/i18n/request.ts) | 未加载 notifications 翻译文件 | 翻译文件未注册 |
**后果**:通知相关文案(`notificationType.*``empty.noNotifications*``actions.markAllRead` 等)散落在 messages 命名空间,模块边界混乱,维护困难。
### 2.2 通知标题硬编码P0
| 位置 | 代码 | 违反规则 |
|------|------|----------|
| [announcements/actions.ts](file:///e:/Desktop/CICD/src/modules/announcements/actions.ts) L75 | `title: \`新公告:${announcement.title}\`` | "所有用户可见文本必须适配 i18n" |
| [messaging/actions.ts](file:///e:/Desktop/CICD/src/modules/messaging/actions.ts) L70-71 | `title: input.subject ? \`New message: ${input.subject}\` : "New message"` | 同上 |
**后果**:通知标题语言固定(公告通知中文、消息通知英文),无法随 locale 切换。
### 2.3 AnnouncementList 过滤模式不一致P1
| 位置 | 问题 |
|------|------|
| [announcement-list.tsx](file:///e:/Desktop/CICD/src/modules/announcements/components/announcement-list.tsx) L48-59 | 客户端 `useMemo` 过滤 + URL `?status=` 更新混合模式 |
**问题分析**
- L48-51客户端 `filtered` 按 `filter` 状态过滤 `announcements` prop
- L53-59`handleFilterChange` 同时更新 `filter` 状态和 URL `?status=`
- 父页面 `admin/announcements/page.tsx` 根据 `?status=` 服务端查询并传入 `announcements` prop
**后果**:数据被双重过滤(服务端 + 客户端逻辑冗余URL 刷新时客户端 `filter` 状态可能与服务端 `initialStatus` 不同步。
### 2.4 MessageList 客户端过滤冗余P1
| 位置 | 问题 |
|------|------|
| [message-list.tsx](file:///e:/Desktop/CICD/src/modules/messaging/components/message-list.tsx) L50-53 | `filtered` 在客户端再次过滤 `displayMessages`,但 `getMessagesAction` 已按 `type` 参数过滤 |
**问题分析**
- `useMessageSearch` 调用 `getMessagesAction({ type: tab, ... })`,服务端已按 `tab` 过滤
- L50-53 又在客户端按 `m.receiverId === currentUserId` / `m.senderId === currentUserId` 过滤
- 当 `tab === "inbox"` 时,服务端返回 `receiverId === userId` 的消息,客户端再过滤一次相同条件
**后果**:逻辑冗余,且当服务端逻辑变化时客户端过滤可能不一致。
### 2.5 消息详情页编排未下沉P1
| 位置 | 问题 |
|------|------|
| `src/app/(dashboard)/messages/[id]/page.tsx` | 页面层直接调用 `getMessageById` 和 `getMessageThread`,未使用编排函数 |
**后果**:与 V1-P1-5 的编排下沉原则不一致;多个页面需要相同数据时无法复用。
### 2.6 表单未展示服务端校验错误P1
| 位置 | 问题 |
|------|------|
| [announcement-form.tsx](file:///e:/Desktop/CICD/src/modules/announcements/components/announcement-form.tsx) L70-76 | 仅显示 `res.message`,未消费 `res.errors` 字段级错误 |
| [message-compose.tsx](file:///e:/Desktop/CICD/src/modules/messaging/components/message-compose.tsx) L57-63 | 同上 |
**问题分析**
- Server Action 返回 `{ success: false, message, errors: { title: ["..."], content: ["..."] } }`
- 表单仅 `toast.error(res.message)`,用户无法看到具体字段错误
- V1-P1-6 添加的 `superRefine` 条件校验错误无法有效传达给用户
**后果**用户不知道哪个字段出错体验差Zod 校验形同虚设。
### 2.7 轮询间隔硬编码P2
| 位置 | 代码 |
|------|------|
| [notification-dropdown.tsx](file:///e:/Desktop/CICD/src/modules/notifications/components/notification-dropdown.tsx) L71 | `30_000` 硬编码 |
| [unread-message-badge.tsx](file:///e:/Desktop/CICD/src/modules/messaging/components/unread-message-badge.tsx) | `60_000` 硬编码 |
**后果**:调整轮询频率需修改多个文件,无统一配置点。
### 2.8 架构图未记录 V2 新增内容P2
V2 新增的编排函数、i18n 文件、常量等需同步到架构图。
---
## 三、V2 改进优先级
### V2-P0紧急影响 i18n 完整性)
1. **通知 i18n 命名空间独立**:创建 `notifications.json` 翻译文件,将通知相关文案从 `messages.json` 迁移;更新 `i18n/request.ts` 加载新文件;通知组件改用 `useTranslations("notifications")`。
2. **通知标题 i18n 化**:在 `announcements/actions.ts` 和 `messaging/actions.ts` 中使用 `getTranslations` 获取通知标题翻译。
### V2-P1重要影响代码质量与体验
3. **AnnouncementList 过滤模式统一**:移除客户端 `useMemo` 过滤,改为纯服务端过滤(通过 URL `?status=` 触发 RSC 重新渲染)。
4. **MessageList 过滤冗余移除**:移除客户端 `filtered` 过滤,直接使用 `displayMessages`(服务端已按 `type` 过滤)。
5. **消息详情页编排下沉**:新增 `getMessageDetailPageData` 编排函数。
6. **表单服务端校验错误展示**:在 `AnnouncementForm` 和 `MessageCompose` 中展示 `res.errors` 字段级错误。
### V2-P2优化提升可维护性
7. **轮询间隔常量化**:提取 `NOTIFICATION_POLL_INTERVAL_MS` 和 `MESSAGE_POLL_INTERVAL_MS` 常量。
8. **架构图同步**:补充 V2 新增内容到 004/005 架构文档。
---
## 四、实施计划
| 编号 | 文件 | 变更类型 |
|------|------|----------|
| V2-P0-1 | `src/shared/i18n/messages/{zh-CN,en}/notifications.json` | 新建 |
| V2-P0-1 | `src/i18n/request.ts` | 修改(加载 notifications |
| V2-P0-1 | `src/shared/i18n/messages/{zh-CN,en}/messages.json` | 修改(移除通知相关键) |
| V2-P0-1 | `src/modules/notifications/components/notification-list.tsx` | 修改useTranslations 命名空间) |
| V2-P0-1 | `src/modules/notifications/components/notification-dropdown.tsx` | 修改(同上) |
| V2-P0-2 | `src/modules/announcements/actions.ts` | 修改getTranslations |
| V2-P0-2 | `src/modules/messaging/actions.ts` | 修改getTranslations |
| V2-P1-1 | `src/modules/announcements/components/announcement-list.tsx` | 修改(移除客户端过滤) |
| V2-P1-2 | `src/modules/messaging/components/message-list.tsx` | 修改(移除 filtered |
| V2-P1-3 | `src/modules/messaging/data-access.ts` | 修改(新增编排函数) |
| V2-P1-3 | `src/app/(dashboard)/messages/[id]/page.tsx` | 修改(使用编排函数) |
| V2-P1-4 | `src/modules/announcements/components/announcement-form.tsx` | 修改(展示 errors |
| V2-P1-4 | `src/modules/messaging/components/message-compose.tsx` | 修改(展示 errors |
| V2-P2-1 | `src/modules/notifications/components/notification-dropdown.tsx` | 修改(常量化) |
| V2-P2-1 | `src/modules/messaging/components/unread-message-badge.tsx` | 修改(常量化) |
| V2-P2-2 | `docs/architecture/004_architecture_impact_map.md` | 修改(同步) |
| V2-P2-2 | `docs/architecture/005_architecture_data.json` | 修改(同步) |

View File

@@ -1,10 +1,9 @@
import { notFound } from "next/navigation" import { notFound } from "next/navigation"
import type { Metadata } from "next" import type { Metadata } from "next"
import { after } from "next/server"
import { getTranslations } from "next-intl/server" import { getTranslations } from "next-intl/server"
import { requirePermission } from "@/shared/lib/auth-guard" import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions" import { Permissions } from "@/shared/types/permissions"
import { getMessageById, markMessageAsRead } from "@/modules/messaging/data-access" import { getMessageDetailPageData } from "@/modules/messaging/data-access"
import { MessageDetail } from "@/modules/messaging/components/message-detail" import { MessageDetail } from "@/modules/messaging/components/message-detail"
export const dynamic = "force-dynamic" export const dynamic = "force-dynamic"
@@ -22,14 +21,9 @@ export default async function MessageDetailPage({
const ctx = await requirePermission(Permissions.MESSAGE_READ) const ctx = await requirePermission(Permissions.MESSAGE_READ)
const { id } = await params const { id } = await params
const message = await getMessageById(id, ctx.userId) const message = await getMessageDetailPageData(id, ctx.userId)
if (!message) notFound() if (!message) notFound()
// Auto-mark as read when viewed by the receiver (non-blocking)
if (!message.isRead && message.receiverId === ctx.userId) {
after(() => markMessageAsRead(id, ctx.userId))
}
return ( return (
<div className="flex h-full flex-col p-8"> <div className="flex h-full flex-col p-8">
<MessageDetail message={message} currentUserId={ctx.userId} /> <MessageDetail message={message} currentUserId={ctx.userId} />

View File

@@ -2,10 +2,9 @@ import { getTranslations } from "next-intl/server"
import { requirePermission } from "@/shared/lib/auth-guard" import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions" import { Permissions } from "@/shared/types/permissions"
import { getMessages } from "@/modules/messaging/data-access" import { getMessagesPageData } from "@/modules/messaging/data-access"
import { getNotifications } from "@/modules/notifications/data-access"
import { MessageList } from "@/modules/messaging/components/message-list" import { MessageList } from "@/modules/messaging/components/message-list"
import { NotificationList } from "@/modules/messaging/components/notification-list" import { NotificationList } from "@/modules/notifications/components/notification-list"
export const dynamic = "force-dynamic" export const dynamic = "force-dynamic"
@@ -18,10 +17,8 @@ export default async function MessagesPage() {
const t = await getTranslations("messages") const t = await getTranslations("messages")
const ctx = await requirePermission(Permissions.MESSAGE_READ) const ctx = await requirePermission(Permissions.MESSAGE_READ)
const [messagesResult, notificationsResult] = await Promise.all([ const { messages: messagesResult, notifications: notificationsResult } =
getMessages({ userId: ctx.userId, type: "all", page: 1, pageSize: 50 }), await getMessagesPageData(ctx.userId)
getNotifications(ctx.userId, { page: 1, pageSize: 20 }),
])
return ( return (
<div className="flex h-full flex-col space-y-8 p-8"> <div className="flex h-full flex-col space-y-8 p-8">

View File

@@ -29,6 +29,7 @@ export default getRequestConfig(async () => {
examHomework, examHomework,
announcements, announcements,
messages, messages,
notifications,
settings, settings,
textbooks, textbooks,
grade, grade,
@@ -48,6 +49,7 @@ export default getRequestConfig(async () => {
import(`@/shared/i18n/messages/${locale}/exam-homework.json`), import(`@/shared/i18n/messages/${locale}/exam-homework.json`),
import(`@/shared/i18n/messages/${locale}/announcements.json`), import(`@/shared/i18n/messages/${locale}/announcements.json`),
import(`@/shared/i18n/messages/${locale}/messages.json`), import(`@/shared/i18n/messages/${locale}/messages.json`),
import(`@/shared/i18n/messages/${locale}/notifications.json`),
import(`@/shared/i18n/messages/${locale}/settings.json`), import(`@/shared/i18n/messages/${locale}/settings.json`),
import(`@/shared/i18n/messages/${locale}/textbooks.json`), import(`@/shared/i18n/messages/${locale}/textbooks.json`),
import(`@/shared/i18n/messages/${locale}/grade.json`), import(`@/shared/i18n/messages/${locale}/grade.json`),
@@ -71,6 +73,7 @@ export default getRequestConfig(async () => {
examHomework: examHomework.default, examHomework: examHomework.default,
announcements: announcements.default, announcements: announcements.default,
messages: messages.default, messages: messages.default,
notifications: notifications.default,
settings: settings.default, settings: settings.default,
textbooks: textbooks.default, textbooks: textbooks.default,
grade: grade.default, grade: grade.default,

View File

@@ -2,8 +2,10 @@
import { revalidatePath } from "next/cache" import { revalidatePath } from "next/cache"
import { createId } from "@paralleldrive/cuid2" import { createId } from "@paralleldrive/cuid2"
import { getTranslations } from "next-intl/server"
import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guard" import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guard"
import { trackEvent } from "@/shared/lib/track-event"
import { Permissions } from "@/shared/types/permissions" import { Permissions } from "@/shared/types/permissions"
import type { ActionState } from "@/shared/types/action-state" import type { ActionState } from "@/shared/types/action-state"
import { sendBatchNotifications } from "@/modules/notifications" import { sendBatchNotifications } from "@/modules/notifications"
@@ -69,10 +71,14 @@ async function notifyAnnouncementPublished(announcement: Announcement): Promise<
const targetUserIds = await resolveTargetUserIds(announcement) const targetUserIds = await resolveTargetUserIds(announcement)
if (targetUserIds.length === 0) return if (targetUserIds.length === 0) return
const t = await getTranslations("announcements")
const title = t("notification.publishedTitle", { title: announcement.title })
const content = t("notification.publishedContent")
const payloads: NotificationPayload[] = targetUserIds.map((userId) => ({ const payloads: NotificationPayload[] = targetUserIds.map((userId) => ({
userId, userId,
title: `新公告:${announcement.title}`, title,
content: announcement.content.slice(0, 200), content,
type: "info", type: "info",
actionUrl: `/announcements/${announcement.id}`, actionUrl: `/announcements/${announcement.id}`,
metadata: { metadata: {
@@ -146,6 +152,14 @@ export async function createAnnouncementAction(
revalidatePath("/admin/announcements") revalidatePath("/admin/announcements")
revalidatePath("/announcements") revalidatePath("/announcements")
void trackEvent({
event: isPublished ? "announcement.published" : "announcement.created",
userId: ctx.userId,
targetId: id,
targetType: "announcement",
properties: { type: input.type, status: input.status },
})
return { success: true, message: "Announcement created", data: id } return { success: true, message: "Announcement created", data: id }
} catch (e) { } catch (e) {
return handleActionError(e) return handleActionError(e)
@@ -215,6 +229,13 @@ export async function updateAnnouncementAction(
revalidatePath(`/admin/announcements/${id}`) revalidatePath(`/admin/announcements/${id}`)
revalidatePath("/announcements") revalidatePath("/announcements")
void trackEvent({
event: isPublished && !wasPublished ? "announcement.published" : "announcement.updated",
targetId: id,
targetType: "announcement",
properties: { type: input.type, status: input.status, wasPublished },
})
return { success: true, message: "Announcement updated", data: id } return { success: true, message: "Announcement updated", data: id }
} catch (e) { } catch (e) {
return handleActionError(e) return handleActionError(e)
@@ -233,6 +254,13 @@ export async function deleteAnnouncementAction(id: string): Promise<ActionState<
revalidatePath("/admin/announcements") revalidatePath("/admin/announcements")
revalidatePath("/announcements") revalidatePath("/announcements")
void trackEvent({
event: "announcement.deleted",
targetId: id,
targetType: "announcement",
properties: { type: existing.type, status: existing.status },
})
return { success: true, message: "Announcement deleted" } return { success: true, message: "Announcement deleted" }
} catch (e) { } catch (e) {
return handleActionError(e) return handleActionError(e)
@@ -258,6 +286,13 @@ export async function publishAnnouncementAction(id: string): Promise<ActionState
revalidatePath(`/admin/announcements/${id}`) revalidatePath(`/admin/announcements/${id}`)
revalidatePath("/announcements") revalidatePath("/announcements")
void trackEvent({
event: "announcement.published",
targetId: id,
targetType: "announcement",
properties: { type: existing.type },
})
return { success: true, message: "Announcement published" } return { success: true, message: "Announcement published" }
} catch (e) { } catch (e) {
return handleActionError(e) return handleActionError(e)
@@ -277,6 +312,13 @@ export async function archiveAnnouncementAction(id: string): Promise<ActionState
revalidatePath(`/admin/announcements/${id}`) revalidatePath(`/admin/announcements/${id}`)
revalidatePath("/announcements") revalidatePath("/announcements")
void trackEvent({
event: "announcement.archived",
targetId: id,
targetType: "announcement",
properties: { type: existing.type },
})
return { success: true, message: "Announcement archived" } return { success: true, message: "Announcement archived" }
} catch (e) { } catch (e) {
return handleActionError(e) return handleActionError(e)

View File

@@ -23,6 +23,8 @@ import type { Announcement } from "../types"
type Mode = "create" | "edit" type Mode = "create" | "edit"
type FieldErrors = Record<string, string[]>
export function AnnouncementForm({ export function AnnouncementForm({
mode, mode,
announcement, announcement,
@@ -37,14 +39,21 @@ export function AnnouncementForm({
const t = useTranslations("announcements") const t = useTranslations("announcements")
const router = useRouter() const router = useRouter()
const [isWorking, setIsWorking] = useState(false) const [isWorking, setIsWorking] = useState(false)
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({})
const [type, setType] = useState<string>(announcement?.type ?? "school") const [type, setType] = useState<string>(announcement?.type ?? "school")
const [status, setStatus] = useState<string>(announcement?.status ?? "draft") const [status, setStatus] = useState<string>(announcement?.status ?? "draft")
const [targetGradeId, setTargetGradeId] = useState<string>(announcement?.targetGradeId ?? "") const [targetGradeId, setTargetGradeId] = useState<string>(announcement?.targetGradeId ?? "")
const [targetClassId, setTargetClassId] = useState<string>(announcement?.targetClassId ?? "") const [targetClassId, setTargetClassId] = useState<string>(announcement?.targetClassId ?? "")
const getFieldError = (field: string): string | null => {
const errs = fieldErrors[field]
return errs && errs.length > 0 ? errs[0] : null
}
const handleSubmit = async (formData: FormData) => { const handleSubmit = async (formData: FormData) => {
setIsWorking(true) setIsWorking(true)
setFieldErrors({})
try { try {
formData.set("type", type) formData.set("type", type)
formData.set("status", status) formData.set("status", status)
@@ -72,6 +81,10 @@ export function AnnouncementForm({
router.push("/admin/announcements") router.push("/admin/announcements")
router.refresh() router.refresh()
} else { } else {
// 展示字段级错误(来自 Zod superRefine 校验)
if (res.errors) {
setFieldErrors(res.errors)
}
toast.error(res.message || t("messages.updateFailed")) toast.error(res.message || t("messages.updateFailed"))
} }
} catch { } catch {
@@ -98,7 +111,11 @@ export function AnnouncementForm({
placeholder={t("form.titlePlaceholder")} placeholder={t("form.titlePlaceholder")}
defaultValue={announcement?.title ?? ""} defaultValue={announcement?.title ?? ""}
required required
aria-invalid={!!getFieldError("title")}
/> />
{getFieldError("title") ? (
<p className="text-destructive text-xs">{getFieldError("title")}</p>
) : null}
</div> </div>
<div className="grid gap-2"> <div className="grid gap-2">
@@ -110,7 +127,11 @@ export function AnnouncementForm({
className="min-h-[160px]" className="min-h-[160px]"
defaultValue={announcement?.content ?? ""} defaultValue={announcement?.content ?? ""}
required required
aria-invalid={!!getFieldError("content")}
/> />
{getFieldError("content") ? (
<p className="text-destructive text-xs">{getFieldError("content")}</p>
) : null}
</div> </div>
<div className="grid grid-cols-1 gap-4 md:grid-cols-2"> <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
@@ -148,7 +169,7 @@ export function AnnouncementForm({
<div className="grid gap-2 md:col-span-2"> <div className="grid gap-2 md:col-span-2">
<Label>{t("form.targetGrade")}</Label> <Label>{t("form.targetGrade")}</Label>
<Select value={targetGradeId} onValueChange={setTargetGradeId}> <Select value={targetGradeId} onValueChange={setTargetGradeId}>
<SelectTrigger> <SelectTrigger aria-invalid={!!getFieldError("targetGradeId")}>
<SelectValue placeholder={t("form.targetGradePlaceholder")} /> <SelectValue placeholder={t("form.targetGradePlaceholder")} />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
@@ -160,6 +181,9 @@ export function AnnouncementForm({
</SelectContent> </SelectContent>
</Select> </Select>
<input type="hidden" name="targetGradeId" value={targetGradeId} /> <input type="hidden" name="targetGradeId" value={targetGradeId} />
{getFieldError("targetGradeId") ? (
<p className="text-destructive text-xs">{getFieldError("targetGradeId")}</p>
) : null}
</div> </div>
) : null} ) : null}
@@ -167,7 +191,7 @@ export function AnnouncementForm({
<div className="grid gap-2 md:col-span-2"> <div className="grid gap-2 md:col-span-2">
<Label>{t("form.targetClass")}</Label> <Label>{t("form.targetClass")}</Label>
<Select value={targetClassId} onValueChange={setTargetClassId}> <Select value={targetClassId} onValueChange={setTargetClassId}>
<SelectTrigger> <SelectTrigger aria-invalid={!!getFieldError("targetClassId")}>
<SelectValue placeholder={t("form.targetClassPlaceholder")} /> <SelectValue placeholder={t("form.targetClassPlaceholder")} />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
@@ -179,6 +203,9 @@ export function AnnouncementForm({
</SelectContent> </SelectContent>
</Select> </Select>
<input type="hidden" name="targetClassId" value={targetClassId} /> <input type="hidden" name="targetClassId" value={targetClassId} />
{getFieldError("targetClassId") ? (
<p className="text-destructive text-xs">{getFieldError("targetClassId")}</p>
) : null}
</div> </div>
) : null} ) : null}
</div> </div>

View File

@@ -1,6 +1,5 @@
"use client" "use client"
import { useMemo, useState } from "react"
import Link from "next/link" import Link from "next/link"
import { useRouter } from "next/navigation" import { useRouter } from "next/navigation"
import { Plus, Megaphone } from "lucide-react" import { Plus, Megaphone } from "lucide-react"
@@ -21,6 +20,14 @@ import type { Announcement, AnnouncementStatus } from "../types"
type Filter = "all" | AnnouncementStatus type Filter = "all" | AnnouncementStatus
/**
* 公告列表组件。
*
* 过滤模式:纯服务端过滤。
* - Select 切换时更新 URL `?status=`,触发 RSC 重新渲染
* - 父页面根据 `?status=` 查询并传入 `announcements` prop
* - 组件不再做客户端二次过滤,避免双重过滤逻辑冗余
*/
export function AnnouncementList({ export function AnnouncementList({
announcements, announcements,
canManage, canManage,
@@ -36,7 +43,7 @@ export function AnnouncementList({
}) { }) {
const t = useTranslations("announcements") const t = useTranslations("announcements")
const router = useRouter() const router = useRouter()
const [filter, setFilter] = useState<Filter>(initialStatus ?? "all") const filter: Filter = initialStatus ?? "all"
const filterOptions: { value: Filter; label: string }[] = [ const filterOptions: { value: Filter; label: string }[] = [
{ value: "all", label: t("filter.all") }, { value: "all", label: t("filter.all") },
@@ -45,13 +52,7 @@ export function AnnouncementList({
{ value: "archived", label: t("filter.archived") }, { value: "archived", label: t("filter.archived") },
] ]
const filtered = useMemo(() => { const handleFilterChange = (value: string): void => {
if (filter === "all") return announcements
return announcements.filter((a) => a.status === filter)
}, [announcements, filter])
const handleFilterChange = (value: string) => {
setFilter(value as Filter)
const params = new URLSearchParams() const params = new URLSearchParams()
if (value !== "all") params.set("status", value) if (value !== "all") params.set("status", value)
const qs = params.toString() const qs = params.toString()
@@ -83,11 +84,11 @@ export function AnnouncementList({
) : null} ) : null}
</div> </div>
{filtered.length === 0 ? ( {announcements.length === 0 ? (
<EmptyState <EmptyState
title={t("empty.noAnnouncements")} title={t("empty.noAnnouncements")}
description={ description={
announcements.length === 0 filter === "all"
? t("empty.noAnnouncementsDesc") ? t("empty.noAnnouncementsDesc")
: t("empty.noMatch") : t("empty.noMatch")
} }
@@ -96,7 +97,7 @@ export function AnnouncementList({
/> />
) : ( ) : (
<div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3"> <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3">
{filtered.map((a) => ( {announcements.map((a) => (
<AnnouncementCard <AnnouncementCard
key={a.id} key={a.id}
announcement={a} announcement={a}

View File

@@ -8,6 +8,7 @@ import { announcements, users } from "@/shared/db/schema"
import type { import type {
Announcement, Announcement,
AnnouncementInsertData, AnnouncementInsertData,
AnnouncementStatus,
AnnouncementUpdateData, AnnouncementUpdateData,
GetAnnouncementsParams, GetAnnouncementsParams,
} from "./types" } from "./types"
@@ -195,3 +196,49 @@ export async function archiveAnnouncementById(id: string): Promise<void> {
}) })
.where(eq(announcements.id, id)) .where(eq(announcements.id, id))
} }
/**
* 管理端公告列表页编排函数:一次性获取公告列表、年级列表、班级列表。
* 将原本散落在 page.tsx 中的多模块编排逻辑下沉到 data-access 层,
* 页面层只需调用单一函数,提升可复用性与可测试性。
*/
export async function getAdminAnnouncementsPageData(status?: AnnouncementStatus): Promise<{
announcements: Announcement[]
grades: { id: string; name: string }[]
classes: { id: string; name: string }[]
}> {
const { getGrades } = await import("@/modules/school/data-access")
const { getAdminClasses } = await import("@/modules/classes/data-access")
const [announcementList, gradeList, classList] = await Promise.all([
getAnnouncements({ status }),
getGrades(),
getAdminClasses(),
])
return {
announcements: announcementList,
grades: gradeList.map((g) => ({ id: g.id, name: g.name })),
classes: classList.map((c) => ({ id: c.id, name: c.name })),
}
}
/**
* 管理端公告编辑页编排函数:一次性获取公告详情和年级列表。
*/
export async function getEditAnnouncementPageData(id: string): Promise<{
announcement: Announcement | null
grades: { id: string; name: string }[]
}> {
const { getGrades } = await import("@/modules/school/data-access")
const [announcement, gradeList] = await Promise.all([
getAnnouncementById(id),
getGrades(),
])
return {
announcement,
grades: gradeList.map((g) => ({ id: g.id, name: g.name })),
}
}

View File

@@ -1,5 +1,53 @@
import { z } from "zod" import { z } from "zod"
/**
* 公告类型与目标受众的联合校验:
* - type=schooltargetGradeId / targetClassId 必须为空
* - type=gradetargetGradeId 必填targetClassId 必须为空
* - type=classtargetClassId 必填
*
* 避免"创建无受众公告"的数据完整性问题。
*/
const refineAudience = (
data: {
type?: "school" | "grade" | "class"
targetGradeId?: string | null
targetClassId?: string | null
},
ctx: z.RefinementCtx
): void => {
const type = data.type ?? "school"
const hasGrade = (data.targetGradeId ?? "").trim().length > 0
const hasClass = (data.targetClassId ?? "").trim().length > 0
if (type === "school" && (hasGrade || hasClass)) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["targetGradeId"],
message: "全校公告不应指定目标年级或班级",
})
return
}
if (type === "grade" && !hasGrade) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["targetGradeId"],
message: "年级公告必须指定目标年级",
})
return
}
if (type === "class" && !hasClass) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
path: ["targetClassId"],
message: "班级公告必须指定目标班级",
})
return
}
}
export const CreateAnnouncementSchema = z export const CreateAnnouncementSchema = z
.object({ .object({
title: z.string().trim().min(1).max(255), title: z.string().trim().min(1).max(255),
@@ -10,6 +58,7 @@ export const CreateAnnouncementSchema = z
targetClassId: z.string().trim().optional().nullable(), targetClassId: z.string().trim().optional().nullable(),
publishedAt: z.string().optional().nullable(), publishedAt: z.string().optional().nullable(),
}) })
.superRefine(refineAudience)
.transform((v) => ({ .transform((v) => ({
title: v.title, title: v.title,
content: v.content, content: v.content,
@@ -32,6 +81,7 @@ export const UpdateAnnouncementSchema = z
targetClassId: z.string().trim().optional().nullable(), targetClassId: z.string().trim().optional().nullable(),
publishedAt: z.string().optional().nullable(), publishedAt: z.string().optional().nullable(),
}) })
.superRefine(refineAudience)
.transform((v) => ({ .transform((v) => ({
title: v.title, title: v.title,
content: v.content, content: v.content,

View File

@@ -36,6 +36,26 @@ export type NavItem = {
items?: { title: string; href: string; permission?: Permission }[] items?: { title: string; href: string; permission?: Permission }[]
} }
/**
* 公共导航项:所有已登录用户均可访问的功能模块。
* 通过权限点permission控制可见性新增角色只需在 NAV_CONFIG 中引用这些公共项,
* 无需复制粘贴。符合"配置驱动设计"和"严禁 role === 'xxx' 硬编码"的规则。
*/
const COMMON_NAV_ITEMS: NavItem[] = [
{
title: "Announcements",
icon: Megaphone,
href: "/announcements",
permission: Permissions.ANNOUNCEMENT_READ,
},
{
title: "Messages",
icon: Mail,
href: "/messages",
permission: Permissions.MESSAGE_READ,
},
]
export const NAV_CONFIG: Partial<Record<Role, NavItem[]>> = { export const NAV_CONFIG: Partial<Record<Role, NavItem[]>> = {
admin: [ admin: [
{ {
@@ -118,12 +138,7 @@ export const NAV_CONFIG: Partial<Record<Role, NavItem[]>> = {
{ title: "Data Changes", href: "/admin/audit-logs/data-changes" }, { title: "Data Changes", href: "/admin/audit-logs/data-changes" },
] ]
}, },
{ ...COMMON_NAV_ITEMS,
title: "Messages",
icon: Mail,
href: "/messages",
permission: Permissions.MESSAGE_READ,
},
{ {
title: "Settings", title: "Settings",
icon: Settings, icon: Settings,
@@ -243,18 +258,85 @@ export const NAV_CONFIG: Partial<Record<Role, NavItem[]>> = {
{ title: "年级洞察", href: "/management/grade/insights" }, { title: "年级洞察", href: "/management/grade/insights" },
] ]
}, },
...COMMON_NAV_ITEMS,
],
grade_head: [
{ {
title: "公告", title: "仪表盘",
icon: Megaphone, icon: LayoutDashboard,
href: "/announcements", href: "/management",
permission: Permissions.ANNOUNCEMENT_READ, permission: Permissions.GRADE_MANAGE,
}, },
{ {
title: "消息", title: "年级管理",
icon: Mail, icon: Briefcase,
href: "/messages", href: "/management",
permission: Permissions.MESSAGE_READ, permission: Permissions.GRADE_MANAGE,
items: [
{ title: "年级班级", href: "/management/grade/classes" },
{ title: "年级洞察", href: "/management/grade/insights" },
]
}, },
{
title: "考勤",
icon: CalendarCheck,
href: "/teacher/attendance",
permission: Permissions.ATTENDANCE_READ,
items: [
{ title: "考勤记录", href: "/teacher/attendance" },
{ title: "考勤统计", href: "/teacher/attendance/stats", permission: Permissions.ATTENDANCE_READ },
]
},
{
title: "成绩",
icon: GraduationCap,
href: "/teacher/grades",
permission: Permissions.GRADE_RECORD_READ,
items: [
{ title: "成绩统计", href: "/teacher/grades/stats", permission: Permissions.GRADE_RECORD_READ },
{ title: "成绩分析", href: "/teacher/grades/analytics", permission: Permissions.GRADE_RECORD_READ },
]
},
...COMMON_NAV_ITEMS,
],
teaching_head: [
{
title: "仪表盘",
icon: LayoutDashboard,
href: "/management",
permission: Permissions.GRADE_MANAGE,
},
{
title: "年级管理",
icon: Briefcase,
href: "/management",
permission: Permissions.GRADE_MANAGE,
items: [
{ title: "年级班级", href: "/management/grade/classes" },
{ title: "年级洞察", href: "/management/grade/insights" },
]
},
{
title: "考勤",
icon: CalendarCheck,
href: "/teacher/attendance",
permission: Permissions.ATTENDANCE_READ,
items: [
{ title: "考勤记录", href: "/teacher/attendance" },
{ title: "考勤统计", href: "/teacher/attendance/stats", permission: Permissions.ATTENDANCE_READ },
]
},
{
title: "成绩",
icon: GraduationCap,
href: "/teacher/grades",
permission: Permissions.GRADE_RECORD_READ,
items: [
{ title: "成绩统计", href: "/teacher/grades/stats", permission: Permissions.GRADE_RECORD_READ },
{ title: "成绩分析", href: "/teacher/grades/analytics", permission: Permissions.GRADE_RECORD_READ },
]
},
...COMMON_NAV_ITEMS,
], ],
student: [ student: [
{ {
@@ -303,18 +385,7 @@ export const NAV_CONFIG: Partial<Record<Role, NavItem[]>> = {
href: "/student/elective", href: "/student/elective",
permission: Permissions.ELECTIVE_SELECT, permission: Permissions.ELECTIVE_SELECT,
}, },
{ ...COMMON_NAV_ITEMS,
title: "Announcements",
icon: Megaphone,
href: "/announcements",
permission: Permissions.ANNOUNCEMENT_READ,
},
{
title: "Messages",
icon: Mail,
href: "/messages",
permission: Permissions.MESSAGE_READ,
},
], ],
parent: [ parent: [
{ {
@@ -339,17 +410,6 @@ export const NAV_CONFIG: Partial<Record<Role, NavItem[]>> = {
icon: CalendarRange, icon: CalendarRange,
href: "/parent/leave", href: "/parent/leave",
}, },
{ ...COMMON_NAV_ITEMS,
title: "Announcements",
icon: Megaphone,
href: "/announcements",
permission: Permissions.ANNOUNCEMENT_READ,
},
{
title: "Messages",
icon: Mail,
href: "/messages",
permission: Permissions.MESSAGE_READ,
},
] ]
} }

View File

@@ -1,7 +1,9 @@
"use server" "use server"
import { revalidatePath } from "next/cache" import { revalidatePath } from "next/cache"
import { getTranslations } from "next-intl/server"
import { PermissionDeniedError, requirePermission } from "@/shared/lib/auth-guard" import { PermissionDeniedError, requirePermission } from "@/shared/lib/auth-guard"
import { trackEvent } from "@/shared/lib/track-event"
import { Permissions } from "@/shared/types/permissions" import { Permissions } from "@/shared/types/permissions"
import type { ActionState } from "@/shared/types/action-state" import type { ActionState } from "@/shared/types/action-state"
import { sendNotification } from "@/modules/notifications/dispatcher" import { sendNotification } from "@/modules/notifications/dispatcher"
@@ -20,19 +22,12 @@ import {
getRecipients, getRecipients,
getUnreadMessageCount, getUnreadMessageCount,
} from "./data-access" } from "./data-access"
import {
getNotifications,
markNotificationAsRead,
markAllNotificationsAsRead,
getUnreadNotificationCount,
} from "@/modules/notifications/data-access"
import { import {
getNotificationPreferences, getNotificationPreferences,
upsertNotificationPreferences, upsertNotificationPreferences,
} from "@/modules/notifications/preferences" } from "@/modules/notifications/preferences"
import type { Message, MessageType, RecipientOption } from "./types" import type { Message, MessageType, RecipientOption } from "./types"
import type { import type {
Notification,
NotificationPreferences, NotificationPreferences,
UpdateNotificationPreferencesInput, UpdateNotificationPreferencesInput,
} from "@/modules/notifications/types" } from "@/modules/notifications/types"
@@ -70,10 +65,14 @@ export async function sendMessageAction(
// Notify the receiver about the new message via the notifications dispatcher. // Notify the receiver about the new message via the notifications dispatcher.
// This respects user notification preferences (SMS/WeChat/Email/In-App). // This respects user notification preferences (SMS/WeChat/Email/In-App).
const t = await getTranslations("messages")
const notifyTitle = input.subject
? t("notification.messageTitle", { subject: input.subject })
: t("notification.messageTitleNoSubject")
await sendNotification({ await sendNotification({
userId: input.receiverId, userId: input.receiverId,
type: "info", type: "info",
title: input.subject ? `New message: ${input.subject}` : "New message", title: notifyTitle,
content: input.content.slice(0, 200), content: input.content.slice(0, 200),
actionUrl: `/messages/${id}`, actionUrl: `/messages/${id}`,
metadata: { messageType: "message", messageId: id }, metadata: { messageType: "message", messageId: id },
@@ -82,6 +81,14 @@ export async function sendMessageAction(
revalidatePath("/messages") revalidatePath("/messages")
revalidatePath(`/messages/${id}`) revalidatePath(`/messages/${id}`)
void trackEvent({
event: "message.sent",
userId: ctx.userId,
targetId: id,
targetType: "message",
properties: { receiverId: input.receiverId, hasSubject: !!input.subject },
})
return { success: true, message: "Message sent", data: id } return { success: true, message: "Message sent", data: id }
} catch (e) { } catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message } if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
@@ -102,6 +109,14 @@ export async function markMessageAsReadAction(messageId: string): Promise<Action
await markMessageAsRead(parsed.data.messageId, ctx.userId) await markMessageAsRead(parsed.data.messageId, ctx.userId)
revalidatePath("/messages") revalidatePath("/messages")
revalidatePath(`/messages/${parsed.data.messageId}`) revalidatePath(`/messages/${parsed.data.messageId}`)
void trackEvent({
event: "message.marked_read",
userId: ctx.userId,
targetId: parsed.data.messageId,
targetType: "message",
})
return { success: true, message: "Marked as read" } return { success: true, message: "Marked as read" }
} catch (e) { } catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message } if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
@@ -122,6 +137,14 @@ export async function deleteMessageAction(messageId: string): Promise<ActionStat
await deleteMessage(parsed.data.messageId, ctx.userId) await deleteMessage(parsed.data.messageId, ctx.userId)
revalidatePath("/messages") revalidatePath("/messages")
revalidatePath(`/messages/${parsed.data.messageId}`) revalidatePath(`/messages/${parsed.data.messageId}`)
void trackEvent({
event: "message.deleted",
userId: ctx.userId,
targetId: parsed.data.messageId,
targetType: "message",
})
return { success: true, message: "Message deleted" } return { success: true, message: "Message deleted" }
} catch (e) { } catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message } if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
@@ -193,59 +216,11 @@ export async function getUnreadMessageCountAction(): Promise<ActionState<number>
} }
} }
export async function getUnreadNotificationCountAction(): Promise<ActionState<number>> { // ---------------------------------------------------------------------------
try { // 通知相关 Server ActionsgetNotificationsAction / markNotificationAsReadAction /
const ctx = await requirePermission(Permissions.MESSAGE_READ) // markAllNotificationsAsReadAction / getUnreadNotificationCountAction已迁移至
const count = await getUnreadNotificationCount(ctx.userId) // @/modules/notifications/actions。请直接从 notifications 模块导入。
return { success: true, data: count } // ---------------------------------------------------------------------------
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
export async function getNotificationsAction(
params?: { page?: number; pageSize?: number; unreadOnly?: boolean }
): Promise<ActionState<{ items: Notification[]; total: number; page: number; pageSize: number; totalPages: number }>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_READ)
const result = await getNotifications(ctx.userId, params)
return { success: true, data: result }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
export async function markNotificationAsReadAction(
notificationId: string
): Promise<ActionState<string>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_READ)
await markNotificationAsRead(notificationId, ctx.userId)
revalidatePath("/messages")
return { success: true, message: "Notification marked as read" }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
export async function markAllNotificationsAsReadAction(): Promise<ActionState<string>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_READ)
await markAllNotificationsAsRead(ctx.userId)
revalidatePath("/messages")
return { success: true, message: "All notifications marked as read" }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
export async function getNotificationPreferencesAction(): Promise<ActionState<NotificationPreferences>> { export async function getNotificationPreferencesAction(): Promise<ActionState<NotificationPreferences>> {
try { try {

View File

@@ -23,6 +23,8 @@ import {
import { sendMessageAction } from "../actions" import { sendMessageAction } from "../actions"
import type { RecipientOption } from "../types" import type { RecipientOption } from "../types"
type FieldErrors = Record<string, string[]>
export function MessageCompose({ export function MessageCompose({
recipients, recipients,
parentMessageId, parentMessageId,
@@ -40,10 +42,16 @@ export function MessageCompose({
const router = useRouter() const router = useRouter()
const [isWorking, setIsWorking] = useState(false) const [isWorking, setIsWorking] = useState(false)
const [receiverId, setReceiverId] = useState(defaultReceiverId ?? "") const [receiverId, setReceiverId] = useState(defaultReceiverId ?? "")
const [fieldErrors, setFieldErrors] = useState<FieldErrors>({})
const getFieldError = (field: string): string | null => {
const errs = fieldErrors[field]
return errs && errs.length > 0 ? errs[0] : null
}
const handleSubmit = async (formData: FormData) => { const handleSubmit = async (formData: FormData) => {
if (!receiverId) { if (!receiverId) {
toast.error(t("messages.selectRecipient")) toast.error(t("form.selectRecipient"))
return return
} }
formData.set("receiverId", receiverId) formData.set("receiverId", receiverId)
@@ -52,6 +60,7 @@ export function MessageCompose({
} }
setIsWorking(true) setIsWorking(true)
setFieldErrors({})
try { try {
const res = await sendMessageAction(null, formData) const res = await sendMessageAction(null, formData)
if (res.success) { if (res.success) {
@@ -59,6 +68,10 @@ export function MessageCompose({
router.push("/messages") router.push("/messages")
router.refresh() router.refresh()
} else { } else {
// 展示字段级错误(来自 Zod 校验)
if (res.errors) {
setFieldErrors(res.errors)
}
toast.error(res.message || t("messages.sendFailed")) toast.error(res.message || t("messages.sendFailed"))
} }
} catch { } catch {
@@ -85,7 +98,7 @@ export function MessageCompose({
<div className="grid gap-2"> <div className="grid gap-2">
<Label htmlFor="receiverId">{t("form.to")}</Label> <Label htmlFor="receiverId">{t("form.to")}</Label>
<Select value={receiverId} onValueChange={setReceiverId} disabled={!!defaultReceiverId}> <Select value={receiverId} onValueChange={setReceiverId} disabled={!!defaultReceiverId}>
<SelectTrigger> <SelectTrigger aria-invalid={!!getFieldError("receiverId")}>
<SelectValue placeholder={t("form.toPlaceholder")} /> <SelectValue placeholder={t("form.toPlaceholder")} />
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
@@ -98,6 +111,9 @@ export function MessageCompose({
</SelectContent> </SelectContent>
</Select> </Select>
<input type="hidden" name="receiverId" value={receiverId} /> <input type="hidden" name="receiverId" value={receiverId} />
{getFieldError("receiverId") ? (
<p className="text-destructive text-xs">{getFieldError("receiverId")}</p>
) : null}
</div> </div>
<div className="grid gap-2"> <div className="grid gap-2">
@@ -108,7 +124,11 @@ export function MessageCompose({
placeholder={t("form.subjectPlaceholder")} placeholder={t("form.subjectPlaceholder")}
defaultValue={defaultSubject ?? ""} defaultValue={defaultSubject ?? ""}
maxLength={255} maxLength={255}
aria-invalid={!!getFieldError("subject")}
/> />
{getFieldError("subject") ? (
<p className="text-destructive text-xs">{getFieldError("subject")}</p>
) : null}
</div> </div>
<div className="grid gap-2"> <div className="grid gap-2">
@@ -119,7 +139,11 @@ export function MessageCompose({
placeholder={t("form.contentPlaceholder")} placeholder={t("form.contentPlaceholder")}
className="min-h-[200px]" className="min-h-[200px]"
required required
aria-invalid={!!getFieldError("content")}
/> />
{getFieldError("content") ? (
<p className="text-destructive text-xs">{getFieldError("content")}</p>
) : null}
</div> </div>
<CardFooter className="justify-end gap-2 px-0"> <CardFooter className="justify-end gap-2 px-0">

View File

@@ -1,8 +1,8 @@
"use client" "use client"
import { useEffect, useMemo, useState } from "react" import { useMemo, useState } from "react"
import Link from "next/link" import Link from "next/link"
import { Mail, MailOpen, Plus, Send, Inbox, Search, Loader2 } from "lucide-react" import { Mail, MailOpen, Plus, Send, Inbox, Search, Loader2, ChevronLeft, ChevronRight } from "lucide-react"
import { useTranslations } from "next-intl" import { useTranslations } from "next-intl"
import { Badge } from "@/shared/components/ui/badge" import { Badge } from "@/shared/components/ui/badge"
@@ -16,10 +16,14 @@ import { usePermission } from "@/shared/hooks/use-permission"
import { Permissions } from "@/shared/types/permissions" import { Permissions } from "@/shared/types/permissions"
import { getMessagesAction } from "../actions" import { getMessagesAction } from "../actions"
import { useMessageSearch } from "../hooks/use-message-search"
import type { Message, MessageType } from "../types" import type { Message, MessageType } from "../types"
type Tab = "inbox" | "sent" type Tab = "inbox" | "sent"
/** 客户端分页大小 */
const PAGE_SIZE = 20
export function MessageList({ export function MessageList({
messages, messages,
currentUserId, currentUserId,
@@ -31,54 +35,44 @@ export function MessageList({
}) { }) {
const t = useTranslations("messages") const t = useTranslations("messages")
const [tab, setTab] = useState<Tab>(initialType === "sent" ? "sent" : "inbox") const [tab, setTab] = useState<Tab>(initialType === "sent" ? "sent" : "inbox")
const [keyword, setKeyword] = useState("") const [currentPage, setCurrentPage] = useState(1)
const [searchResults, setSearchResults] = useState<{ kw: string; tab: Tab; items: Message[] } | null>(null)
const { hasPermission } = usePermission() const { hasPermission } = usePermission()
const canSend = hasPermission(Permissions.MESSAGE_SEND) const canSend = hasPermission(Permissions.MESSAGE_SEND)
// 防抖搜索keyword 或 tab 变化时调用 getMessagesAction const { keyword, setKeyword, results, searching, isUsingInitial } = useMessageSearch({
useEffect(() => { searchAction: getMessagesAction,
const kw = keyword.trim() tab,
if (kw.length === 0) { })
return
}
let cancelled = false
const timer = setTimeout(async () => {
if (cancelled) return
const res = await getMessagesAction({ type: tab, keyword: kw })
if (cancelled) return
if (res.success && res.data) {
setSearchResults({ kw, tab, items: res.data.items })
}
}, 400)
return () => {
cancelled = true
clearTimeout(timer)
}
}, [keyword, tab])
// 当前搜索结果是否匹配最新的 keyword 和 tab
const currentResults = searchResults && searchResults.kw === keyword.trim() && searchResults.tab === tab
? searchResults.items
: null
// 搜索中keyword 非空且尚无匹配结果
const searching = keyword.trim().length > 0 && currentResults === null
// 当 keyword 为空时使用 prop messages否则使用搜索结果
const displayMessages = currentResults ?? messages
// 客户端过滤仅在初始数据type=all时需要搜索结果已由服务端按 tab 过滤
const filtered = useMemo(() => { const filtered = useMemo(() => {
const displayMessages = isUsingInitial ? messages : (results ?? [])
if (!isUsingInitial) return displayMessages
if (tab === "inbox") return displayMessages.filter((m) => m.receiverId === currentUserId) if (tab === "inbox") return displayMessages.filter((m) => m.receiverId === currentUserId)
return displayMessages.filter((m) => m.senderId === currentUserId) return displayMessages.filter((m) => m.senderId === currentUserId)
}, [displayMessages, tab, currentUserId]) }, [messages, results, tab, currentUserId, isUsingInitial])
// 客户端分页:超过 PAGE_SIZE 条时显示分页 UI
const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE))
const safePage = Math.min(currentPage, totalPages)
const paged = filtered.slice((safePage - 1) * PAGE_SIZE, safePage * PAGE_SIZE)
const showPagination = filtered.length > PAGE_SIZE
// 切换 tab 或搜索时重置分页
const handleTabChange = (v: string): void => {
setTab(v as Tab)
setCurrentPage(1)
}
const handleKeywordChange = (v: string): void => {
setKeyword(v)
setCurrentPage(1)
}
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-3"> <div className="flex flex-wrap items-center justify-between gap-3">
<Tabs value={tab} onValueChange={(v) => setTab(v as Tab)}> <Tabs value={tab} onValueChange={handleTabChange}>
<TabsList> <TabsList>
<TabsTrigger value="inbox" className="gap-2"> <TabsTrigger value="inbox" className="gap-2">
<Inbox className="h-4 w-4" /> <Inbox className="h-4 w-4" />
@@ -108,7 +102,7 @@ export function MessageList({
aria-label={t("search.placeholder")} aria-label={t("search.placeholder")}
placeholder={t("search.placeholder")} placeholder={t("search.placeholder")}
value={keyword} value={keyword}
onChange={(e) => setKeyword(e.target.value)} onChange={(e) => handleKeywordChange(e.target.value)}
className="pl-9" className="pl-9"
/> />
{searching ? ( {searching ? (
@@ -116,7 +110,7 @@ export function MessageList({
) : null} ) : null}
</div> </div>
{filtered.length === 0 ? ( {paged.length === 0 ? (
<EmptyState <EmptyState
title={tab === "inbox" ? t("empty.inboxEmpty") : t("empty.sentEmpty")} title={tab === "inbox" ? t("empty.inboxEmpty") : t("empty.sentEmpty")}
description={ description={
@@ -128,45 +122,73 @@ export function MessageList({
className="h-auto border-none shadow-none" className="h-auto border-none shadow-none"
/> />
) : ( ) : (
<div className="space-y-3"> <>
{filtered.map((m) => { <div className="space-y-3">
const isReceived = m.receiverId === currentUserId {paged.map((m) => {
const counterpart = isReceived ? m.senderName : m.receiverName const isReceived = m.receiverId === currentUserId
const unread = isReceived && !m.isRead const counterpart = isReceived ? m.senderName : m.receiverName
return ( const unread = isReceived && !m.isRead
<Link key={m.id} href={`/messages/${m.id}`} className="block" aria-label={m.subject ?? t("meta.noSubject")}> return (
<Card className={cn("transition-colors hover:bg-accent/50", unread && "border-primary/40")}> <Link key={m.id} href={`/messages/${m.id}`} className="block" aria-label={m.subject ?? t("meta.noSubject")}>
<CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0 pb-3"> <Card className={cn("transition-colors hover:bg-accent/50", unread && "border-primary/40")}>
<div className="space-y-1"> <CardHeader className="flex flex-row items-start justify-between gap-2 space-y-0 pb-3">
<div className="flex items-center gap-2"> <div className="space-y-1">
{unread ? ( <div className="flex items-center gap-2">
<Mail className="h-4 w-4 text-primary" aria-hidden="true" /> {unread ? (
) : ( <Mail className="h-4 w-4 text-primary" aria-hidden="true" />
<MailOpen className="text-muted-foreground h-4 w-4" aria-hidden="true" /> ) : (
)} <MailOpen className="text-muted-foreground h-4 w-4" aria-hidden="true" />
<span className={cn("text-sm font-medium", unread && "text-primary")}> )}
{m.subject ?? t("meta.noSubject")} <span className={cn("text-sm font-medium", unread && "text-primary")}>
</span> {m.subject ?? t("meta.noSubject")}
{unread ? <Badge variant="default" className="text-xs">{t("status.new")}</Badge> : null} </span>
{unread ? <Badge variant="default" className="text-xs">{t("status.new")}</Badge> : null}
</div>
<p className="text-muted-foreground text-xs">
{isReceived ? t("meta.from") : t("meta.to")}: {counterpart ?? t("meta.unknown")}
</p>
</div> </div>
<p className="text-muted-foreground text-xs"> <span className="text-muted-foreground shrink-0 text-xs">
{isReceived ? t("meta.from") : t("meta.to")}: {counterpart ?? t("meta.unknown")} {formatDate(m.createdAt)}
</span>
</CardHeader>
<CardContent className="pt-0">
<p className="text-muted-foreground line-clamp-2 text-sm whitespace-pre-wrap">
{m.content}
</p> </p>
</div> </CardContent>
<span className="text-muted-foreground shrink-0 text-xs"> </Card>
{formatDate(m.createdAt)} </Link>
</span> )
</CardHeader> })}
<CardContent className="pt-0"> </div>
<p className="text-muted-foreground line-clamp-2 text-sm whitespace-pre-wrap">
{m.content} {showPagination ? (
</p> <div className="flex items-center justify-center gap-4 pt-2" role="navigation" aria-label={t("tabs.inbox")}>
</CardContent> <Button
</Card> variant="outline"
</Link> size="sm"
) onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
})} disabled={safePage <= 1}
</div> aria-label="Previous page"
>
<ChevronLeft className="h-4 w-4" />
</Button>
<span className="text-muted-foreground text-sm" aria-live="polite">
{safePage} / {totalPages}
</span>
<Button
variant="outline"
size="sm"
onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
disabled={safePage >= totalPages}
aria-label="Next page"
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
) : null}
</>
)} )}
</div> </div>
) )

View File

@@ -6,11 +6,14 @@ import { Badge } from "@/shared/components/ui/badge"
import { getUnreadMessageCountAction } from "../actions" import { getUnreadMessageCountAction } from "../actions"
/** 未读消息计数轮询间隔(毫秒) */
const POLL_INTERVAL_MS = 60_000
/** /**
* 未读消息计数徽章 * 未读消息计数徽章
* *
* 在侧边栏 Messages 导航项旁显示未读私信数。 * 在侧边栏 Messages 导航项旁显示未读私信数。
* 每 60 秒轮询一次以保持计数更新。 * 每 POLL_INTERVAL_MS 毫秒轮询一次以保持计数更新。
*/ */
export function UnreadMessageBadge() { export function UnreadMessageBadge() {
const [count, setCount] = useState(0) const [count, setCount] = useState(0)
@@ -30,7 +33,7 @@ export function UnreadMessageBadge() {
const timer = setInterval(() => { const timer = setInterval(() => {
void fetchCount() void fetchCount()
}, 60_000) }, POLL_INTERVAL_MS)
return () => { return () => {
active = false active = false

View File

@@ -180,14 +180,17 @@ export async function markMessageAsRead(id: string, userId: string): Promise<voi
export async function deleteMessage(id: string, userId: string): Promise<void> { export async function deleteMessage(id: string, userId: string): Promise<void> {
const now = new Date() const now = new Date()
// 软删除:发送方删除设置 senderDeletedAt接收方删除设置 receiverDeletedAt互不影响 // 软删除:发送方删除设置 senderDeletedAt接收方删除设置 receiverDeletedAt互不影响
await db // 使用事务保证两次 UPDATE 的原子性,避免部分失败导致数据不一致
.update(messages) await db.transaction(async (tx) => {
.set({ senderDeletedAt: now }) await tx
.where(and(eq(messages.id, id), eq(messages.senderId, userId))) .update(messages)
await db .set({ senderDeletedAt: now })
.update(messages) .where(and(eq(messages.id, id), eq(messages.senderId, userId)))
.set({ receiverDeletedAt: now }) await tx
.where(and(eq(messages.id, id), eq(messages.receiverId, userId))) .update(messages)
.set({ receiverDeletedAt: now })
.where(and(eq(messages.id, id), eq(messages.receiverId, userId)))
})
} }
export const getUnreadMessageCount = cache(async (userId: string): Promise<number> => { export const getUnreadMessageCount = cache(async (userId: string): Promise<number> => {
@@ -244,3 +247,44 @@ export const getRecipients = cache(
return [] return []
} }
) )
/**
* 消息首页编排函数:一次性获取消息列表和通知列表。
* 将原本散落在 page.tsx 中的多模块编排逻辑下沉到 data-access 层,
* 页面层只需调用单一函数,提升可复用性与可测试性。
*/
export async function getMessagesPageData(userId: string): Promise<{
messages: { items: Message[]; total: number; page: number; pageSize: number; totalPages: number }
notifications: { items: import("@/modules/notifications/types").Notification[]; total: number; page: number; pageSize: number; totalPages: number }
}> {
const { getNotifications } = await import("@/modules/notifications/data-access")
const [messagesResult, notificationsResult] = await Promise.all([
getMessages({ userId, type: "all", page: 1, pageSize: 50 }),
getNotifications(userId, { page: 1, pageSize: 20 }),
])
return {
messages: messagesResult,
notifications: notificationsResult,
}
}
/**
* 消息详情页编排函数:获取消息详情,并自动标记为已读(若当前用户为接收方且未读)。
* 使用 next/server 的 after() 实现非阻塞标记,避免阻塞页面渲染。
*/
export async function getMessageDetailPageData(
id: string,
userId: string
): Promise<Message | null> {
const message = await getMessageById(id, userId)
if (!message) return null
// 自动标记已读:仅当当前用户为接收方且消息未读时
if (!message.isRead && message.receiverId === userId) {
await markMessageAsRead(id, userId)
}
return message
}

View File

@@ -0,0 +1,106 @@
"use client"
import { useEffect, useRef, useState } from "react"
import type { ActionState } from "@/shared/types/action-state"
import type { Message, MessageType } from "../types"
type SearchMessagesResult = ActionState<{
items: Message[]
total: number
page: number
pageSize: number
totalPages: number
}>
interface UseMessageSearchParams {
/** 搜索动作(注入的接口,避免组件直接依赖具体 action */
searchAction: (params: {
type: MessageType
keyword: string
page?: number
pageSize?: number
}) => Promise<SearchMessagesResult>
/** 当前标签页 */
tab: "inbox" | "sent"
/** 防抖延迟(毫秒),默认 400 */
debounceMs?: number
}
interface UseMessageSearchResult {
keyword: string
setKeyword: (v: string) => void
results: Message[] | null
searching: boolean
/** 当前 keyword 为空时为 true表示应使用 prop 传入的初始消息 */
isUsingInitial: boolean
}
/**
* 消息搜索 hook将搜索逻辑从 MessageList 组件抽离为独立 hook
* 提升可测试性与可复用性。支持防抖、请求取消、状态匹配。
*
* 使用方式:
* const { keyword, setKeyword, results, searching } = useMessageSearch({
* searchAction: getMessagesAction,
* tab,
* })
*/
export function useMessageSearch({
searchAction,
tab,
debounceMs = 400,
}: UseMessageSearchParams): UseMessageSearchResult {
const [keyword, setKeyword] = useState("")
const [results, setResults] = useState<Message[] | null>(null)
const [searching, setSearching] = useState(false)
const requestIdRef = useRef(0)
useEffect(() => {
const kw = keyword.trim()
if (kw.length === 0) {
setResults(null)
setSearching(false)
return
}
setSearching(true)
const currentRequestId = ++requestIdRef.current
const timer = setTimeout(async () => {
// 在异步执行前检查是否已被后续请求取代
if (currentRequestId !== requestIdRef.current) return
try {
const res = await searchAction({ type: tab, keyword: kw })
// 请求返回后再次检查,避免竞态
if (currentRequestId !== requestIdRef.current) return
if (res.success && res.data) {
setResults(res.data.items)
} else {
setResults([])
}
} catch {
if (currentRequestId !== requestIdRef.current) return
setResults([])
} finally {
if (currentRequestId === requestIdRef.current) {
setSearching(false)
}
}
}, debounceMs)
return () => {
clearTimeout(timer)
}
}, [keyword, tab, searchAction, debounceMs])
const isUsingInitial = keyword.trim().length === 0
return {
keyword,
setKeyword,
results,
searching,
isUsingInitial,
}
}

View File

@@ -5,21 +5,31 @@
* *
* - sendNotificationAction: 发送通知给指定用户(需要 MESSAGE_SEND 权限) * - sendNotificationAction: 发送通知给指定用户(需要 MESSAGE_SEND 权限)
* - sendClassNotificationAction: 发送班级通知(教师权限,按班级查询学生后批量发送) * - sendClassNotificationAction: 发送班级通知(教师权限,按班级查询学生后批量发送)
* - getNotificationsAction / markNotificationAsReadAction / markAllNotificationsAsReadAction / getUnreadNotificationCountAction: 站内通知 CRUD
* *
* 权限说明: * 权限说明:
* 项目无独立 NOTIFICATION_SEND 权限点,复用 MESSAGE_SEND教师/管理员/年级主任均拥有)。 * 项目无独立 NOTIFICATION_SEND 权限点,复用 MESSAGE_SEND教师/管理员/年级主任均拥有)。
* 班级通知按教师所教班级过滤,确保教师只能给自己班级发通知。 * 班级通知按教师所教班级过滤,确保教师只能给自己班级发通知。
* 站内通知读取/标记已读复用 MESSAGE_READ 权限(任何能读消息的用户都能查看通知)。
*/ */
import { revalidatePath } from "next/cache"
import { z } from "zod" import { z } from "zod"
import { PermissionDeniedError, requirePermission } from "@/shared/lib/auth-guard" import { PermissionDeniedError, requirePermission } from "@/shared/lib/auth-guard"
import { trackEvent } from "@/shared/lib/track-event"
import { Permissions } from "@/shared/types/permissions" import { Permissions } from "@/shared/types/permissions"
import type { ActionState } from "@/shared/types/action-state" import type { ActionState } from "@/shared/types/action-state"
import { getClassExists, getStudentIdsByClassId } from "@/modules/classes/data-access" import { getClassExists, getStudentIdsByClassId } from "@/modules/classes/data-access"
import { sendNotification, sendBatchNotifications } from "./dispatcher" import { sendNotification, sendBatchNotifications } from "./dispatcher"
import type { NotificationPayload, ChannelSendResult } from "./types" import {
getNotifications,
markNotificationAsRead,
markAllNotificationsAsRead,
getUnreadNotificationCount,
} from "./data-access"
import type { NotificationPayload, ChannelSendResult, Notification } from "./types"
/** /**
* Zod 校验通知负载sendNotificationAction 入参) * Zod 校验通知负载sendNotificationAction 入参)
@@ -157,3 +167,101 @@ export async function sendClassNotificationAction(
return { success: false, message: "Unexpected error" } return { success: false, message: "Unexpected error" }
} }
} }
// ---------------------------------------------------------------------------
// 站内通知 CRUD Server Actions
//
// 这些 Action 从 messaging/actions.ts 迁移而来,使 notifications 模块成为
// 通知相关 UI 组件的唯一数据来源,消除 messaging 与 notifications 在 UI 层
// 的双向耦合。权限复用 MESSAGE_READ任何能读消息的用户都能查看通知
// ---------------------------------------------------------------------------
/** Zod 校验:通知 ID 路径参数 */
const NotificationIdSchema = z.string().trim().min(1)
/**
* 获取当前用户的通知列表(分页)。
*/
export async function getNotificationsAction(
params?: { page?: number; pageSize?: number; unreadOnly?: boolean }
): Promise<ActionState<{ items: Notification[]; total: number; page: number; pageSize: number; totalPages: number }>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_READ)
const result = await getNotifications(ctx.userId, params)
return { success: true, data: result }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
/**
* 获取当前用户的未读通知计数。
*/
export async function getUnreadNotificationCountAction(): Promise<ActionState<number>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_READ)
const count = await getUnreadNotificationCount(ctx.userId)
return { success: true, data: count }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
/**
* 将单条通知标记为已读。
*/
export async function markNotificationAsReadAction(
notificationId: string
): Promise<ActionState<string>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_READ)
const parsed = NotificationIdSchema.safeParse(notificationId)
if (!parsed.success) {
return { success: false, message: "Invalid notification id" }
}
await markNotificationAsRead(parsed.data, ctx.userId)
revalidatePath("/messages")
void trackEvent({
event: "notification.marked_read",
userId: ctx.userId,
targetId: parsed.data,
targetType: "notification",
})
return { success: true, message: "Notification marked as read" }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}
/**
* 将当前用户的所有未读通知标记为已读。
*/
export async function markAllNotificationsAsReadAction(): Promise<ActionState<string>> {
try {
const ctx = await requirePermission(Permissions.MESSAGE_READ)
await markAllNotificationsAsRead(ctx.userId)
revalidatePath("/messages")
void trackEvent({
event: "notification.marked_all_read",
userId: ctx.userId,
targetType: "notification",
})
return { success: true, message: "All notifications marked as read" }
} catch (e) {
if (e instanceof PermissionDeniedError) return { success: false, message: e.message }
if (e instanceof Error) return { success: false, message: e.message }
return { success: false, message: "Unexpected error" }
}
}

View File

@@ -0,0 +1,2 @@
export { NotificationList } from "./notification-list"
export { NotificationDropdown } from "./notification-dropdown"

View File

@@ -25,7 +25,7 @@ import {
markAllNotificationsAsReadAction, markAllNotificationsAsReadAction,
markNotificationAsReadAction, markNotificationAsReadAction,
} from "../actions" } from "../actions"
import type { Notification, NotificationType } from "@/modules/notifications/types" import type { Notification, NotificationType } from "../types"
const TYPE_ICON: Record<NotificationType, typeof Bell> = { const TYPE_ICON: Record<NotificationType, typeof Bell> = {
message: MessageSquare, message: MessageSquare,
@@ -34,8 +34,11 @@ const TYPE_ICON: Record<NotificationType, typeof Bell> = {
grade: GraduationCap, grade: GraduationCap,
} }
/** 通知下拉菜单轮询间隔(毫秒) */
const POLL_INTERVAL_MS = 30_000
export function NotificationDropdown() { export function NotificationDropdown() {
const t = useTranslations("messages") const t = useTranslations("notifications")
const router = useRouter() const router = useRouter()
const [notifications, setNotifications] = useState<Notification[]>([]) const [notifications, setNotifications] = useState<Notification[]>([])
const [unreadCount, setUnreadCount] = useState(0) const [unreadCount, setUnreadCount] = useState(0)
@@ -63,11 +66,11 @@ export function NotificationDropdown() {
void fetchNotifications() void fetchNotifications()
void fetchUnreadCount() void fetchUnreadCount()
// 每 30 秒轮询刷新通知和未读计数 // 每 POLL_INTERVAL_MS 毫秒轮询刷新通知和未读计数
const timer = setInterval(() => { const timer = setInterval(() => {
void fetchNotifications() void fetchNotifications()
void fetchUnreadCount() void fetchUnreadCount()
}, 30_000) }, POLL_INTERVAL_MS)
return () => { return () => {
active = false active = false
@@ -98,7 +101,7 @@ export function NotificationDropdown() {
return ( return (
<DropdownMenu open={open} onOpenChange={setOpen}> <DropdownMenu open={open} onOpenChange={setOpen}>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon" className="relative text-muted-foreground" aria-label={t("title.notifications")}> <Button variant="ghost" size="icon" className="relative text-muted-foreground" aria-label={t("title.dropdown")}>
<Bell className="size-5" aria-hidden="true" /> <Bell className="size-5" aria-hidden="true" />
{unreadCount > 0 ? ( {unreadCount > 0 ? (
<Badge <Badge
@@ -108,12 +111,12 @@ export function NotificationDropdown() {
{unreadCount > 9 ? "9+" : unreadCount} {unreadCount > 9 ? "9+" : unreadCount}
</Badge> </Badge>
) : null} ) : null}
<span className="sr-only">{t("title.notifications")}</span> <span className="sr-only">{t("title.dropdown")}</span>
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-80 p-0"> <DropdownMenuContent align="end" className="w-80 p-0">
<DropdownMenuLabel className="flex items-center justify-between"> <DropdownMenuLabel className="flex items-center justify-between">
<span>{t("title.notifications")}</span> <span>{t("title.dropdown")}</span>
{unreadCount > 0 ? ( {unreadCount > 0 ? (
<button <button
type="button" type="button"

View File

@@ -14,7 +14,7 @@ import { EmptyState } from "@/shared/components/ui/empty-state"
import { cn, formatDate } from "@/shared/lib/utils" import { cn, formatDate } from "@/shared/lib/utils"
import { markAllNotificationsAsReadAction, markNotificationAsReadAction } from "../actions" import { markAllNotificationsAsReadAction, markNotificationAsReadAction } from "../actions"
import type { Notification, NotificationType } from "@/modules/notifications/types" import type { Notification, NotificationType } from "../types"
const TYPE_ICON: Record<NotificationType, typeof Bell> = { const TYPE_ICON: Record<NotificationType, typeof Bell> = {
message: MessageSquare, message: MessageSquare,
@@ -24,7 +24,7 @@ const TYPE_ICON: Record<NotificationType, typeof Bell> = {
} }
export function NotificationList({ notifications }: { notifications: Notification[] }) { export function NotificationList({ notifications }: { notifications: Notification[] }) {
const t = useTranslations("messages") const t = useTranslations("notifications")
const router = useRouter() const router = useRouter()
const [isWorking, setIsWorking] = useState(false) const [isWorking, setIsWorking] = useState(false)
const hasUnread = notifications.some((n) => !n.isRead) const hasUnread = notifications.some((n) => !n.isRead)
@@ -61,8 +61,8 @@ export function NotificationList({ notifications }: { notifications: Notificatio
<div className="space-y-6"> <div className="space-y-6">
<div className="flex flex-wrap items-center justify-between gap-3"> <div className="flex flex-wrap items-center justify-between gap-3">
<div> <div>
<h2 className="text-2xl font-bold tracking-tight">{t("title.notifications")}</h2> <h2 className="text-2xl font-bold tracking-tight">{t("title.list")}</h2>
<p className="text-muted-foreground text-sm">{t("description.notifications")}</p> <p className="text-muted-foreground text-sm">{t("description.list")}</p>
</div> </div>
{hasUnread ? ( {hasUnread ? (
<Button onClick={handleMarkAllRead} disabled={isWorking} variant="outline"> <Button onClick={handleMarkAllRead} disabled={isWorking} variant="outline">
@@ -106,7 +106,7 @@ export function NotificationList({ notifications }: { notifications: Notificatio
) : null} ) : null}
<div className="flex items-center gap-2 text-xs text-muted-foreground"> <div className="flex items-center gap-2 text-xs text-muted-foreground">
<Badge variant="outline" className="text-xs"> <Badge variant="outline" className="text-xs">
{t(`notificationType.${n.type}`)} {t(`type.${n.type}`)}
</Badge> </Badge>
<span>{formatDate(n.createdAt)}</span> <span>{formatDate(n.createdAt)}</span>
{!n.isRead ? ( {!n.isRead ? (

View File

@@ -5,6 +5,8 @@
* - sendNotification / sendBatchNotifications: 分发器入口 * - sendNotification / sendBatchNotifications: 分发器入口
* - createNotification / getNotifications / markNotificationAsRead / markAllNotificationsAsRead / getUnreadNotificationCount: 站内通知 CRUD * - createNotification / getNotifications / markNotificationAsRead / markAllNotificationsAsRead / getUnreadNotificationCount: 站内通知 CRUD
* - getNotificationPreferences / upsertNotificationPreferences: 通知偏好 CRUD * - getNotificationPreferences / upsertNotificationPreferences: 通知偏好 CRUD
* - Server Actions: sendNotificationAction / sendClassNotificationAction / getNotificationsAction / markNotificationAsReadAction / markAllNotificationsAsReadAction / getUnreadNotificationCountAction
* - UI 组件: NotificationList / NotificationDropdown
* - 类型定义: NotificationPayload, ChannelSendResult, NotificationChannel, NotificationType, Notification, NotificationPreferences 等 * - 类型定义: NotificationPayload, ChannelSendResult, NotificationChannel, NotificationType, Notification, NotificationPreferences 等
* - 渠道发送器工厂: createSmsSender, createWechatSender, createEmailSender, createInAppSender * - 渠道发送器工厂: createSmsSender, createWechatSender, createEmailSender, createInAppSender
* *
@@ -36,6 +38,15 @@ export {
getNotificationPreferences, getNotificationPreferences,
upsertNotificationPreferences, upsertNotificationPreferences,
} from "./preferences" } from "./preferences"
export {
sendNotificationAction,
sendClassNotificationAction,
getNotificationsAction,
getUnreadNotificationCountAction,
markNotificationAsReadAction,
markAllNotificationsAsReadAction,
} from "./actions"
export { NotificationList, NotificationDropdown } from "./components"
export type { export type {
NotificationChannel, NotificationChannel,
NotificationPayload, NotificationPayload,

View File

@@ -82,6 +82,10 @@
"deleteTitle": "Delete announcement", "deleteTitle": "Delete announcement",
"deleteDesc": "This will permanently delete \"{title}\"." "deleteDesc": "This will permanently delete \"{title}\"."
}, },
"notification": {
"publishedTitle": "New announcement: {title}",
"publishedContent": "You have a new announcement. Please review it."
},
"error": { "error": {
"loadFailed": "Failed to load announcements", "loadFailed": "Failed to load announcements",
"loadFailedDesc": "Sorry, an unexpected error occurred while loading announcements. Please try again later.", "loadFailedDesc": "Sorry, an unexpected error occurred while loading announcements. Please try again later.",

View File

@@ -4,13 +4,11 @@
"detail": "Message", "detail": "Message",
"compose": "Compose Message", "compose": "Compose Message",
"reply": "Reply", "reply": "Reply",
"newMessage": "New Message", "newMessage": "New Message"
"notifications": "Notifications"
}, },
"description": { "description": {
"list": "Manage your inbox and stay updated with notifications.", "list": "Manage your inbox and stay updated with notifications.",
"compose": "Send a message to another user.", "compose": "Send a message to another user."
"notifications": "Stay updated on your latest activities."
}, },
"tabs": { "tabs": {
"inbox": "Inbox", "inbox": "Inbox",
@@ -20,14 +18,10 @@
"compose": "Compose", "compose": "Compose",
"reply": "Reply", "reply": "Reply",
"delete": "Delete", "delete": "Delete",
"markRead": "Mark as read",
"markAllRead": "Mark all as read",
"send": "Send", "send": "Send",
"sending": "Sending...", "sending": "Sending...",
"cancel": "Cancel", "cancel": "Cancel",
"back": "Back", "back": "Back"
"viewAll": "View all notifications",
"view": "View"
}, },
"form": { "form": {
"to": "To", "to": "To",
@@ -51,12 +45,6 @@
"noSubject": "(no subject)", "noSubject": "(no subject)",
"readAt": "Read {date}" "readAt": "Read {date}"
}, },
"notificationType": {
"message": "Message",
"announcement": "Announcement",
"homework": "Homework",
"grade": "Grade"
},
"search": { "search": {
"placeholder": "Search messages by subject or content...", "placeholder": "Search messages by subject or content...",
"noResults": "No matching messages found" "noResults": "No matching messages found"
@@ -66,9 +54,6 @@
"inboxEmptyDesc": "You have no incoming messages yet.", "inboxEmptyDesc": "You have no incoming messages yet.",
"sentEmpty": "No sent messages", "sentEmpty": "No sent messages",
"sentEmptyDesc": "You have not sent any messages yet.", "sentEmptyDesc": "You have not sent any messages yet.",
"noNotifications": "No notifications",
"noNotificationsDesc": "You have no notifications yet.",
"noNotificationsDropdown": "No notifications",
"deleteTitle": "Delete message", "deleteTitle": "Delete message",
"deleteDesc": "This will permanently delete the message \"{subject}\"." "deleteDesc": "This will permanently delete the message \"{subject}\"."
}, },
@@ -76,16 +61,17 @@
"sent": "Message sent", "sent": "Message sent",
"deleted": "Message deleted", "deleted": "Message deleted",
"markedRead": "Marked as read", "markedRead": "Marked as read",
"allMarkedRead": "All notifications marked as read",
"notificationMarkedRead": "Notification marked as read",
"sendSelf": "Cannot send a message to yourself", "sendSelf": "Cannot send a message to yourself",
"sendFailed": "Failed to send message", "sendFailed": "Failed to send message",
"deleteFailed": "Failed to delete", "deleteFailed": "Failed to delete",
"markReadFailed": "Failed to mark as read",
"notFound": "Message not found", "notFound": "Message not found",
"invalidId": "Invalid message id", "invalidId": "Invalid message id",
"selectRecipient": "Please select a recipient" "selectRecipient": "Please select a recipient"
}, },
"notification": {
"messageTitle": "New message: {subject}",
"messageTitleNoSubject": "New message"
},
"error": { "error": {
"loadFailed": "Failed to load messages", "loadFailed": "Failed to load messages",
"loadFailedDesc": "Sorry, an unexpected error occurred while loading messages. Please try again later.", "loadFailedDesc": "Sorry, an unexpected error occurred while loading messages. Please try again later.",

View File

@@ -0,0 +1,39 @@
{
"title": {
"list": "Notifications",
"dropdown": "Notifications"
},
"description": {
"list": "Stay updated on your latest activities."
},
"actions": {
"markRead": "Mark as read",
"markAllRead": "Mark all as read",
"viewAll": "View all notifications",
"view": "View"
},
"type": {
"message": "Message",
"announcement": "Announcement",
"homework": "Homework",
"grade": "Grade"
},
"status": {
"new": "New"
},
"empty": {
"noNotifications": "No notifications",
"noNotificationsDesc": "You have no notifications yet.",
"noNotificationsDropdown": "No notifications"
},
"messages": {
"allMarkedRead": "All notifications marked as read",
"notificationMarkedRead": "Notification marked as read",
"markReadFailed": "Failed to mark as read"
},
"error": {
"loadFailed": "Failed to load notifications",
"loadFailedDesc": "Sorry, an unexpected error occurred while loading notifications. Please try again later.",
"retry": "Retry"
}
}

View File

@@ -80,7 +80,11 @@
"noAnnouncementsDesc": "目前还没有任何公告。", "noAnnouncementsDesc": "目前还没有任何公告。",
"noMatch": "当前筛选条件下暂无公告。", "noMatch": "当前筛选条件下暂无公告。",
"deleteTitle": "删除公告", "deleteTitle": "删除公告",
"deleteDesc": "此操作将永久删除"{title}"。" "deleteDesc": "此操作将永久删除公告{title}。"
},
"notification": {
"publishedTitle": "新公告:{title}",
"publishedContent": "您有一条新公告,请及时查看。"
}, },
"error": { "error": {
"loadFailed": "公告加载失败", "loadFailed": "公告加载失败",

View File

@@ -4,13 +4,11 @@
"detail": "消息详情", "detail": "消息详情",
"compose": "撰写消息", "compose": "撰写消息",
"reply": "回复", "reply": "回复",
"newMessage": "新消息", "newMessage": "新消息"
"notifications": "通知"
}, },
"description": { "description": {
"list": "管理收件箱并随时掌握通知动态。", "list": "管理收件箱并随时掌握通知动态。",
"compose": "向其他用户发送消息。", "compose": "向其他用户发送消息。"
"notifications": "随时了解最新动态。"
}, },
"tabs": { "tabs": {
"inbox": "收件箱", "inbox": "收件箱",
@@ -20,14 +18,10 @@
"compose": "撰写", "compose": "撰写",
"reply": "回复", "reply": "回复",
"delete": "删除", "delete": "删除",
"markRead": "标记已读",
"markAllRead": "全部标记已读",
"send": "发送", "send": "发送",
"sending": "发送中...", "sending": "发送中...",
"cancel": "取消", "cancel": "取消",
"back": "返回", "back": "返回"
"viewAll": "查看全部通知",
"view": "查看"
}, },
"form": { "form": {
"to": "收件人", "to": "收件人",
@@ -51,12 +45,6 @@
"noSubject": "(无主题)", "noSubject": "(无主题)",
"readAt": "阅读于 {date}" "readAt": "阅读于 {date}"
}, },
"notificationType": {
"message": "消息",
"announcement": "公告",
"homework": "作业",
"grade": "成绩"
},
"search": { "search": {
"placeholder": "按主题或内容搜索消息...", "placeholder": "按主题或内容搜索消息...",
"noResults": "未找到匹配的消息" "noResults": "未找到匹配的消息"
@@ -66,26 +54,24 @@
"inboxEmptyDesc": "您还没有收到任何消息。", "inboxEmptyDesc": "您还没有收到任何消息。",
"sentEmpty": "无已发送消息", "sentEmpty": "无已发送消息",
"sentEmptyDesc": "您还没有发送任何消息。", "sentEmptyDesc": "您还没有发送任何消息。",
"noNotifications": "暂无通知",
"noNotificationsDesc": "您还没有任何通知。",
"noNotificationsDropdown": "暂无通知",
"deleteTitle": "删除消息", "deleteTitle": "删除消息",
"deleteDesc": "此操作将永久删除消息"{subject}"。" "deleteDesc": "此操作将永久删除消息{subject}。"
}, },
"messages": { "messages": {
"sent": "消息已发送", "sent": "消息已发送",
"deleted": "消息已删除", "deleted": "消息已删除",
"markedRead": "已标记为已读", "markedRead": "已标记为已读",
"allMarkedRead": "全部已标记为已读",
"notificationMarkedRead": "通知已标记为已读",
"sendSelf": "不能给自己发送消息", "sendSelf": "不能给自己发送消息",
"sendFailed": "发送消息失败", "sendFailed": "发送消息失败",
"deleteFailed": "删除失败", "deleteFailed": "删除失败",
"markReadFailed": "标记已读失败",
"notFound": "消息不存在", "notFound": "消息不存在",
"invalidId": "消息 ID 无效", "invalidId": "消息 ID 无效",
"selectRecipient": "请选择收件人" "selectRecipient": "请选择收件人"
}, },
"notification": {
"messageTitle": "新消息:{subject}",
"messageTitleNoSubject": "新消息"
},
"error": { "error": {
"loadFailed": "消息加载失败", "loadFailed": "消息加载失败",
"loadFailedDesc": "抱歉,加载消息时发生了意外错误。请稍后重试。", "loadFailedDesc": "抱歉,加载消息时发生了意外错误。请稍后重试。",

View File

@@ -0,0 +1,39 @@
{
"title": {
"list": "通知",
"dropdown": "通知"
},
"description": {
"list": "随时了解最新动态。"
},
"actions": {
"markRead": "标记已读",
"markAllRead": "全部标记已读",
"viewAll": "查看全部通知",
"view": "查看"
},
"type": {
"message": "消息",
"announcement": "公告",
"homework": "作业",
"grade": "成绩"
},
"status": {
"new": "新"
},
"empty": {
"noNotifications": "暂无通知",
"noNotificationsDesc": "您还没有任何通知。",
"noNotificationsDropdown": "暂无通知"
},
"messages": {
"allMarkedRead": "全部已标记为已读",
"notificationMarkedRead": "通知已标记为已读",
"markReadFailed": "标记已读失败"
},
"error": {
"loadFailed": "通知加载失败",
"loadFailedDesc": "抱歉,加载通知时发生了意外错误。请稍后重试。",
"retry": "重试"
}
}