diff --git a/docs/architecture/004_architecture_impact_map.md b/docs/architecture/004_architecture_impact_map.md index dc176ce..4f1da38 100644 --- a/docs/architecture/004_architecture_impact_map.md +++ b/docs/architecture/004_architecture_impact_map.md @@ -636,39 +636,50 @@ src/auth.ts ──▶ import { ... } from "@/shared/lib/permissions" **职责**:教材与知识体系管理(教材/章节树形结构、知识点 CRUD、Markdown 内容编辑、知识图谱)。 **导出函数**: -- Actions(10 个,均为写操作;读操作由 RSC 页面直接调用 data-access):`createTextbookAction` / `updateTextbookAction` / `deleteTextbookAction` / `createChapterAction` / `updateChapterContentAction` / `deleteChapterAction` / `reorderChaptersAction` / `createKnowledgePointAction` / `updateKnowledgePointAction` / `deleteKnowledgePointAction` -- Data-access:`getTextbooks` / `getTextbookById` / `getChaptersByTextbookId` / `getKnowledgePointsByChapterId` / `getKnowledgePointsByTextbookId` / `createTextbook` / `updateTextbook` / `deleteTextbook` / `createChapter` / `updateChapterContent` / `deleteChapter` / `createKnowledgePoint` / `updateKnowledgePoint` / `deleteKnowledgePoint` / `reorderChapters` / `getTextbooksDashboardStats` / `getKnowledgePointOptions`(跨模块接口,供 questions 调用) +- Actions(11 个,均为写操作;读操作由 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 调用)/ `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` - 被依赖:`questions`(✅ P1-1 已修复:通过 textbooks data-access)、`exams`(通过类型)、`dashboard`(通过 data-access,P0-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 层) - ✅ actions 层编排模式标杆(权限校验 → 调用 data-access → revalidatePath) - ✅ data-access 层职责单一 - ✅ P2 已修复:`data-access.ts` 中 `byId.get(pid)!.children.push` 非空断言清理为安全守卫;`or(...)!` 非空断言清理为条件 push -- ⚠️ P0 跨模块 UI 依赖:`knowledge-point-dialogs.tsx` 直接 import questions 模块组件 -- ⚠️ P0 前端权限硬编码:`canEdit={true}` 按路由写死,未用 `usePermission().hasPermission()` -- ⚠️ P0 全模块零 i18n:中英文文案硬编码,未接入 next-intl -- ⚠️ P1 Server Action 未校验资源归属(chapterId 是否属于 textbookId) -- ⚠️ P1 data-access 缺数据范围过滤(学生端未按年级过滤) -- ⚠️ P1 缺 Error Boundary(无 error.tsx) -- ⚠️ P1 知识点列表/弹窗存在重复实现(knowledge-point-panel.tsx 无调用方) -- ⚠️ P1 学科/年级选项硬编码三处且彼此不一致 -- ⚠️ P1 纯逻辑未导出,零单测 +- ✅ P0 跨模块 UI 依赖已修复:`knowledge-point-dialogs.tsx` 通过 render prop 解耦,不再直接 import questions 模块 +- ✅ P0 前端权限硬编码已修复:改用 `usePermission().hasPermission()` +- ✅ P0 i18n 已基本接入:`chapter-sidebar-list.tsx` / `actions.ts` / `section-error-boundary.tsx`(默认值改英文)均已接入 next-intl +- ✅ P1 Server Action 资源归属校验已修复:新增 `verifyChapterBelongsToTextbook` / `verifyKnowledgePointBelongsToTextbook` +- ✅ P1 data-access 数据范围过滤已修复:新增 `getTextbooksWithScope`,学生端强制按年级过滤 +- ✅ P1 Error Boundary 已补齐:新增 `section-error-boundary.tsx` +- ✅ P1 知识点列表/弹窗重复实现已清理:移除无调用方的 `knowledge-point-panel.tsx` +- ✅ P1 学科/年级选项统一:抽取到 `constants.ts`(`SUBJECTS` / `GRADES` / `SUBJECT_COLORS`) +- ✅ 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(写操作) | -| `data-access.ts` | 514 | 教材/章节/知识点 CRUD + 跨模块查询接口 | +| `actions.ts` | 377 | 11 个 Server Action(写操作,含 Zod 校验 + 资源归属校验) | +| `data-access.ts` | 619 | 教材/章节/知识点 CRUD + 跨模块查询接口 + 资源归属校验 + 数据范围过滤 | | `types.ts` | 45 | 类型定义 | | `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-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-2(2026-06-22 审计发现):年级 CRUD 逻辑与 `grade-management` 模块重复定义,两套实现并存 - ⚠️ P0-5(2026-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")` +- ✅ P1-3 修复(2026-06-22):新增 school-error-boundary.tsx(class component Error Boundary + i18n + router.refresh 重试)和 school-skeleton.tsx(SchoolListSkeleton 表格骨架 + SchoolCardSkeleton 卡片骨架);4 个页面(schools/grades/departments/academic-year)均已包裹 SchoolErrorBoundary;school.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`) | | `schema.ts` | 51 | Zod 校验 | | `types.ts` | 96 | 类型定义(含 Insert/Update 入参类型) | +| components/school-error-boundary.tsx | 72 | 共享 Error Boundary(class 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) -- 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,含防抖和请求竞态取消) - 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~~ 新增客户端分页 UI(PAGE_SIZE=20,ChevronLeft/ChevronRight 按钮) - ✅ P1-9 已修复:~~`deleteMessage` 两个独立 UPDATE 无事务~~ 改为 `db.transaction` 包裹 senderDeletedAt 和 receiverDeletedAt 更新,保证原子性 - ✅ 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 模块) | -| `data-access.ts` | ~270 | 私信 CRUD + `getMessagesPageData` 编排函数(✅ P1-5 新增) | +| `actions.ts` | ~280 | 7 个私信 Server Action + 2 个通知偏好 Action(✅ P1-4:通知 CRUD Action 已迁移至 notifications 模块;✅ V2-P0-2:通知标题 i18n 化) | +| `data-access.ts` | ~290 | 私信 CRUD + `getMessagesPageData` 编排函数(✅ P1-5 新增)+ `getMessageDetailPageData` 编排函数(✅ V2-P1-3 新增) | | `schema.ts` | 44 | 私信发送校验 + messageId 校验 + 通知偏好更新校验 | | `types.ts` | 52 | 私信类型 + re-export 通知类型(向后兼容) | | `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 + 客户端分页 UI,PAGE_SIZE=20) | +| `components/message-list.tsx` | 消息列表(✅ P1-7:使用 `useMessageSearch` hook + 客户端分页 UI,PAGE_SIZE=20;✅ V2-P1-2:客户端过滤仅在初始数据时执行) | | `components/message-detail.tsx` | 消息详情(含回复) | -| `components/message-compose.tsx` | 撰写新消息 | -| `components/unread-message-badge.tsx` | 未读消息计数徽章(侧边栏,每 60 秒轮询 `getUnreadMessageCountAction`) | +| `components/message-compose.tsx` | 撰写新消息(✅ V2-P1-4:fieldErrors + aria-invalid 字段级错误展示) | +| `components/unread-message-badge.tsx` | 未读消息计数徽章(侧边栏,每 60 秒轮询 `getUnreadMessageCountAction`;✅ V2-P2-1:POLL_INTERVAL_MS 常量) | **客户端行为**: -- `message-list.tsx`:客户端调用 `getMessagesAction` 搜索消息(useMessageSearch hook,400ms 防抖,请求竞态取消) -- `unread-message-badge.tsx`:每 60 秒轮询 `getUnreadMessageCountAction` 刷新未读计数 +- `message-list.tsx`:客户端调用 `getMessagesAction` 搜索消息(useMessageSearch hook,400ms 防抖,请求竞态取消);V2-P1-2 优化:客户端过滤仅在初始数据(type=all)时执行 +- `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-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) +- ✅ 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` 表 - ✅ 渠道抽象优秀(接口 + 工厂 + Mock 实现) @@ -1090,11 +1111,11 @@ src/auth.ts ──▶ import { ... } from "@/shared/lib/permissions" **组件清单**: | 组件 | 职责 | |------|------| -| `components/notification-list.tsx` | 通知列表(消息页底部,展示所有通知,支持标记已读) | -| `components/notification-dropdown.tsx` | 通知下拉菜单(站点头部,每 30 秒轮询 `getNotificationsAction` + `getUnreadNotificationCountAction`) | +| `components/notification-list.tsx` | 通知列表(消息页底部,展示所有通知,支持标记已读;✅ V2-P0-1:useTranslations 命名空间从 "messages" 切换到 "notifications") | +| `components/notification-dropdown.tsx` | 通知下拉菜单(站点头部,每 30 秒轮询 `getNotificationsAction` + `getUnreadNotificationCountAction`;✅ V2-P0-1:useTranslations 命名空间切换;✅ V2-P2-1:POLL_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-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) +- ✅ 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-detail.tsx` | 公告详情(只读) | -| `components/announcement-form.tsx` | 公告表单(创建/编辑,✅ P1-6:条件校验由 schema superRefine 保证) | +| `components/announcement-form.tsx` | 公告表单(创建/编辑,✅ P1-6:条件校验由 schema superRefine 保证;✅ V2-P1-4:fieldErrors + aria-invalid 字段级错误展示) | | `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/rf-mappers.ts` | **纯函数**:toRfNodes/toRfEdges/fromRfEdges(LessonPlanNode/Edge ↔ React Flow Node/Edge 映射) | | `config/block-registry.tsx` | **配置驱动**:BLOCK_REGISTRY 注册表 + getBlockComponent/isRichTextBlock,node-edit-panel 通过配置渲染 Block | -| `providers/lesson-plan-provider.tsx` | **Provider + Context(P1-5/P1-7/P2-4)**:LessonPlanProvider 注入数据服务/角色配置/埋点;定义 LessonPlanDataService 接口、4 个角色配置(TEACHER/ADMIN/STUDENT/PARENT)、ROLE_CONFIGS 注册表、LessonPlanTracker 接口 + noopTracker;hooks:useLessonPlanContextSafe(返回 null 不抛错)/useLessonPlanContext/useRoleConfig/useLessonPlanService/useLessonPlanTracker | +| `providers/lesson-plan-provider.tsx` | **Provider + Context(P1-5/P1-7/P2-4/V2-6)**:LessonPlanProvider 注入数据服务/角色配置/埋点;定义 LessonPlanDataService 接口、4 个角色配置(TEACHER/ADMIN/STUDENT/PARENT)、ROLE_CONFIGS 注册表、LessonPlanTracker 接口 + noopTracker;hooks:useLessonPlanContextSafe(返回 null 不抛错)/useLessonPlanContext/useRoleConfig/useLessonPlanService/useLessonPlanTracker/useLessonPlanTrackerSafe(V2-6 新增,返回 noopTracker 不抛错) | | `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-versions.ts` | 版本管理(创建/查询/回滚/清理) | -| `data-access-templates.ts` | 个人模板 CRUD | -| `data-access-knowledge.ts` | 按知识点/题目反查课案 | -| `actions.ts` | 课案 CRUD/版本/模板 Server Actions | -| `actions-publish.ts` | 发布作业 Server Action | -| `actions-ai.ts` | AI 知识点建议 Server Action | -| `actions-kp.ts` | 知识点选项 Server Action | -| `publish-service.ts` | 发布作业服务(编排 homework/exams/classes,通过对方 data-access 调用,无直查跨模块表) | +| `data-access.ts` | 课案 CRUD + 模板查询(migrateV1ToV2/normalizeDocument/buildInitialContent 从 lib/ 导入并 re-export 保持向后兼容;buildScopeCondition 按 scope 类型精确过滤 P0-3;V2-1:抛出 `LessonPlanDataError` 错误码;V2-3:mapRowToLessonPlan/mapRowToListItem/mapRowToTemplate 显式映射 + isLessonPlanStatus/isTemplateType/isTemplateScope 类型守卫) | +| `data-access-versions.ts` | 版本管理(创建/查询/回滚/清理;V2-3:mapRowToVersion 显式映射) | +| `data-access-templates.ts` | 个人模板 CRUD(V2-3:mapRowToTemplate 显式映射 + 类型守卫) | +| `data-access-knowledge.ts` | 按知识点/题目反查课案(V2-3:显式字段映射替代 `as unknown as`) | +| `actions.ts` | 课案 CRUD/版本/模板 Server Actions(V2-1:getTranslations i18n + 错误码捕获;V2-2:createLessonPlanAction 传入 translateTitle 翻译 SYSTEM_TEMPLATES) | +| `actions-publish.ts` | 发布作业 Server Action(V2-1:getTranslations i18n + PUBLISH_ERROR_KEY_MAP 错误码映射) | +| `actions-ai.ts` | AI 知识点建议 Server Action(V2-1:i18n + 错误码) | +| `actions-kp.ts` | 知识点选项 Server Action(V2-1:i18n + 错误码) | +| `publish-service.ts` | 发布作业服务(编排 homework/exams/classes,通过对方 data-access 调用,无直查跨模块表;V2-1:抛出 `PublishServiceError` 错误码;V2-3:显式字段映射替代 `as unknown as`) | | `ai-suggest.ts` | AI 知识点建议服务 | | `seed-templates.ts` | 模板种子数据 | | `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-card.tsx` | 课案卡片(i18n 已接入) | -| `components/lesson-plan-filters.tsx` | 课案筛选器(i18n 已接入) | -| `components/lesson-plan-editor.tsx` | 课案编辑器(编排 NodeEditor + NodeEditPanel,i18n 已接入) | -| `components/node-editor.tsx` | **节点图画布**(React Flow,使用 lib/rf-mappers + lib/node-summary 纯函数,i18n 已接入) | +| `components/lesson-plan-card.tsx` | 课案卡片(i18n 已接入;V2-6:duplicate/archive 调用 tracker.track) | +| `components/lesson-plan-filters.tsx` | 课案筛选器(i18n 已接入;V2-5:3 个表单元素 label htmlFor 关联) | +| `components/lesson-plan-editor.tsx` | 课案编辑器(编排 NodeEditor + NodeEditPanel,i18n 已接入;V2-6:handleManualSave 调用 tracker.track) | +| `components/node-editor.tsx` | **节点图画布**(React Flow,使用 lib/rf-mappers + lib/node-summary 纯函数,i18n 已接入;V2-4:MiniMap 复用 getNodeColor;V2-5:role=application + 键盘导航配置) | | `components/node-edit-panel.tsx` | **侧边内容编辑面板**(配置驱动渲染 Block,通过 getBlockComponent + LessonPlanErrorBoundary 包裹,i18n 已接入) | | `components/nodes/lesson-node.tsx` | **自定义节点组件**(使用 lib/node-summary 的 getNodeSummary/getNodeColor,i18n 已接入) | | `components/lesson-plan-error-boundary.tsx` | **错误边界**:LessonPlanErrorBoundary 类组件,支持 fallback 和 onError 回调 | | `components/lesson-plan-skeleton.tsx` | **骨架屏**:VersionListSkeleton/QuestionBankSkeleton/KnowledgePointSkeleton/LessonPlanListSkeleton | | `components/block-renderer.tsx` | ⚠️ @deprecated Block 渲染器(已被 NodeEditor 替代,保留向后兼容) | -| `components/template-picker.tsx` | 模板选择器(i18n 已接入) | -| `components/version-history-drawer.tsx` | 版本历史抽屉(i18n 已接入) | +| `components/template-picker.tsx` | 模板选择器(i18n 已接入;V2-6:create 调用 tracker.track) | +| `components/version-history-drawer.tsx` | 版本历史抽屉(i18n 已接入;V2-6:revert 调用 tracker.track) | | `components/knowledge-point-picker.tsx` | 知识点选择器(i18n 已接入) | | `components/question-bank-picker.tsx` | 题库选择器(i18n 已接入) | -| `components/inline-question-editor.tsx` | 内联题目编辑器(i18n 已接入) | -| `components/publish-homework-dialog.tsx` | 发布作业对话框(i18n 已接入) | +| `components/inline-question-editor.tsx` | 内联题目编辑器(i18n 已接入;V2-5:type/difficulty select label htmlFor 关联) | +| `components/publish-homework-dialog.tsx` | 发布作业对话框(i18n 已接入;V2-6:publish 调用 tracker.track) | | `components/blocks/rich-text-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.reload,i18n 已接入) | +| `components/blocks/exercise-block.tsx` | 练习 Block(被 NodeEditPanel 复用,使用 router.refresh 替代 window.location.reload,i18n 已接入;V2-5:purpose select label 关联 + 题目列表 ul/li 语义化) | | `components/blocks/reflection-block.tsx` | 反思 Block(被 NodeEditPanel 复用,i18n 已接入) | --- diff --git a/docs/architecture/005_architecture_data.json b/docs/architecture/005_architecture_data.json index 040603f..479284a 100644 --- a/docs/architecture/005_architecture_data.json +++ b/docs/architecture/005_architecture_data.json @@ -4086,6 +4086,12 @@ "permission": "TEXTBOOK_UPDATE", "signature": "(chapterId, newIndex, parentId, textbookId) => Promise", "purpose": "章节排序" + }, + { + "name": "getKnowledgePointsByChapterAction", + "permission": "TEXTBOOK_READ", + "signature": "(chapterId, textbookId) => Promise>", + "purpose": "获取章节下的知识点列表(含资源归属校验)" } ], "dataAccess": [ @@ -4249,6 +4255,24 @@ "updateKnowledgePointAction", "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": [ @@ -4264,7 +4288,7 @@ { "name": "useKnowledgePointActions", "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参数)", "usedBy": [ "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": [ { "name": "ChapterSidebarList", @@ -4370,10 +4493,6 @@ "name": "CreateChapterDialog", "purpose": "创建章节对话框" }, - { - "name": "CreateKnowledgePointDialog", - "purpose": "创建知识点对话框" - }, { "name": "KnowledgeGraph", "purpose": "知识图谱可视化" @@ -4387,8 +4506,8 @@ "purpose": "知识点列表" }, { - "name": "KnowledgePointPanel", - "purpose": "知识点面板" + "name": "SectionErrorBoundary", + "purpose": "章节内容错误边界(class component + i18n + router.refresh 重试)" }, { "name": "TextbookCard", @@ -4415,27 +4534,25 @@ "purpose": "教材设置对话框" } ], - "uiDeps": [ - { - "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" - } - ], + "uiDeps": [], + "uiDepsNote": "已通过 render prop 解耦,不再直接 import questions 模块组件", "knownIssues": [ - "P0 跨模块 UI 依赖:knowledge-point-dialogs.tsx 直接 import questions 模块 CreateQuestionDialog", - "P0 前端权限硬编码:canEdit={true} 按路由写死,未用 usePermission().hasPermission()", - "P0 全模块零 i18n:中英文文案硬编码,未接入 next-intl", - "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" + "i18n 覆盖率约 95%(chapter-sidebar-list 已接入,actions.ts 已接入,section-error-boundary 默认值已改英文)", + "类型断言残留 3 处 as string", + "P2 图谱方向键导航未实现" ], + "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" } }, @@ -5804,6 +5921,24 @@ { "name": "AcademicYearClient", "purpose": "学年管理客户端" + }, + { + "name": "SchoolErrorBoundary", + "file": "components/school-error-boundary.tsx", + "purpose": "school 模块共享 Error Boundary(class 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": [ @@ -12938,7 +13073,13 @@ "P1-7": "新增 4 个角色配置(TEACHER/ADMIN/STUDENT/PARENT)+ ROLE_CONFIGS 注册表", "P1-8": "新增 BLOCK_REGISTRY 注册表,node-edit-panel 配置驱动渲染", "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/li;node-editor 画布添加 role=application + 键盘导航配置", + "V2-6": "Tracker 埋点接入:新增 useLessonPlanTrackerSafe hook,在 create/save/publish/revert/duplicate/archive 6 处调用 tracker.track" } } }, diff --git a/docs/architecture/audit/announcements-messages-audit-report-v2.md b/docs/architecture/audit/announcements-messages-audit-report-v2.md new file mode 100644 index 0000000..2da92df --- /dev/null +++ b/docs/architecture/audit/announcements-messages-audit-report-v2.md @@ -0,0 +1,159 @@ +# 公告和消息模块审计报告 V2 + +> 审查日期:2026-06-22 +> 审查范围:V1 改进后的 `src/modules/announcements/**`、`src/modules/messaging/**`、`src/modules/notifications/**`、对应路由层 +> 前置文档:`announcements-messages-audit-report.md`(V1,14 项改进已全部完成或标记超出范围) +> 架构图参考:`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` | 修改(同步) | diff --git a/src/app/(dashboard)/messages/[id]/page.tsx b/src/app/(dashboard)/messages/[id]/page.tsx index 3c4f3da..c00506a 100644 --- a/src/app/(dashboard)/messages/[id]/page.tsx +++ b/src/app/(dashboard)/messages/[id]/page.tsx @@ -1,10 +1,9 @@ import { notFound } from "next/navigation" import type { Metadata } from "next" -import { after } from "next/server" import { getTranslations } from "next-intl/server" import { requirePermission } from "@/shared/lib/auth-guard" 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" export const dynamic = "force-dynamic" @@ -22,14 +21,9 @@ export default async function MessageDetailPage({ const ctx = await requirePermission(Permissions.MESSAGE_READ) const { id } = await params - const message = await getMessageById(id, ctx.userId) + const message = await getMessageDetailPageData(id, ctx.userId) 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 (
diff --git a/src/app/(dashboard)/messages/page.tsx b/src/app/(dashboard)/messages/page.tsx index 52c5287..55239b9 100644 --- a/src/app/(dashboard)/messages/page.tsx +++ b/src/app/(dashboard)/messages/page.tsx @@ -2,10 +2,9 @@ import { getTranslations } from "next-intl/server" import { requirePermission } from "@/shared/lib/auth-guard" import { Permissions } from "@/shared/types/permissions" -import { getMessages } from "@/modules/messaging/data-access" -import { getNotifications } from "@/modules/notifications/data-access" +import { getMessagesPageData } from "@/modules/messaging/data-access" 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" @@ -18,10 +17,8 @@ export default async function MessagesPage() { const t = await getTranslations("messages") const ctx = await requirePermission(Permissions.MESSAGE_READ) - const [messagesResult, notificationsResult] = await Promise.all([ - getMessages({ userId: ctx.userId, type: "all", page: 1, pageSize: 50 }), - getNotifications(ctx.userId, { page: 1, pageSize: 20 }), - ]) + const { messages: messagesResult, notifications: notificationsResult } = + await getMessagesPageData(ctx.userId) return (
diff --git a/src/i18n/request.ts b/src/i18n/request.ts index 36f10e6..b13dd1f 100644 --- a/src/i18n/request.ts +++ b/src/i18n/request.ts @@ -29,6 +29,7 @@ export default getRequestConfig(async () => { examHomework, announcements, messages, + notifications, settings, textbooks, grade, @@ -48,6 +49,7 @@ export default getRequestConfig(async () => { import(`@/shared/i18n/messages/${locale}/exam-homework.json`), import(`@/shared/i18n/messages/${locale}/announcements.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}/textbooks.json`), import(`@/shared/i18n/messages/${locale}/grade.json`), @@ -71,6 +73,7 @@ export default getRequestConfig(async () => { examHomework: examHomework.default, announcements: announcements.default, messages: messages.default, + notifications: notifications.default, settings: settings.default, textbooks: textbooks.default, grade: grade.default, diff --git a/src/modules/announcements/actions.ts b/src/modules/announcements/actions.ts index 331e60d..be4de87 100644 --- a/src/modules/announcements/actions.ts +++ b/src/modules/announcements/actions.ts @@ -2,8 +2,10 @@ import { revalidatePath } from "next/cache" import { createId } from "@paralleldrive/cuid2" +import { getTranslations } from "next-intl/server" import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guard" +import { trackEvent } from "@/shared/lib/track-event" import { Permissions } from "@/shared/types/permissions" import type { ActionState } from "@/shared/types/action-state" import { sendBatchNotifications } from "@/modules/notifications" @@ -69,10 +71,14 @@ async function notifyAnnouncementPublished(announcement: Announcement): Promise< const targetUserIds = await resolveTargetUserIds(announcement) 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) => ({ userId, - title: `新公告:${announcement.title}`, - content: announcement.content.slice(0, 200), + title, + content, type: "info", actionUrl: `/announcements/${announcement.id}`, metadata: { @@ -146,6 +152,14 @@ export async function createAnnouncementAction( revalidatePath("/admin/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 } } catch (e) { return handleActionError(e) @@ -215,6 +229,13 @@ export async function updateAnnouncementAction( revalidatePath(`/admin/announcements/${id}`) 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 } } catch (e) { return handleActionError(e) @@ -233,6 +254,13 @@ export async function deleteAnnouncementAction(id: string): Promise + export function AnnouncementForm({ mode, announcement, @@ -37,14 +39,21 @@ export function AnnouncementForm({ const t = useTranslations("announcements") const router = useRouter() const [isWorking, setIsWorking] = useState(false) + const [fieldErrors, setFieldErrors] = useState({}) const [type, setType] = useState(announcement?.type ?? "school") const [status, setStatus] = useState(announcement?.status ?? "draft") const [targetGradeId, setTargetGradeId] = useState(announcement?.targetGradeId ?? "") const [targetClassId, setTargetClassId] = useState(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) => { setIsWorking(true) + setFieldErrors({}) try { formData.set("type", type) formData.set("status", status) @@ -72,6 +81,10 @@ export function AnnouncementForm({ router.push("/admin/announcements") router.refresh() } else { + // 展示字段级错误(来自 Zod superRefine 校验) + if (res.errors) { + setFieldErrors(res.errors) + } toast.error(res.message || t("messages.updateFailed")) } } catch { @@ -98,7 +111,11 @@ export function AnnouncementForm({ placeholder={t("form.titlePlaceholder")} defaultValue={announcement?.title ?? ""} required + aria-invalid={!!getFieldError("title")} /> + {getFieldError("title") ? ( +

{getFieldError("title")}

+ ) : null}
@@ -110,7 +127,11 @@ export function AnnouncementForm({ className="min-h-[160px]" defaultValue={announcement?.content ?? ""} required + aria-invalid={!!getFieldError("content")} /> + {getFieldError("content") ? ( +

{getFieldError("content")}

+ ) : null}
@@ -148,7 +169,7 @@ export function AnnouncementForm({
+ {getFieldError("targetGradeId") ? ( +

{getFieldError("targetGradeId")}

+ ) : null}
) : null} @@ -167,7 +191,7 @@ export function AnnouncementForm({
+ {getFieldError("targetClassId") ? ( +

{getFieldError("targetClassId")}

+ ) : null}
) : null}
diff --git a/src/modules/announcements/components/announcement-list.tsx b/src/modules/announcements/components/announcement-list.tsx index 68858d0..9348400 100644 --- a/src/modules/announcements/components/announcement-list.tsx +++ b/src/modules/announcements/components/announcement-list.tsx @@ -1,6 +1,5 @@ "use client" -import { useMemo, useState } from "react" import Link from "next/link" import { useRouter } from "next/navigation" import { Plus, Megaphone } from "lucide-react" @@ -21,6 +20,14 @@ import type { Announcement, AnnouncementStatus } from "../types" type Filter = "all" | AnnouncementStatus +/** + * 公告列表组件。 + * + * 过滤模式:纯服务端过滤。 + * - Select 切换时更新 URL `?status=`,触发 RSC 重新渲染 + * - 父页面根据 `?status=` 查询并传入 `announcements` prop + * - 组件不再做客户端二次过滤,避免双重过滤逻辑冗余 + */ export function AnnouncementList({ announcements, canManage, @@ -36,7 +43,7 @@ export function AnnouncementList({ }) { const t = useTranslations("announcements") const router = useRouter() - const [filter, setFilter] = useState(initialStatus ?? "all") + const filter: Filter = initialStatus ?? "all" const filterOptions: { value: Filter; label: string }[] = [ { value: "all", label: t("filter.all") }, @@ -45,13 +52,7 @@ export function AnnouncementList({ { value: "archived", label: t("filter.archived") }, ] - const filtered = useMemo(() => { - if (filter === "all") return announcements - return announcements.filter((a) => a.status === filter) - }, [announcements, filter]) - - const handleFilterChange = (value: string) => { - setFilter(value as Filter) + const handleFilterChange = (value: string): void => { const params = new URLSearchParams() if (value !== "all") params.set("status", value) const qs = params.toString() @@ -83,11 +84,11 @@ export function AnnouncementList({ ) : null}
- {filtered.length === 0 ? ( + {announcements.length === 0 ? ( ) : (
- {filtered.map((a) => ( + {announcements.map((a) => ( { }) .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 })), + } +} diff --git a/src/modules/announcements/schema.ts b/src/modules/announcements/schema.ts index 9f3338b..368c32a 100644 --- a/src/modules/announcements/schema.ts +++ b/src/modules/announcements/schema.ts @@ -1,5 +1,53 @@ import { z } from "zod" +/** + * 公告类型与目标受众的联合校验: + * - type=school:targetGradeId / targetClassId 必须为空 + * - type=grade:targetGradeId 必填,targetClassId 必须为空 + * - type=class:targetClassId 必填 + * + * 避免"创建无受众公告"的数据完整性问题。 + */ +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 .object({ title: z.string().trim().min(1).max(255), @@ -10,6 +58,7 @@ export const CreateAnnouncementSchema = z targetClassId: z.string().trim().optional().nullable(), publishedAt: z.string().optional().nullable(), }) + .superRefine(refineAudience) .transform((v) => ({ title: v.title, content: v.content, @@ -32,6 +81,7 @@ export const UpdateAnnouncementSchema = z targetClassId: z.string().trim().optional().nullable(), publishedAt: z.string().optional().nullable(), }) + .superRefine(refineAudience) .transform((v) => ({ title: v.title, content: v.content, diff --git a/src/modules/layout/config/navigation.ts b/src/modules/layout/config/navigation.ts index 5040962..e895174 100644 --- a/src/modules/layout/config/navigation.ts +++ b/src/modules/layout/config/navigation.ts @@ -36,6 +36,26 @@ export type NavItem = { 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> = { admin: [ { @@ -118,12 +138,7 @@ export const NAV_CONFIG: Partial> = { { title: "Data Changes", href: "/admin/audit-logs/data-changes" }, ] }, - { - title: "Messages", - icon: Mail, - href: "/messages", - permission: Permissions.MESSAGE_READ, - }, + ...COMMON_NAV_ITEMS, { title: "Settings", icon: Settings, @@ -243,18 +258,85 @@ export const NAV_CONFIG: Partial> = { { title: "年级洞察", href: "/management/grade/insights" }, ] }, + ...COMMON_NAV_ITEMS, + ], + grade_head: [ { - title: "公告", - icon: Megaphone, - href: "/announcements", - permission: Permissions.ANNOUNCEMENT_READ, + title: "仪表盘", + icon: LayoutDashboard, + href: "/management", + permission: Permissions.GRADE_MANAGE, }, { - title: "消息", - icon: Mail, - href: "/messages", - permission: Permissions.MESSAGE_READ, + 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, + ], + 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: [ { @@ -303,18 +385,7 @@ export const NAV_CONFIG: Partial> = { href: "/student/elective", permission: Permissions.ELECTIVE_SELECT, }, - { - title: "Announcements", - icon: Megaphone, - href: "/announcements", - permission: Permissions.ANNOUNCEMENT_READ, - }, - { - title: "Messages", - icon: Mail, - href: "/messages", - permission: Permissions.MESSAGE_READ, - }, + ...COMMON_NAV_ITEMS, ], parent: [ { @@ -339,17 +410,6 @@ export const NAV_CONFIG: Partial> = { icon: CalendarRange, href: "/parent/leave", }, - { - title: "Announcements", - icon: Megaphone, - href: "/announcements", - permission: Permissions.ANNOUNCEMENT_READ, - }, - { - title: "Messages", - icon: Mail, - href: "/messages", - permission: Permissions.MESSAGE_READ, - }, + ...COMMON_NAV_ITEMS, ] } diff --git a/src/modules/messaging/actions.ts b/src/modules/messaging/actions.ts index 47ccad3..a53b072 100644 --- a/src/modules/messaging/actions.ts +++ b/src/modules/messaging/actions.ts @@ -1,7 +1,9 @@ "use server" import { revalidatePath } from "next/cache" +import { getTranslations } from "next-intl/server" import { PermissionDeniedError, requirePermission } from "@/shared/lib/auth-guard" +import { trackEvent } from "@/shared/lib/track-event" import { Permissions } from "@/shared/types/permissions" import type { ActionState } from "@/shared/types/action-state" import { sendNotification } from "@/modules/notifications/dispatcher" @@ -20,19 +22,12 @@ import { getRecipients, getUnreadMessageCount, } from "./data-access" -import { - getNotifications, - markNotificationAsRead, - markAllNotificationsAsRead, - getUnreadNotificationCount, -} from "@/modules/notifications/data-access" import { getNotificationPreferences, upsertNotificationPreferences, } from "@/modules/notifications/preferences" import type { Message, MessageType, RecipientOption } from "./types" import type { - Notification, NotificationPreferences, UpdateNotificationPreferencesInput, } from "@/modules/notifications/types" @@ -70,10 +65,14 @@ export async function sendMessageAction( // Notify the receiver about the new message via the notifications dispatcher. // 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({ userId: input.receiverId, type: "info", - title: input.subject ? `New message: ${input.subject}` : "New message", + title: notifyTitle, content: input.content.slice(0, 200), actionUrl: `/messages/${id}`, metadata: { messageType: "message", messageId: id }, @@ -82,6 +81,14 @@ export async function sendMessageAction( revalidatePath("/messages") 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 } } catch (e) { if (e instanceof PermissionDeniedError) return { success: false, message: e.message } @@ -102,6 +109,14 @@ export async function markMessageAsReadAction(messageId: string): Promise } } -export async function getUnreadNotificationCountAction(): Promise> { - 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 getNotificationsAction( - params?: { page?: number; pageSize?: number; unreadOnly?: boolean } -): Promise> { - 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> { - 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> { - 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" } - } -} +// --------------------------------------------------------------------------- +// 通知相关 Server Actions(getNotificationsAction / markNotificationAsReadAction / +// markAllNotificationsAsReadAction / getUnreadNotificationCountAction)已迁移至 +// @/modules/notifications/actions。请直接从 notifications 模块导入。 +// --------------------------------------------------------------------------- export async function getNotificationPreferencesAction(): Promise> { try { diff --git a/src/modules/messaging/components/message-compose.tsx b/src/modules/messaging/components/message-compose.tsx index 95164d7..111b050 100644 --- a/src/modules/messaging/components/message-compose.tsx +++ b/src/modules/messaging/components/message-compose.tsx @@ -23,6 +23,8 @@ import { import { sendMessageAction } from "../actions" import type { RecipientOption } from "../types" +type FieldErrors = Record + export function MessageCompose({ recipients, parentMessageId, @@ -40,10 +42,16 @@ export function MessageCompose({ const router = useRouter() const [isWorking, setIsWorking] = useState(false) const [receiverId, setReceiverId] = useState(defaultReceiverId ?? "") + const [fieldErrors, setFieldErrors] = useState({}) + + const getFieldError = (field: string): string | null => { + const errs = fieldErrors[field] + return errs && errs.length > 0 ? errs[0] : null + } const handleSubmit = async (formData: FormData) => { if (!receiverId) { - toast.error(t("messages.selectRecipient")) + toast.error(t("form.selectRecipient")) return } formData.set("receiverId", receiverId) @@ -52,6 +60,7 @@ export function MessageCompose({ } setIsWorking(true) + setFieldErrors({}) try { const res = await sendMessageAction(null, formData) if (res.success) { @@ -59,6 +68,10 @@ export function MessageCompose({ router.push("/messages") router.refresh() } else { + // 展示字段级错误(来自 Zod 校验) + if (res.errors) { + setFieldErrors(res.errors) + } toast.error(res.message || t("messages.sendFailed")) } } catch { @@ -85,7 +98,7 @@ export function MessageCompose({
+ {getFieldError("receiverId") ? ( +

{getFieldError("receiverId")}

+ ) : null}
@@ -108,7 +124,11 @@ export function MessageCompose({ placeholder={t("form.subjectPlaceholder")} defaultValue={defaultSubject ?? ""} maxLength={255} + aria-invalid={!!getFieldError("subject")} /> + {getFieldError("subject") ? ( +

{getFieldError("subject")}

+ ) : null}
@@ -119,7 +139,11 @@ export function MessageCompose({ placeholder={t("form.contentPlaceholder")} className="min-h-[200px]" required + aria-invalid={!!getFieldError("content")} /> + {getFieldError("content") ? ( +

{getFieldError("content")}

+ ) : null}
diff --git a/src/modules/messaging/components/message-list.tsx b/src/modules/messaging/components/message-list.tsx index e0f63af..df019bc 100644 --- a/src/modules/messaging/components/message-list.tsx +++ b/src/modules/messaging/components/message-list.tsx @@ -1,8 +1,8 @@ "use client" -import { useEffect, useMemo, useState } from "react" +import { useMemo, useState } from "react" 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 { Badge } from "@/shared/components/ui/badge" @@ -16,10 +16,14 @@ import { usePermission } from "@/shared/hooks/use-permission" import { Permissions } from "@/shared/types/permissions" import { getMessagesAction } from "../actions" +import { useMessageSearch } from "../hooks/use-message-search" import type { Message, MessageType } from "../types" type Tab = "inbox" | "sent" +/** 客户端分页大小 */ +const PAGE_SIZE = 20 + export function MessageList({ messages, currentUserId, @@ -31,54 +35,44 @@ export function MessageList({ }) { const t = useTranslations("messages") const [tab, setTab] = useState(initialType === "sent" ? "sent" : "inbox") - const [keyword, setKeyword] = useState("") - const [searchResults, setSearchResults] = useState<{ kw: string; tab: Tab; items: Message[] } | null>(null) + const [currentPage, setCurrentPage] = useState(1) const { hasPermission } = usePermission() const canSend = hasPermission(Permissions.MESSAGE_SEND) - // 防抖搜索:keyword 或 tab 变化时调用 getMessagesAction - useEffect(() => { - const kw = keyword.trim() - 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 + const { keyword, setKeyword, results, searching, isUsingInitial } = useMessageSearch({ + searchAction: getMessagesAction, + tab, + }) + // 客户端过滤仅在初始数据(type=all)时需要,搜索结果已由服务端按 tab 过滤 const filtered = useMemo(() => { + const displayMessages = isUsingInitial ? messages : (results ?? []) + if (!isUsingInitial) return displayMessages if (tab === "inbox") return displayMessages.filter((m) => m.receiverId === 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 (
- setTab(v as Tab)}> + @@ -108,7 +102,7 @@ export function MessageList({ aria-label={t("search.placeholder")} placeholder={t("search.placeholder")} value={keyword} - onChange={(e) => setKeyword(e.target.value)} + onChange={(e) => handleKeywordChange(e.target.value)} className="pl-9" /> {searching ? ( @@ -116,7 +110,7 @@ export function MessageList({ ) : null}
- {filtered.length === 0 ? ( + {paged.length === 0 ? ( ) : ( -
- {filtered.map((m) => { - const isReceived = m.receiverId === currentUserId - const counterpart = isReceived ? m.senderName : m.receiverName - const unread = isReceived && !m.isRead - return ( - - - -
-
- {unread ? ( -
+ + + + ) + })} +
+ + {showPagination ? ( +
+ + + {safePage} / {totalPages} + + +
+ ) : null} + )}
) diff --git a/src/modules/messaging/components/unread-message-badge.tsx b/src/modules/messaging/components/unread-message-badge.tsx index 13f74a5..576c99d 100644 --- a/src/modules/messaging/components/unread-message-badge.tsx +++ b/src/modules/messaging/components/unread-message-badge.tsx @@ -6,11 +6,14 @@ import { Badge } from "@/shared/components/ui/badge" import { getUnreadMessageCountAction } from "../actions" +/** 未读消息计数轮询间隔(毫秒) */ +const POLL_INTERVAL_MS = 60_000 + /** * 未读消息计数徽章 * * 在侧边栏 Messages 导航项旁显示未读私信数。 - * 每 60 秒轮询一次以保持计数更新。 + * 每 POLL_INTERVAL_MS 毫秒轮询一次以保持计数更新。 */ export function UnreadMessageBadge() { const [count, setCount] = useState(0) @@ -30,7 +33,7 @@ export function UnreadMessageBadge() { const timer = setInterval(() => { void fetchCount() - }, 60_000) + }, POLL_INTERVAL_MS) return () => { active = false diff --git a/src/modules/messaging/data-access.ts b/src/modules/messaging/data-access.ts index 9aeb887..b093743 100644 --- a/src/modules/messaging/data-access.ts +++ b/src/modules/messaging/data-access.ts @@ -180,14 +180,17 @@ export async function markMessageAsRead(id: string, userId: string): Promise { const now = new Date() // 软删除:发送方删除设置 senderDeletedAt,接收方删除设置 receiverDeletedAt,互不影响 - await db - .update(messages) - .set({ senderDeletedAt: now }) - .where(and(eq(messages.id, id), eq(messages.senderId, userId))) - await db - .update(messages) - .set({ receiverDeletedAt: now }) - .where(and(eq(messages.id, id), eq(messages.receiverId, userId))) + // 使用事务保证两次 UPDATE 的原子性,避免部分失败导致数据不一致 + await db.transaction(async (tx) => { + await tx + .update(messages) + .set({ senderDeletedAt: now }) + .where(and(eq(messages.id, id), eq(messages.senderId, userId))) + await tx + .update(messages) + .set({ receiverDeletedAt: now }) + .where(and(eq(messages.id, id), eq(messages.receiverId, userId))) + }) } export const getUnreadMessageCount = cache(async (userId: string): Promise => { @@ -244,3 +247,44 @@ export const getRecipients = cache( 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 { + const message = await getMessageById(id, userId) + if (!message) return null + + // 自动标记已读:仅当当前用户为接收方且消息未读时 + if (!message.isRead && message.receiverId === userId) { + await markMessageAsRead(id, userId) + } + + return message +} diff --git a/src/modules/messaging/hooks/use-message-search.ts b/src/modules/messaging/hooks/use-message-search.ts new file mode 100644 index 0000000..da84c2d --- /dev/null +++ b/src/modules/messaging/hooks/use-message-search.ts @@ -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 + /** 当前标签页 */ + 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(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, + } +} diff --git a/src/modules/notifications/actions.ts b/src/modules/notifications/actions.ts index bd2d977..8ae4630 100644 --- a/src/modules/notifications/actions.ts +++ b/src/modules/notifications/actions.ts @@ -5,21 +5,31 @@ * * - sendNotificationAction: 发送通知给指定用户(需要 MESSAGE_SEND 权限) * - sendClassNotificationAction: 发送班级通知(教师权限,按班级查询学生后批量发送) + * - getNotificationsAction / markNotificationAsReadAction / markAllNotificationsAsReadAction / getUnreadNotificationCountAction: 站内通知 CRUD * * 权限说明: * 项目无独立 NOTIFICATION_SEND 权限点,复用 MESSAGE_SEND(教师/管理员/年级主任均拥有)。 * 班级通知按教师所教班级过滤,确保教师只能给自己班级发通知。 + * 站内通知读取/标记已读复用 MESSAGE_READ 权限(任何能读消息的用户都能查看通知)。 */ +import { revalidatePath } from "next/cache" import { z } from "zod" import { PermissionDeniedError, requirePermission } from "@/shared/lib/auth-guard" +import { trackEvent } from "@/shared/lib/track-event" import { Permissions } from "@/shared/types/permissions" import type { ActionState } from "@/shared/types/action-state" import { getClassExists, getStudentIdsByClassId } from "@/modules/classes/data-access" 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 入参) @@ -157,3 +167,101 @@ export async function sendClassNotificationAction( 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> { + 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> { + 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> { + 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> { + 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" } + } +} diff --git a/src/modules/notifications/components/index.ts b/src/modules/notifications/components/index.ts new file mode 100644 index 0000000..1a293cc --- /dev/null +++ b/src/modules/notifications/components/index.ts @@ -0,0 +1,2 @@ +export { NotificationList } from "./notification-list" +export { NotificationDropdown } from "./notification-dropdown" diff --git a/src/modules/messaging/components/notification-dropdown.tsx b/src/modules/notifications/components/notification-dropdown.tsx similarity index 92% rename from src/modules/messaging/components/notification-dropdown.tsx rename to src/modules/notifications/components/notification-dropdown.tsx index 66325ed..aa5ed65 100644 --- a/src/modules/messaging/components/notification-dropdown.tsx +++ b/src/modules/notifications/components/notification-dropdown.tsx @@ -25,7 +25,7 @@ import { markAllNotificationsAsReadAction, markNotificationAsReadAction, } from "../actions" -import type { Notification, NotificationType } from "@/modules/notifications/types" +import type { Notification, NotificationType } from "../types" const TYPE_ICON: Record = { message: MessageSquare, @@ -34,8 +34,11 @@ const TYPE_ICON: Record = { grade: GraduationCap, } +/** 通知下拉菜单轮询间隔(毫秒) */ +const POLL_INTERVAL_MS = 30_000 + export function NotificationDropdown() { - const t = useTranslations("messages") + const t = useTranslations("notifications") const router = useRouter() const [notifications, setNotifications] = useState([]) const [unreadCount, setUnreadCount] = useState(0) @@ -63,11 +66,11 @@ export function NotificationDropdown() { void fetchNotifications() void fetchUnreadCount() - // 每 30 秒轮询刷新通知和未读计数 + // 每 POLL_INTERVAL_MS 毫秒轮询刷新通知和未读计数 const timer = setInterval(() => { void fetchNotifications() void fetchUnreadCount() - }, 30_000) + }, POLL_INTERVAL_MS) return () => { active = false @@ -98,7 +101,7 @@ export function NotificationDropdown() { return ( - - {t("title.notifications")} + {t("title.dropdown")} {unreadCount > 0 ? (