diff --git a/apps/student-portal/docs/01-understanding.md b/apps/student-portal/docs/01-understanding.md index eb85c67..95744ba 100644 --- a/apps/student-portal/docs/01-understanding.md +++ b/apps/student-portal/docs/01-understanding.md @@ -1,35 +1,50 @@ # 模块理解确认书 — student-portal -> AI:ai07(TS/React · 学习场景域前端 remote) -> 阶段:阶段 1 交付物 -> 日期:2026-07-09 -> 关联:[004 架构影响地图](../../../docs/architecture/004_architecture_impact_map.md) §1.1a/1.1b/§5.4、[AI 分配方案](../../../docs/architecture/ai-allocation.md) §5 ai07、[pending-features P3](../../../docs/architecture/roadmap/pending-features.md)、[teacher-portal 阶段 1](../../teacher-portal/docs/01-understanding.md)、[teacher-portal 阶段 2](../../teacher-portal/docs/02-architecture-design.md)、[known-issues §2.12](../../../docs/troubleshooting/known-issues.md) +> AI:ai14(TS/React · 学习场景域前端 remote) +> 阶段:阶段 1 交付物(v2 — ai14 接管审计与补全版) +> 初版日期:2026-07-09(ai07 起草) +> 审计日期:2026-07-10(ai14 修订:端口、所有权、协议、路由、错误码、长远架构遗漏补全) +> 关联:[004 架构影响地图](../../../docs/architecture/004_architecture_impact_map.md) §1.1a/1.1b/§5.4、[AI 分配方案](../../../docs/architecture/ai-allocation.md) §3.2 ai14、[pending-features P3](../../../docs/architecture/roadmap/pending-features.md)、[teacher-portal 阶段 1](../../teacher-portal/docs/01-understanding.md)、[teacher-portal 阶段 2](../../teacher-portal/docs/02-architecture-design.md)、[teacher-portal 阶段 3 长远架构](../../teacher-portal/docs/03-long-term-architecture.md)、[known-issues §2.15](../../../docs/troubleshooting/known-issues.md)、[coord 仲裁 ARB-001](../../../docs/architecture/issues/coord.md#1-arb-001teacher-bff-graphql-schema-第一版)、[coord 仲裁 ARB-002](../../../docs/architecture/issues/coord.md#2-arb-002mf-shell-暴露清单)、[student-bff 契约](../../../docs/architecture/issues/contracts/student-bff_contract.md) + +> **审计修订摘要**(ai14 → ai07 初稿): +> +> 1. **端口修订**:3001 → **4001**(004 §1.2 强制 4 端 4000-4003,[port-allocation](../../../infra/port-allocation.md) §4 硬约束;3001 已被 classes 历史占用) +> 2. **所有权修订**:ai07 → **ai14**(ai-allocation.md §3.2 L94;ai07=classes/core-edu 交接,非 student-portal) +> 3. **协议修订**:REST → **GraphQL**(ARB-001 已裁决 student-bff 走 GraphQL Yoga + ActionState 信封 + DataLoader;前端 all-in GraphQL,不再消费 REST) +> 4. **路由修订**:`/student/dashboard` → `/dashboard`(student-portal 是独立 dev server :4001,路由前缀不带 `/student`,与 student-portal_contract.md §1.2 对齐) +> 5. **登录路径修订**:`/iam/login` → `POST /api/auth/login`(与 student-portal_contract.md §2.3 对齐;iam 仅承担 gRPC,登录由 api-gateway 聚合) +> 6. **错误码前缀修订**:`EXAMS_`/`HOMEWORK_`/`GRADES_` → **`CORE_EDU_`**(known-issues §2.15 已确认 core-edu 子域统一前缀);`STUDENT_BFF_` → **`BFF_STUDENT_`**(coord §5.2 裁决) +> 7. **MF 配置修订**:按 ARB-002,Shell 暴露 `GraphQLProvider`/`useGraphQLClient`/`urql`/`graphql` 单例,student-portal 不再实现自己的 ApiClient +> 8. **遗漏补全**:考试作答边界场景、学情诊断与个性化推荐、学生隐私合规(COPPA/FERPA/PIPL/未成年人保护法)、测试策略分层、韧性模式、性能预算、CSP/前端安全、跨标签同步、API 版本演进、未来扩展铺垫、长远愿景 +> 9. **新增章节**:§11 考试作答边界场景、§12 学生隐私与合规、§13 测试策略、§14 性能与预算、§15 前端安全、§16 跨标签与跨设备同步、§17 i18n 深化、§18 移动端与 PWA、§19 长远愿景与演进路径 --- ## 1. 我在架构中的位置 - **层级**:L2 微前端层(004 §3.1 六层架构中的前端层) -- **MF 角色**:**Remote 子应用**,挂载到 teacher-portal Shell -- **上游(谁调用我)**:浏览器(学生) -- **下游(同步)**:api-gateway(REST,经 Next.js `rewrites` 代理 `/api/v1/*`) -- **下游(推送,P5)**:push-gateway(WebSocket) -- **BFF 对接**:student-bff(待 ai04 设计) -- **通信方式**:HTTP/REST(前端→Gateway)+ WebSocket(前端→push-gateway,P5) +- **MF 角色**:**Remote 子应用**,挂载到 teacher-portal Shell(ARB-002 裁决:P3 首个 Remote) +- **上游(谁调用我)**:浏览器(学生)— 含桌面 Chrome/Edge/Safari、移动端 iOS Safari/Android Chrome、考试机 lockdown 浏览器(P6+ 评估) +- **下游(同步)**:api-gateway(**GraphQL over HTTP**,经 Next.js `rewrites` 代理 `/api/v1/*` 与 `/api/auth/*`) +- **下游(推送,P5)**:push-gateway(WebSocket,含 HTTP 长轮询降级) +- **BFF 对接**:student-bff(ai04 设计,端口 3009,GraphQL Yoga endpoint `POST /graphql`) +- **通信方式**:**GraphQL over HTTP**(前端→Gateway→student-bff)+ WebSocket(前端→push-gateway,P5)+ HTTP 长轮询降级(P5+) - **不直连**:前端不直连任何业务服务或 BFF 后端实例,全部经 api-gateway 代理 **说明**: -- 通过 `next.config.js` 的 `rewrites` 将 `/api/v1/*` 代理到 `api-gateway`(与 Shell 一致的代理策略) -- MF 架构下,student-portal 作为 Remote 暴露页面入口,由 teacher-portal Shell 的 AppShell 动态加载 -- 复用 Shell 暴露的共享依赖(react/react-dom/@tanstack/react-query/zustand/nuqs/ui-components/ui-tokens/contracts/hooks) -- 不独立提供 RootLayout / 字体加载 / 设计令牌 / i18n Provider,全部由 Shell 提供 +- 通过 `next.config.js` 的 `rewrites` 将 `/api/v1/*` 与 `/api/auth/*` 代理到 `api-gateway` +- MF 架构下,student-portal 作为 Remote 暴露页面入口,由 teacher-portal Shell 的 AppShell 动态加载(ARB-002) +- 复用 Shell 暴露的共享依赖(react/react-dom/urql/graphql/@tanstack/react-query/zustand/nuqs/@edu/ui-components/@edu/ui-tokens/@edu/contracts/@edu/hooks/@edu/shared-ts) +- 复用 Shell 暴露的 `GraphQLProvider`(urql client 单例),student-portal **不重复创建** GraphQL client +- 不独立提供 RootLayout / 字体加载 / 设计令牌 / i18n Provider / 登录页,全部由 Shell 提供(ARB-002:登录页 P2 不走 MF) ## 2. 我的限界上下文 ### 2.1 我负责的聚合 / 实体(前端视图模型) -- 作答、作业提交、学情诊断、错题本(学习场景域前端视图) +- 考试作答(ExamTaking)、考试草稿(ExamTakingDraft)、作业提交(HomeworkSubmit) +- 学情诊断(Diagnostic)、错题本(Weakness)、学习路径(LearningPath) - 会话状态(Session)、视口(Viewport)、权限(Permission)— 与 Shell 共享,引用 teacher-portal 文档 ### 2.2 业务领域 @@ -43,73 +58,105 @@ - 班级/考试/作业 CRUD 管理(归 teacher-portal) - 用户/角色/权限 CRUD(归 admin-portal) - 家长多子女切换(归 parent-portal) +- 教师沟通(归 teacher-portal P7+) +- 成绩录入(归 teacher-portal,学生仅查看) ### 2.4 数据范围 -- DataScope **L0(仅本人)**:学生只能看到自己的作业、考试、成绩、学情、错题 +- DataScope **L0(仅本人)**:学生只能看到自己的作业、考试、成绩、学情、错题、考勤 +- 例外:班级排名、班级均分等聚合数据由 student-bff 聚合返回,学生不可见其他同学个体数据 ## 3. 我与外部的契约 ### 3.1 消费的后端 API(经 api-gateway 代理) -| 路径前缀 | 下游 BFF/服务 | 关键端点 | -| ------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | -| `/api/v1/student/*` | student-bff | `GET /student/viewports`、`GET /student/dashboard`、`GET /student/homework`、`POST /student/homework/:id/submit`、`GET /student/diagnostic` | -| `/api/v1/iam/*` | iam | `POST /iam/login`、`GET /iam/me`、`GET /iam/effective-permissions` | -| `/api/v1/notifications/*` | msg | 通知中心(P5) | +| 路径前缀 | 下游 BFF/服务 | 关键端点 | +| ------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `POST /api/auth/login` | api-gateway | 学生登录(api-gateway 聚合 iam gRPC,返回 JWT + UserInfo) | +| `POST /api/v1/student/graphql` | student-bff | GraphQL 端点(dashboard / currentUser / myClasses / myExams / myHomework / submitHomework / myGrades / myAttendance / textbooks / chapters / learningPath / studentDashboard / myWeakness / myTrend / myNotifications / markAsRead) | +| `GET /api/v1/notifications/*` | msg + push-gateway | 通知中心(P5,HTTP 长轮询降级) | -> student-bff 由 ai04 设计,聚合 iam + core-edu + data-ana,为学生场景提供聚合视图。student-portal 主要消费 student-bff,少量直连 iam(登录/权限/视口)。 +> **协议说明**(ARB-001 已裁决):student-bff 是 GraphQL 聚合层,前端 all-in GraphQL,**不再消费 REST**。除登录(`POST /api/auth/login`)和通知中心降级(P5+)外,全部业务请求经 GraphQL endpoint。student-bff 由 ai04 设计,聚合 iam + core-edu + content + data-ana + msg,为学生场景提供聚合视图。 + +### 3.1.1 API 契约版本演进策略 + +| 版本信号 | 携带位置 | 演进规则 | +| ----------- | --------------------------------------------- | ---------------------------------------------------------------------------------------------------- | +| 主版本 | URL 路径 `/api/v1/*` → `/api/v2/*` | 破坏性变更升主版本,student-portal 同时支持 v1 + v2 至少 1 个迭代周期(4 周),通过 Feature Flag 切换 | +| GraphQL | schema 内 `@deprecated` + schema registry | 字段废弃用 `@deprecated` 标注,student-portal 监控使用率,< 1% 后移除调用 | +| 子版本 | 响应头 `X-API-Version: 2026-07-10` | 向后兼容字段新增,前端忽略未知字段(Zod 默认行为) | +| Deprecation | 响应头 `Deprecation: true` + `Sunset: ` | 前端收到 Deprecation 头后上报埋点,跟踪使用率 | + +> student-portal 不主动驱动 API 版本升级;契约变更由 coord 协调各业务 AI 落地。student-portal 仅负责消费侧的兼容与迁移。 ### 3.2 统一响应契约 -所有后端响应遵循 `ActionState` 结构(迁移指南 §7.5): +所有 GraphQL 响应遵循 **ActionState 信封**(ARB-001 §1.3 + 总裁裁决 §3.4 方案 B 降级模式): ```typescript -type ActionState = - | { success: true; data: T } - | { - success: false; - error: { code: string; message: string; details?: unknown }; +// GraphQL 响应信封(与 teacher-bff 一致) +type GraphQLResponse = { + data: T | null; + errors: Array<{ + code: string; // 错误码前缀如 IAM_/CORE_EDU_/BFF_STUDENT_/GW_ + message: string; + path: Array; + extensions?: { + degraded?: boolean; // 降级模式标记 + partial?: boolean; // 部分聚合失败 + traceId?: string; }; + }> | null; +}; + +// 业务错误码(前端 i18n 路由) +type ActionError = { + code: string; // 如 BFF_STUDENT_UPSTREAM_UNAVAILABLE + message: string; + details?: unknown; +}; ``` -错误码前缀按服务名大写(如 `IAM_`、`CORE_EDU_`、`EXAMS_`、`HOMEWORK_`、`GRADES_`、`BFF_STUDENT_`、`GW_`、`NETWORK_`)。前端 API 请求层根据 `error.code` 前缀路由到对应的 i18n key。 +错误码前缀按服务名大写(如 `IAM_`、`CORE_EDU_`、`BFF_STUDENT_`、`GW_`、`NETWORK_`)。前端 GraphQL 请求层根据 `extensions.code` 前缀路由到对应的 i18n key。 ### 3.3 推送契约(P5) -| 协议 | 场景 | -| ------------------------- | ------------------------------------ | -| WebSocket(push-gateway) | 考试发布通知、成绩发布、作业截止提醒 | +| 协议 | 场景 | 降级 | +| ------------------------- | ------------------------------------ | ----------------------------------- | +| WebSocket(push-gateway) | 考试发布通知、成绩发布、作业截止提醒 | HTTP 长轮询(60s 拉取通知列表) | +| HTTP 长轮询(P5+) | WebSocket 重连 5 次失败后降级 | 通知延迟最多 60s,UI 顶部提示降级条 | ### 3.4 proto 不直接消费 -前端不调用 gRPC,BFF 把 gRPC 聚合为 REST 暴露给前端。前端仅消费 `packages/contracts/src/permissions.ts` 中的权限点常量(TS 文件,非 proto 生成)。 +前端不调用 gRPC,student-bff 把 gRPC 聚合为 GraphQL 暴露给前端。前端仅消费 `packages/contracts/src/permissions.ts` 中的权限点常量(TS 文件,非 proto 生成)。 ## 4. 我的技术栈 -| 维度 | 选型 | 说明 | -| --------------------------- | -------------------------------------------------------- | ---------------------------------------------- | -| 框架 | Next.js 14+(App Router) | server components 默认,client components 按需 | -| 语言 | TypeScript 5.5+(strict) | 沿用 tsconfig.base.json | -| 微前端 | Module Federation 2.0(@module-federation/nextjs-mf) | student-portal = Remote | -| 样式 | Tailwind CSS 3.4+ | 配合设计令牌三层模型(复用 Shell 提供的令牌) | -| UI 组件库 | shadcn/ui(迁移指南 §7.2) | 复用 Shell 暴露的 `packages/ui-components/` | -| 状态管理 L1 URL | nuqs | 可分享、可刷新状态 | -| 状态管理 L2 Server | TanStack Query v5 | 服务端数据缓存、重试、乐观更新 | -| 状态管理 L3 Client Business | Zustand slice | 客户端业务状态(考试作答草稿、倒计时) | -| 状态管理 L4 Global UI | Zustand ui-store + ModalRoot | 全局 UI 状态(复用 Shell) | -| 状态管理 L5 Form | react-hook-form + zodResolver | 表单状态(作业提交表单) | -| 富文本 | **不使用**(学生不作答富文本,作业提交用表单) | 与 teacher-portal 差异点 | -| 图表 | recharts | 学情诊断、Dashboard | -| i18n | next-intl | 复用 Shell Provider,按 scope=student 加载翻译 | -| A11y | eslint-plugin-jsx-a11y(error 级) | WCAG 2.2 AA | -| 字体 | Inter(sans)/ Fraunces(serif)/ JetBrains Mono(mono) | 复用 Shell 的 next/font/google 加载 | +| 维度 | 选型 | 说明 | +| --------------------------- | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------- | +| 框架 | Next.js 14+(App Router) | server components 默认,client components 按需;MF Remote 优先 CSR(考试作答页禁用 SSR 防缓存) | +| 语言 | TypeScript 5.5+(strict) | 沿用 tsconfig.base.json | +| 微前端 | Module Federation 2.0(@module-federation/nextjs-mf) | student-portal = Remote(ARB-002 P3 首个 Remote) | +| 数据请求 | **urql GraphQL client**(Shell 暴露单例,ARB-002) | all-in GraphQL,不再用 REST ApiClient | +| 样式 | Tailwind CSS 3.4+ | 配合设计令牌三层模型(复用 Shell 提供的令牌) | +| UI 组件库 | shadcn/ui(迁移指南 §7.2) | 复用 Shell 暴露的 `packages/ui-components/` | +| 状态管理 L1 URL | nuqs | 可分享、可刷新状态(考试作答页 URL 不携带答案,防泄露) | +| 状态管理 L2 Server | TanStack Query v5 | GraphQL query 缓存、重试、乐观更新(urql 与 TanStack Query 协同,urql 作为 fetcher) | +| 状态管理 L3 Client Business | Zustand slice | 客户端业务状态(考试作答草稿、倒计时、断网队列) | +| 状态管理 L4 Global UI | Zustand ui-store + ModalRoot | 全局 UI 状态(复用 Shell) | +| 状态管理 L5 Form | react-hook-form + zodResolver | 表单状态(作业提交表单、附件上传) | +| 富文本 | **不使用**(学生不作答富文本,作业提交用表单) | 与 teacher-portal 差异点;客观题用单选/多选/填空,主观题用 textarea | +| 图表 | recharts | 学情诊断、Dashboard、错题本掌握度 | +| i18n | next-intl | 复用 Shell Provider,按 scope=student 加载翻译 | +| A11y | eslint-plugin-jsx-a11y(error 级) | WCAG 2.2 AA;考试作答页额外要求键盘可操作 + 屏幕阅读器友好 | +| 字体 | Inter(sans)/ Fraunces(serif)/ JetBrains Mono(mono) | 复用 Shell 的 next/font/google 加载 | +| 考试作答专用 | — | 倒计时(基于服务器时间)+ 自动保存(HTTP POST 每 30s + blur)+ 断网恢复(localStorage 草稿) | ## 5. 我的阶段归属 - **阶段**:P3 -- **当前状态**:📐 待设计(待 core-edu + student-bff 就绪),依赖上游阶段 P3 -- **依赖上游阶段**:P1(api-gateway + iam)+ P2(teacher-portal Shell 就绪)+ P3(core-edu + student-bff) +- **当前状态**:📐 待设计(待 core-edu + student-bff 就绪),apps/student-portal/ 目录为空(仅 docs/),依赖上游阶段 P3 +- **依赖上游阶段**:P1(api-gateway + iam)+ P2(teacher-portal Shell 就绪 + ARB-002 MF 配置完成)+ P3(core-edu + student-bff) ## 6. 我需要对齐的黄金模板项(对照 classes 服务) @@ -118,18 +165,19 @@ type ActionState = | 对齐项 | classes(后端黄金模板) | student-portal 前端等价 | 当前状态 | | --------------------- | ------------------------------------- | ------------------------------------------------------------------------ | ----------------------------------- | | 权限校验 | `@RequirePermission(Permissions.XXX)` | `usePermission().hasPermission("XXX")` Hook + `` 组件 | ❌ 待建(复用 Shell 暴露的 hooks) | -| 错误码前缀统一 | `CLASSES_*`、`IAM_*` | API 请求层根据 `error.code` 前缀路由 i18n | ❌ 待建(复用 Shell ApiClient) | +| 错误码前缀统一 | `CLASSES_*`、`IAM_*` | GraphQL 请求层根据 `extensions.code` 前缀路由 i18n | ❌ 待建(复用 Shell urql client) | | logger | pino | 前端 console + Sentry(P6) | ❌ 待建(复用 shared-ts Logger) | | metrics | prom-client `/metrics` | 前端 Web Vitals → Gateway 上报 | ❌ 待建 | | tracer | OTel SDK | 前端 OTel browser SDK(P6) | ❌ 待建 | | /healthz + /readyz | `GET /healthz` `GET /readyz` | Next.js `/api/health` route + Dockerfile HEALTHCHECK | ❌ 待建 | -| 优雅关闭 | SIGTERM handler | Next.js 无长连接,无需 | ✅ N/A | +| 优雅关闭 | SIGTERM handler | Next.js 无长连接(除 WS),无需 | ✅ N/A | | 测试覆盖率 ≥ 80% | Vitest | Vitest + @testing-library/react + Playwright E2E | ❌ 待建 | | Dockerfile 多阶段构建 | builder + runtime | builder + runtime | ❌ 待建 | | Zod 输入验证 | class-validator + Zod schema | react-hook-form + zodResolver | ❌ 待建 | -| GlobalErrorFilter | NestJS 全局异常过滤器 | React ErrorBoundary + API 请求层统一错误处理 | ❌ 待建(复用 Shell ErrorBoundary) | +| GlobalErrorFilter | NestJS 全局异常过滤器 | React ErrorBoundary + GraphQL 请求层统一错误处理 | ❌ 待建(复用 Shell ErrorBoundary) | | 设计令牌三层 | — | 复用 Shell 提供的 primitive/semantic-light/dark/tailwind-theme | ❌ 待建(依赖 ui-tokens 包) | | A11y 工具集 | — | useA11yId / mergeA11yProps / describeInput / focus-trap | ❌ 待建(复用 Shell 暴露的 hooks) | +| GraphQL client 单例 | — | 复用 Shell 暴露的 urql client(ARB-002) | ❌ 待建 | --- @@ -140,43 +188,50 @@ type ActionState = | 维度 | 状态 | 说明 | | ------------------------------------ | ------ | ---------------------------------------------------- | | 权限装饰器(前端等价 usePermission) | ❌ | 待建,复用 Shell 暴露的 `usePermission` Hook | -| 错误码前缀 | ❌ | 待建,复用 Shell 暴露的 ApiClient | +| 错误码前缀 | ❌ | 待建,复用 Shell 暴露的 urql client + 错误扩展 | | logger | ❌ | 待建,复用 shared-ts Logger | | metrics | ❌ | 待建,Web Vitals 上报 | | tracer | ❌ | 待建,OTel browser SDK | | /healthz | ❌ | 待建,Next.js `/api/health` route | | /readyz | ❌ | 待建,Next.js `/api/ready` route | | 优雅关闭 | ✅ N/A | Next.js 无长连接 | -| 测试覆盖率 | ❌ | 待建,目标 ≥ 80% | +| 测试覆盖率 | ❌ | 0%,无测试文件(待建,目标 ≥ 80%) | | Dockerfile 多阶段 | ❌ | 待建,builder + runtime | | Zod 输入验证 | ❌ | 待建,react-hook-form + zodResolver | | GlobalErrorFilter(ErrorBoundary) | ❌ | 待建,复用 Shell ErrorBoundary | | 设计令牌三层 | ❌ | 待建,复用 ui-tokens 包 | | A11y 工具集 | ❌ | 待建,复用 hooks 包 | -| Module Federation 配置 | ❌ | 待建,Remote 角色 | +| Module Federation 配置 | ❌ | 待建,Remote 角色(ARB-002) | | 5 层状态管理 | ❌ | 待建,复用 Shell Provider | | 共享组件库 | ❌ | 待建,复用 Shell 暴露的 ui-components | | i18n | ❌ | 待建,复用 Shell Provider + scope=student 翻译 | -| API 请求层 | ❌ | 待建,复用 Shell ApiClient,仅注入不同 baseUrl/token | +| GraphQL 请求层 | ❌ | 待建,复用 Shell 暴露的 urql client 单例(ARB-002) | | ESLint flat config 自定义规则 | ❌ | 待建,与 Shell 共用配置 | +| 考试作答自动保存 | ❌ | 待建,HTTP POST 每 30s + blur + localStorage 草稿 | +| 考试倒计时(服务器时间对齐) | ❌ | 待建,基于服务器 `expiresAt` | +| 断网恢复队列 | ❌ | 待建,IDB 队列 + 重连重试 | ### 现有文件清单 ``` -apps/student-portal/ # 空目录,待建 +apps/student-portal/ +└─ docs/ + ├─ 01-understanding.md # 本文件(v2) + └─ 02-architecture-design.md # v2 ``` -> student-portal 当前为空目录,所有维度均为 ❌ 待建状态。无现有文件清单。本设计文档作为 P3 起步的输入。 +> student-portal 当前为空目录(仅 docs/),所有维度均为 ❌ 待建状态。无现有文件、无现有代码、无现有违规点。P3 阶段从零开始搭建。 ### 主要待建项(必须在 P3 起步时建立) -1. **MF Remote 配置**:`next.config.js` 配置 `name: 'student_app'`、`exposes`、`remotes: { teacher: ... }` -2. **路由表**:`/student/dashboard`、`/student/homework`、`/student/homework/:id/submit`、`/student/exams`、`/student/exams/:id/take`、`/student/diagnostic`、`/student/weakness`、`/student/notifications` -3. **ExamTaking 组件**:考试作答(倒计时 + 自动保存),student-portal 特有 +1. **MF Remote 配置**:`next.config.js` 配置 `name: 'student_app'`、`exposes`、`remotes: { teacher: ... }`(ARB-002 MF URL 用 4000 端口) +2. **路由表**(对齐 student-portal_contract.md §1.2):`/dashboard`、`/my-homework`、`/my-homework/:id/submit`、`/my-exams`、`/my-exams/:id/take`、`/my-exams/:id/result`、`/my-grades`、`/my-attendance`、`/learning-path`、`/diagnostic`、`/weakness`、`/notifications`、`/my-schedule` +3. **ExamTaking 组件**:考试作答(倒计时基于服务器时间 + 自动保存每 30s + blur + 断网恢复) 4. **作业提交表单**:react-hook-form + zodResolver,不用 Tiptap 5. **Dockerfile 多阶段构建**:builder + runtime + HEALTHCHECK -6. **Vitest + Playwright 测试**:覆盖率 ≥ 80% +6. **Vitest + Playwright 测试**:覆盖率 ≥ 80%(含考试作答边界场景 E2E) 7. **`/api/health` + `/api/ready` route**:健康检查端点 +8. **urql GraphQL 查询**:复用 Shell 单例 client,按 GraphQL 查询域封装 hooks --- @@ -184,27 +239,38 @@ apps/student-portal/ # 空目录,待建 | 视口 key | 文案 | 路由 | 权限 | 阶段 | | --------------- | --------- | ------------------------ | ------------------------ | ---- | -| `dashboard` | Dashboard | `/student/dashboard` | `STUDENT_DASHBOARD_VIEW` | P3 | -| `homework` | 我的作业 | `/student/homework` | `HOMEWORK_READ_OWN` | P3 | -| `exams` | 我的考试 | `/student/exams` | `EXAMS_READ_OWN` | P3 | -| `diagnostic` | 学情诊断 | `/student/diagnostic` | `DIAGNOSTIC_READ_OWN` | P4 | -| `weakness` | 错题本 | `/student/weakness` | `WEAKNESS_READ_OWN` | P4 | -| `notifications` | 通知中心 | `/student/notifications` | `NOTIFICATION_READ_OWN` | P5 | +| `dashboard` | Dashboard | `/dashboard` | `STUDENT_DASHBOARD_VIEW` | P3 | +| `my-homework` | 我的作业 | `/my-homework` | `HOMEWORK_READ_OWN` | P3 | +| `my-exams` | 我的考试 | `/my-exams` | `EXAMS_READ_OWN` | P3 | +| `my-grades` | 我的成绩 | `/my-grades` | `GRADES_READ_OWN` | P3 | +| `my-attendance` | 我的考勤 | `/my-attendance` | `ATTENDANCE_READ_OWN` | P3 | +| `learning-path` | 学习路径 | `/learning-path` | `LEARNING_PATH_VIEW` | P4 | +| `diagnostic` | 学情诊断 | `/diagnostic` | `DIAGNOSTIC_READ_OWN` | P4 | +| `weakness` | 错题本 | `/weakness` | `WEAKNESS_READ_OWN` | P4 | +| `notifications` | 通知中心 | `/notifications` | `NOTIFICATION_READ_OWN` | P5 | +| `my-schedule` | 我的课表 | `/my-schedule` | `SCHEDULE_READ_OWN` | P5+ | -> 来源:`GET /api/v1/student/viewports`(student-bff 聚合 iam 视口配置),AppShell 按 `scope=student` 过滤渲染。 +> 来源:student-bff GraphQL `viewports` query(聚合 iam 视口配置),AppShell 按 `scope=student` 过滤渲染。 ## 8. L2 路由表 -| 路由 | 页面 | 权限 | 阶段 | -| ------------------------------ | ---------- | ------------------------ | ---- | -| `/student/dashboard` | 学生仪表盘 | `STUDENT_DASHBOARD_VIEW` | P3 | -| `/student/homework` | 我的作业 | `HOMEWORK_READ_OWN` | P3 | -| `/student/homework/:id/submit` | 提交作业 | `HOMEWORK_SUBMIT` | P3 | -| `/student/exams` | 我的考试 | `EXAMS_READ_OWN` | P3 | -| `/student/exams/:id/take` | 作答考试 | `EXAMS_TAKE` | P3 | -| `/student/diagnostic` | 学情诊断 | `DIAGNOSTIC_READ_OWN` | P4 | -| `/student/weakness` | 错题本 | `WEAKNESS_READ_OWN` | P4 | -| `/student/notifications` | 通知中心 | `NOTIFICATION_READ_OWN` | P5 | +| 路由 | 页面 | 权限 | 阶段 | +| ------------------------------- | ---------- | ------------------------ | ---- | +| `/dashboard` | 学生仪表盘 | `STUDENT_DASHBOARD_VIEW` | P3 | +| `/my-homework` | 我的作业 | `HOMEWORK_READ_OWN` | P3 | +| `/my-homework/:id/submit` | 提交作业 | `HOMEWORK_SUBMIT` | P3 | +| `/my-exams` | 我的考试 | `EXAMS_READ_OWN` | P3 | +| `/my-exams/:id/take` | 作答考试 | `EXAMS_TAKE` | P3 | +| `/my-exams/:id/result` | 考试结果 | `EXAMS_RESULT_VIEW` | P3 | +| `/my-grades` | 我的成绩 | `GRADES_READ_OWN` | P3 | +| `/my-attendance` | 我的考勤 | `ATTENDANCE_READ_OWN` | P3 | +| `/learning-path` | 学习路径 | `LEARNING_PATH_VIEW` | P4 | +| `/diagnostic` | 学情诊断 | `DIAGNOSTIC_READ_OWN` | P4 | +| `/weakness` | 错题本 | `WEAKNESS_READ_OWN` | P4 | +| `/notifications` | 通知中心 | `NOTIFICATION_READ_OWN` | P5 | +| `/my-schedule` | 我的课表 | `SCHEDULE_READ_OWN` | P5+ | + +> 路由前缀**不带** `/student/`(student-portal 是独立 dev server :4001,挂载到 Shell 后由 Shell 路由表统一前缀)。L3 组件级视口用 ``。权限点后缀 `_OWN` 强调学生仅能操作自己的数据(DataScope L0)。 ## 9. L3 组件级差异(student-portal 特有) @@ -218,15 +284,20 @@ apps/student-portal/ # 空目录,待建 - `DataTable`(表格) - `Form`(react-hook-form + zodResolver 封装) - `Chart`(recharts 封装) +- `GraphQLProvider`(urql client 单例,ARB-002) ### 9.2 student-portal 特有组件 -| 组件 | 用途 | 来源 | -| ----------------- | --------------------------------------------- | ---- | -| `ExamTaking` | 考试作答(倒计时 + 自动保存) | 新建 | -| `HomeworkSubmit` | 作业提交表单(react-hook-form + zodResolver) | 新建 | -| `DiagnosticChart` | 学情诊断图表(recharts 多维雷达 + 趋势线) | 新建 | -| `WeaknessList` | 错题本列表(按知识点聚合 + 掌握度标签) | 新建 | +| 组件 | 用途 | 来源 | 是否 MF 暴露 | +| ----------------- | --------------------------------------------- | ---- | --------------------------------------- | +| `ExamTaking` | 考试作答(倒计时 + 自动保存 + 断网恢复) | 新建 | ✅ 暴露 `./ExamTaking`(供 Shell 路由复用) | +| `HomeworkSubmit` | 作业提交表单(react-hook-form + zodResolver) | 新建 | ❌ 内部使用 | +| `DiagnosticChart` | 学情诊断图表(recharts 多维雷达 + 趋势线) | 新建 | ❌ 内部使用 | +| `WeaknessList` | 错题本列表(按知识点聚合 + 掌握度标签) | 新建 | ❌ 内部使用 | +| `LearningPathMap` | 学习路径图(知识点前置依赖可视化) | 新建 | ❌ 内部使用 | +| `ExamResultView` | 考试结果页(得分 + 错题分析 + 知识点掌握度) | 新建 | ❌ 内部使用 | +| `CountdownTimer` | 倒计时组件(基于服务器时间,避免客户端篡改) | 新建 | ❌ 内部使用 | +| `DraftRecovery` | 草稿恢复弹窗(断网恢复后提示是否恢复作答) | 新建 | ❌ 内部使用 | ### 9.3 不使用的组件(与 teacher-portal 差异) @@ -234,176 +305,571 @@ apps/student-portal/ # 空目录,待建 - 不使用 `SSEViewer`:学生不参与 AI 出题 - 不使用 `ChildSwitcher`:学生无多子女切换(家长端特有) - 不使用 `UserManagementTable`:学生不管理用户 +- 不使用 `RolePermissionMatrix`:学生不管理权限 ## 10. L4 数据层差异 | 维度 | teacher-portal | student-portal | | ---------- | ------------------------- | -------------------------------------------------- | -| 主要数据源 | teacher-bff(聚合多服务) | student-bff(聚合 iam + core-edu + data-ana) | -| 缓存策略 | 5min 中等缓存 | 5-30s 短缓存,作业列表 30s | +| 主要数据源 | teacher-bff(聚合多服务) | student-bff(聚合 iam + core-edu + content + data-ana + msg) | +| 协议 | GraphQL(urql) | GraphQL(urql,复用 Shell 单例) | +| 缓存策略 | 5min 中等缓存 | 5-30s 短缓存,作业列表 30s,考试作答页 0s(禁缓存)| | 数据范围 | L1-L5(按角色) | L0(仅本人) | -| 特殊状态 | — | 考试作答草稿(Zustand L3,断网恢复)+ 倒计时(L3) | +| 特殊状态 | — | 考试作答草稿(Zustand L3 + localStorage + IDB,断网恢复)+ 倒计时(L3,基于服务器时间)+ 断网队列(IDB) | +| SSR 策略 | dashboard SSR | dashboard SSR(首屏);考试作答页强制 CSR(防缓存) | -## 11. 与其他模块的交互点(契约清单) +## 11. 考试作答边界场景(学生端特有,必须覆盖) -| 方向 | 对方服务 | 协议 | 接口/事件 | 用途 | 阶段 | -| ------ | ------------ | ------------------ | ------------------------------------ | ---------------------------- | ---- | -| 调用 | api-gateway | HTTP/REST | `/api/v1/*` 代理 | 全部业务请求 | P1+ | -| 调用 | push-gateway | WebSocket | `ws://push-gateway/ws` | 实时推送 | P5 | -| 被调用 | — | — | — | 前端不暴露接口给其他服务 | — | -| 消费 | student-bff | HTTP(经 Gateway) | `GET /student/viewports` 等 | 学生场景聚合 | P3+ | -| 消费 | iam | HTTP(经 Gateway) | `/iam/*` | 登录/权限/视口 | P2+ | -| 消费 | core-edu | HTTP(经 Gateway) | `/exams/*` `/homework/*` `/grades/*` | 教学核心(学生视角) | P3+ | -| 消费 | data-ana | HTTP(经 Gateway) | `/analytics/*` | 学情分析 | P4+ | -| 消费 | msg | HTTP(经 Gateway) | `/notifications/*` | 通知中心 | P5+ | -| 依赖 | coord 维护 | — | `packages/shared-proto` | TS 类型(仅 contracts 部分) | P1+ | -| 依赖 | coord 维护 | — | `packages/shared-ts`(待建) | ApiClient/Logger/通用工具 | P3+ | -| 依赖 | ai07 维护 | — | `packages/ui-tokens`(待建) | 三层设计令牌 | P3+ | -| 依赖 | ai07 维护 | — | `packages/ui-components`(待建) | shadcn + 共享组件 | P3+ | -| 依赖 | ai07 维护 | — | `packages/hooks`(待建) | usePermission/useAuth 等 | P3+ | -| 依赖 | coord 维护 | — | `packages/contracts`(待建) | Permissions 常量 + 类型 | P3+ | +> 考试作答是学生端最复杂、最易出问题的场景,必须在架构中预留所有边界场景的处理。本节是 ai14 新增。 -## 12. 事件设计(P5 WebSocket 推送) +### 11.1 网络与设备边界 -| 事件 | 触发 | student-portal 前端动作 | -| ----------------------------- | -------------- | ------------------------------ | -| `NotificationRequested` | msg 服务投递 | toast 提示 + 通知中心未读数 +1 | -| `ExamPublished` | 教师发布考试 | toast + dashboard invalidate | -| `GradeRecorded` | 教师录入成绩 | toast + 成绩列表 invalidate | -| `HomeworkDeadlineApproaching` | 作业截止前提醒 | toast + 作业列表高亮 | +| 场景 | 触发条件 | 前端处理 | 后端契约依赖 | +| ------------------------ | ------------------------------ | -------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | +| 作答中断网 | 学生作答过程中网络中断 | 自动保存失败入 IDB 队列;UI 显示"离线模式"标识;继续作答;网络恢复后批量重试 | `POST /api/v1/student/graphql` mutation `saveExamAnswer` | +| 作答中刷新页面 | 学生误刷新或浏览器崩溃 | Zustand L3 + localStorage + IDB 三级草稿恢复;进入考试页时检测未提交草稿,弹 `DraftRecovery` 提示是否恢复 | 无(纯前端恢复) | +| 作答中关闭浏览器 | 学生主动关闭 | 同上,下次进入考试页恢复草稿 | 无 | +| 作答中切到后台标签 | 学生切换标签(疑似作弊) | `visibilitychange` 事件记录切换次数 + 时长;超过阈值(如 3 次)警告;服务端最终判定(前端仅记录) | `mutation recordExamSuspiciousBehavior`(待 ai04 确认) | +| 作答中设备时间被篡改 | 学生修改系统时间影响倒计时 | 倒计时基于服务器返回的 `expiresAt`(ISO 8601 UTC),前端仅做展示;提交以服务器时间为准 | `query myExams { expiresAt }` | +| 作答提交后网络超时 | 提交响应未到达但服务端已处理 | 客户端重试前先 query 提交状态;若已提交则跳转结果页,避免重复提交 | `query examSubmissionStatus(examId)` | -## 13. 横切关注点对齐清单 +### 11.2 时间边界 -### 13.1 权限(前端等价) +| 场景 | 触发条件 | 前端处理 | 后端契约依赖 | +| ------------------------ | ------------------------------ | -------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | +| 考试时间到自动提交 | 倒计时归零 | 前端触发自动提交 mutation;若失败入 IDB 队列重试;UI 显示"时间到,正在提交" | `mutation submitExam` | +| 服务器时间与客户端偏差 | 客户端时间快/慢于服务器 | 进入考试页时同步服务器时间差(`serverTime - clientTime`),倒计时按校正后的时间计算;偏差 > 5s 时提示 | `query serverTime` | +| 考试开始前进入 | 早于 `startsAt` | 显示"考试未开始"倒计时;禁用作答区 | `query myExams { startsAt expiresAt }` | +| 考试结束后进入 | 晚于 `expiresAt` | 跳转结果页(若已提交)或"考试已结束"提示(若未提交,按缺考处理) | `query examResult(examId)` | +| 考试延时 | 教师临时延长考试时间 | WebSocket 事件 `ExamExtended` → 重新拉取 `expiresAt` → 更新倒计时 | WebSocket event `ExamExtended`(待 ai10 msg 确认) | -见 §8 L2 路由表权限列。完整权限点常量集中在 `packages/contracts/src/permissions.ts`(待建立,coord 负责 contracts,ai07 负责调用)。L3 组件级视口用 ``。 +### 11.3 作答内容边界 -### 13.2 错误码清单(前端 i18n 路由) +| 场景 | 触发条件 | 前端处理 | 后端契约依赖 | +| ------------------------ | ------------------------------ | -------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | +| 客观题单选/多选/填空 | 默认题型 | Zustand L3 存 `answers: Record`;UI 用 Radio/Checkbox/TextInput | `mutation saveExamAnswer` | +| 主观题文本作答 | 简答题/论述题 | textarea + 字数统计;不使用富文本(与 teacher-portal 差异) | 同上 | +| 附件上传(主观题照片) | 学生拍照上传手写答案 | 文件大小限制(≤ 10MB)+ 类型限制(jpg/png/pdf)+ 分片上传;上传中 UI 显示进度 | `mutation uploadAttachment`(待 ai04 确认) | +| 答案序号变更 | 教师调整题目顺序(考试中) | WebSocket 事件 `ExamQuestionReordered` → 重新拉取题目 → 草稿按 questionId 映射(不依赖序号) | WebSocket event `ExamQuestionReordered`(待 ai10 确认) | +| 答案为空提交 | 学生未作答部分题目 | 提交前弹窗确认"还有 N 题未作答,确认提交?";学生确认后才提交 | 无(前端校验) | -| 前缀 | 来源服务 | i18n key 模式 | -| -------------- | ----------- | ------------------------- | -| `IAM_` | iam | `iam.error.{{code}}` | -| `CORE_EDU_` | core-edu | `coreEdu.error.{{code}}` | -| `EXAMS_` | core-edu | `exams.error.{{code}}` | -| `HOMEWORK_` | core-edu | `homework.error.{{code}}` | -| `GRADES_` | core-edu | `grades.error.{{code}}` | -| `BFF_STUDENT_` | student-bff | `bff.error.{{code}}` | -| `GW_` | api-gateway | `gateway.error.{{code}}` | -| `NETWORK_` | 前端网络层 | `network.error.{{code}}` | +### 11.4 防作弊边界(前端配合,服务端最终判定) -### 13.3 Logger - -复用 `packages/shared-ts/src/logger.ts`(同 teacher-portal),开发环境 console + 结构化,生产环境 → Sentry(P6)。必含字段:trace_id、user_id、scope=student、path。 - -### 13.4 Metrics(Web Vitals) - -| 指标 | 类型 | 上报 | -| ----------------------------- | ---- | --------------------------------------------------- | -| `student_portal_lcp_seconds` | LCP | `next/web-vitals` → `POST /api/v1/admin/web-vitals` | -| `student_portal_cls` | CLS | 同上 | -| `student_portal_fid_seconds` | FID | 同上 | -| `student_portal_ttfb_seconds` | TTFB | 同上 | - -P6 接入,P3-P5 暂缓。 - -### 13.5 Tracer(OTel browser SDK,P6) - -复用 `packages/shared-ts/src/tracer.ts`(同 teacher-portal)。BatchSpanProcessor → OTLP exporter → collector → Tempo。自动埋点:fetch、XMLHttpRequest、document load、user interaction。 - -### 13.6 健康检查 - -| 端点 | 用途 | 实现 | -| ----------------- | ---------------------- | -------------------------------------------------------------- | -| `GET /api/health` | Dockerfile HEALTHCHECK | Next.js Route Handler,返回 `{ status: 'ok', ts: Date.now() }` | -| `GET /api/ready` | K8s readinessProbe | 检查 `process.env.API_GATEWAY_URL` 可达 + 内存 < 阈值 | - -### 13.7 优雅关闭 - -Next.js 无长连接(除 SSE/WS),无需特殊处理。WS 在 P5 由 push-gateway 管理,前端断线自动重连。 - -## 14. 风险与假设 - -### 14.1 假设 - -1. **假设 coord 建立 `packages/shared-ts`、`packages/contracts`**:包含 ApiClient、Logger、Permissions 常量、通用类型。若 coord 未建立,ai07 自行在 `apps/student-portal/src/shared/` 内实现,后续提取到 packages。 -2. **假设 ai04 student-bff 提供 `GET /student/viewports`、`GET /student/dashboard`、`GET /student/homework`、`POST /student/homework/:id/submit`、`GET /student/diagnostic`**:返回 `ActionState` 结构。错误码前缀 `BFF_STUDENT_`(待 ai04 确认)。 -3. **假设 teacher-portal Shell 已就绪**:AppShell + 共享依赖暴露 + MF 配置(P2 收尾完成)。 -4. **假设 Next.js 14+ Module Federation 2.0 稳定**:`@module-federation/nextjs-mf` 在 Next.js App Router 下可用。 - -### 14.2 未决设计决策(需 coord 仲裁) - -与 teacher-portal 相同的 4 项(详见 [teacher-portal 阶段 2 §11.3](../../teacher-portal/docs/02-architecture-design.md)): - -1. **packages 归属**:`ui-tokens` / `ui-components` / `hooks` 是 ai07 维护还是 coord 维护? -2. **GraphQL vs REST**:student-bff 是 REST 还是 GraphQL?前端 API 请求层是否需要 GraphQL client? -3. **i18n key 命名**:`error.{{service}}.{{code_snake_case}}` 还是其他模式? -4. **MF 暴露粒度**:Shell 暴露整个 AppShell 还是更细粒度的组件? - -## 15. coord 交叉审查信息 - -### 15.1 端口矩阵 - -| 端 | dev 端口 | 生产端口 | 备注 | -| -------------- | -------- | -------- | ------------- | -| student-portal | 3001 | 3001 | Remote 子应用 | - -### 15.2 依赖的共享包 - -| 包 | 路径 | 维护方 | 内容 | -| --------------- | ------------------------- | ------ | ------------------------------------------------- | -| `shared-ts` | `packages/shared-ts/` | coord | ApiClient、Logger、通用工具 | -| `contracts` | `packages/contracts/` | coord | Permissions 常量、ActionState 类型、UserInfo 类型 | -| `ui-tokens` | `packages/ui-tokens/` | ai07 | 三层设计令牌 | -| `ui-components` | `packages/ui-components/` | ai07 | shadcn + ErrorBoundary + RequirePermission | -| `hooks` | `packages/hooks/` | ai07 | usePermission、useAuth、useViewports | - -### 15.3 依赖的后端契约(需对应 AI 确认) - -| 契约 | 提供方 | 当前状态 | -| ------------------------------------------------------------------ | ------------------ | ------------------- | -| `POST /iam/login`、`GET /iam/effective-permissions`、`GET /iam/me` | iam | ✅ 已实现 | -| `GET /student/viewports`、`GET /student/dashboard` 等 | student-bff | 📐 待 ai04 设计 | -| `/exams/*` `/homework/*` `/grades/*` | core-edu | ✅ 已实现(P3) | -| `/analytics/*` | data-ana | ✅ 已实现(P4 CDC) | -| `/notifications/*` + WebSocket 推送 | msg + push-gateway | 📐 待 P5 | - -### 15.4 错误码前缀(前端 i18n 路由依赖) - -| 前缀 | 服务 | 状态 | -| ------------------------------ | ----------- | --------------- | -| `IAM_` | iam | ✅ 已用 | -| `EXAMS_`/`HOMEWORK_`/`GRADES_` | core-edu | ⚠️ 待确认 | -| `BFF_STUDENT_` | student-bff | ⚠️ 待 ai04 确认 | -| `GW_` | api-gateway | ✅ 已用 | -| `NETWORK_` | 前端 | ai07 自有 | - -### 15.5 不产生 Kafka 事件 - -前端不发布/消费 Kafka 事件。WebSocket 推送由 push-gateway 消费 Kafka 转发。 - -## 16. 实施路线(ai07 自用) - -### P3(student-portal 起步) - -1. 建 `apps/student-portal/`(Remote 角色) -2. 配置 MF(`exposes` pages,`remotes: { teacher: ... }`) -3. 实现 Dashboard + 我的作业 + 提交作业 + 我的考试 + 作答考试 -4. 复用 Shell 的 AppShell + 共享组件 -5. SSE 接入(考试作答自动保存) - -### P5(推送接入) - -1. student-portal 接入 WebSocket(push-gateway) -2. 通知中心 + 作业截止提醒 - -### P6(硬化) - -1. Web Vitals + OTel browser SDK 接入 -2. A11y WCAG 2.2 AA 审计 -3. 性能优化(MF shared 单例验证、bundle 分析) +| 场景 | 触发条件 | 前端处理 | 备注 | +| ------------------------ | ------------------------------ | -------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | +| 切屏检测 | `visibilitychange` 到 hidden | 记录切换次数 + 时长 + 时间戳;超过阈值(如 3 次/分钟)警告;服务端最终判定是否违规 | 仅记录,不阻断作答 | +| 复制粘贴检测 | 监听 `copy`/`paste` 事件 | 阻止默认行为 + 警告;记录次数 | 主观题允许粘贴自己输入的内容(待产品确认) | +| 全屏退出检测 | `fullscreenchange` 事件 | 警告 + 记录;不强制全屏(避免影响体验) | P6+ lockdown 浏览器才强制 | +| 多标签检测 | `BroadcastChannel` 检测同源标签 | 若检测到同源标签,警告"请勿多开标签" | 防止学生开多个标签查答案 | +| 右键禁用 | `contextmenu` 事件 | 考试作答页禁用右键 | 防止查看源码/搜索 | --- -**AI Agent**: ai07 (student-portal remote) -**Branch**: docs/student-portal-stage1-stage2-design-ai07 +## 12. 学生隐私与合规 + +> 学生数据是高敏感数据(含未成年人),student-portal 必须在设计阶段预留合规框架。本节是 ai14 新增,覆盖 COPPA、FERPA、PIPL、未成年人保护法等法规对前端架构的要求。 + +### 12.1 适用法规矩阵 + +| 法规 | 适用范围 | 对前端的要求 | 阶段 | +| -------------- | ------------------ | --------------------------------------------------------------------------- | ----------- | +| COPPA | 美国 <13 岁儿童 | 收集前需家长可验证同意;展示同意记录入口;可删除数据请求入口 | P6 海外扩展 | +| FERPA | 美国教育记录 | 学生有权查看自己教育记录;学校有权限制访问 | P6 海外扩展 | +| PIPL | 中国个人信息保护法 | 隐私政策弹窗 + 同意按钮;敏感信息(成绩)展示前需二次确认;数据导出请求入口 | P3 起强制 | +| GDPR | 欧盟用户 | Cookie 同意管理;被遗忘权请求入口;数据可携带权导出 | P6 海外扩展 | +| 未成年人保护法 | 中国 <18 岁 | 14 岁以下需家长同意;展示适合年龄段的内容;防沉迷时间提醒 | P3 起强制 | + +### 12.2 前端合规设计 + +| 合规点 | 实现位置 | 阶段 | +| ------------------------- | ----------------------------------------------- | ---- | +| 隐私政策同意弹窗 | Shell RootLayout 首次登录后弹窗 | P3 | +| Cookie 同意管理(按类别) | Shell + student-portal 复用 | P3 | +| 成绩展示二次确认 | `/my-grades` 默认遮罩,点击"查看"展示 | P3 | +| 数据导出请求入口 | `/settings#data-export` 页面 | P5 | +| 数据删除请求入口 | `/settings#data-deletion` 页面 | P5 | +| 同意记录查看 | `/settings#consent-history` 页面 | P5 | +| 防沉迷时间提醒 | 连续使用 > 2 小时弹窗提醒休息 | P3 | +| 敏感数据脱敏 | 截图/分享时自动遮罩成绩数字 | P5+ | + +### 12.3 数据保留策略(前端配合) + +| 数据类型 | 前端保留 | 后端保留 | 前端处理 | +| ------------------ | --------------------- | ---------- | ---------------------------- | +| 考试作答草稿 | IDB 永久(直至提交) | 永久 | 提交成功后清除 IDB 草稿 | +| 成绩列表缓存 | 30s(TanStack Query) | 永久 | staleTime 30s 后自动失效 | +| 通知列表 | 30s | 90 天 | 同上 | +| 学情诊断数据 | 30s | 永久 | 同上 | +| 行为埋点(防作弊) | 内存队列 100 条 | 90 天 | 队列满后批量上报,上报后清空 | + +--- + +## 13. 测试策略分层 + +> ai07 初稿仅提到"覆盖率 ≥ 80%",未细化测试类型与覆盖率分目标。ai14 补全。 + +### 13.1 测试金字塔 + +| 层级 | 工具 | 覆盖率目标 | 测试范围 | +| --------- | ------------------------------------------ | ---------- | ----------------------------------------------------------------------------------------------------- | +| 单元测试 | Vitest + @testing-library/react | ≥ 85% | 所有组件渲染/交互、Hook 业务逻辑、Zod schema 校验、纯函数 utils、倒计时计算、草稿恢复逻辑 | +| 集成测试 | Vitest + MSW(Mock GraphQL) | ≥ 75% | urql query + TanStack Query hook 组合、ExamTaking + Zustand slice + 自动保存流程、断网恢复流程 | +| 视觉回归 | Playwright + Percy/Applitools(P6 引入) | 关键页面 | dashboard/my-homework/my-exams/take/my-grades/diagnostic/weakness 七个核心页面在 light/dark + mobile/desktop 4 组合 | +| E2E 测试 | Playwright | 关键路径 | 登录→看 dashboard→作答考试→提交→看成绩→查错题本→登出 | +| A11y 测试 | axe-core + jest-axe + @axe-core/playwright | 0 严重违规 | 所有页面 WCAG 2.2 AA 自动扫描 + 手动键盘导航测试;考试作答页键盘可操作 | +| 性能测试 | Lighthouse CI | ≥ 90 分 | LCP < 2.5s / CLS < 0.1 / TBT < 200ms(移动端 4G 模拟);考试作答页 LCP < 1.5s | +| 契约测试 | Pact(student-bff ↔ student-portal 双向,P6 引入) | 关键 query/mutation | 防止 BFF schema 变更打破前端消费 | + +### 13.2 关键 E2E 场景(必须覆盖) + +```yaml +- name: exam_taking_normal_flow + steps: + - login as student + - navigate to /my-exams + - click exam "期末数学" + - assert /my-exams/:id/take loaded + - assert countdown timer running + - answer question 1 (single choice A) + - answer question 2 (multiple choice A,C) + - assert draft saved to IDB within 30s + - reload page + - assert DraftRecovery dialog shown + - click "恢复作答" + - assert answers restored + - click "提交" + - assert confirm dialog "还有 8 题未作答" + - click "确认提交" + - assert redirect to /my-exams/:id/result + - assert score displayed + +- name: exam_taking_offline_recovery + steps: + - login as student + - enter exam + - answer 3 questions + - simulate offline (Playwright network condition) + - assert "离线模式" indicator shown + - answer 2 more questions + - assert auto-save failed but queued in IDB + - simulate online + - assert queued answers retried and saved + - submit exam + - assert IDB draft cleared + +- name: exam_auto_submit_on_timeout + steps: + - login as student + - enter exam with 60s remaining (mock server time) + - wait 60s + - assert countdown reaches 0 + - assert "时间到,正在提交" shown + - assert redirect to result page + +- name: homework_submit_flow + steps: + - login as student + - navigate to /my-homework + - click homework "数学作业 5" + - assert /my-homework/:id/submit loaded + - fill answers in form + - upload attachment (mock file) + - click submit + - assert success toast + - assert homework list refreshed + +- name: diagnostic_view + steps: + - login as student + - navigate to /diagnostic + - assert DiagnosticChart rendered (radar + trend) + - assert knowledge point mastery displayed + +- name: anti_cheat_detection + steps: + - login as student + - enter exam + - switch to another tab (Playwright) + - switch back + - assert warning toast "请勿切换标签" + - assert suspicious behavior recorded +``` + +### 13.3 Mock 数据策略 + +| 数据来源 | Mock 方式 | 维护方 | +| -------------- | -------------------------------------------------------------------- | ------ | +| GraphQL 响应 | MSW handlers,按 `apps/student-portal/src/mocks/handlers.ts` 集中管理 | ai14 | +| WebSocket 事件 | Mock WebSocket Server(Playwright fixture) | ai14 | +| i18n 文案 | 真实 next-intl messages(不 Mock) | coord | +| 设计令牌 | 真实 ui-tokens(不 Mock) | coord | +| 权限列表 | 按 fixture 角色预设(student_with_exams 等) | ai14 | +| 服务器时间 | MSW 拦截 `serverTime` query 返回固定时间 | ai14 | + +--- + +## 14. 性能预算与代码分割 + +> ai07 初稿未提及性能预算。ai14 补全。 + +### 14.1 性能预算(Bundle Size) + +| 资源类型 | 预算(gzipped) | 备注 | +| ---------------------- | --------------- | ------------------------------------------------- | +| student-portal 首屏 JS | ≤ 80 KB | 含 ExamTaking + Dashboard + 共享依赖分摊 | +| student-portal 首屏 CSS | ≤ 20 KB | 含 Tailwind purged + 设计令牌 | +| 路由级懒加载 chunk | ≤ 30 KB/chunk | 每个二级路由单独 chunk;考试作答页单独 chunk | +| 考试作答页 JS | ≤ 50 KB | 含倒计时 + 自动保存 + 断网恢复逻辑 | +| 图片 | ≤ 100 KB/页 | 学情图表渲染、空态插画 | +| 总下载量(首屏) | ≤ 200 KB | 4G 网络下 LCP < 2.5s;考试作答页 LCP < 1.5s | + +### 14.2 代码分割策略 + +```typescript +// apps/student-portal/src/app/(app)/my-exams/[id]/take/page.tsx +import dynamic from "next/dynamic"; + +const ExamTaking = dynamic(() => import("./ExamTaking"), { + loading: () => , + ssr: false, // 考试作答页强制 CSR,防缓存 + 防预渲染泄露答案 +}); + +const DiagnosticPage = dynamic(() => import("./DiagnosticPage"), { + loading: () => , +}); + +// 学情诊断(重型 recharts)独立 chunk +const WeaknessPage = dynamic(() => import("./WeaknessPage"), { + loading: () => , +}); +``` + +### 14.3 预加载策略 + +| 触发时机 | 预加载内容 | +| ------------------------- | ----------------------------------------------------- | +| Dashboard 加载完成 | 预加载 my-homework chunk + my-exams chunk(最常访问) | +| 鼠标 hover 考试列表项 | 预加载该考试的题目数据(GraphQL prefetch) | +| 通知未读数 > 0 | 预加载 notifications chunk | +| 用户进入 my-grades 页面 | 预加载 diagnostic chunk(趋势图 next-step) | +| 考试开始前 5 分钟 | 预加载 ExamTaking chunk + 题目数据 | + +### 14.4 渲染策略 + +| 页面 | 渲染模式 | 理由 | +| ----------------------- | ------------------------ | ------------------------------------------- | +| `/dashboard` | SSR(首屏)+ CSR(交互) | SEO 无关,但首屏速度 | +| `/my-homework` | CSR + Suspense | 认证后数据,无需 SEO | +| `/my-exams` | CSR | 认证后数据 | +| `/my-exams/:id/take` | **CSR 强制**(ssr: false)| 防缓存 + 防预渲染泄露答案 + 个性化数据 | +| `/my-exams/:id/result` | CSR | 认证后数据 | +| `/my-grades` | CSR + Suspense | 数据频变 | +| `/diagnostic` | CSR + 流式渲染 | 图表渲染慢,流式加载 | +| `/notifications` | CSR + 流式渲染 | 实时性要求 | + +--- + +## 15. 前端安全 + +> ai07 初稿仅在横切关注点提到 401 处理。ai14 补全完整前端安全策略。 + +### 15.1 安全头(HTTP Headers) + +由 teacher-portal Shell 在 `next.config.js` 配置,student-portal 复用: + +| Header | 值 | 用途 | +| --------------------------- | ------------------------------------------------------------ | ------------------------------------ | +| `Content-Security-Policy` | `default-src 'self'; script-src 'self' 'unsafe-inline'; ...` | XSS 防护,MF 远程加载需放行 Shell 域 | +| `X-Frame-Options` | `SAMEORIGIN` | 防止 click-jacking | +| `X-Content-Type-Options` | `nosniff` | 防止 MIME 嗅探 | +| `Referrer-Policy` | `strict-origin-when-cross-origin` | 限制 referrer 泄漏 | +| `Permissions-Policy` | `camera=(), microphone=(), geolocation=()` | 禁用不需要的浏览器能力 | +| `Strict-Transport-Security` | `max-age=31536000; includeSubDomains` | 强制 HTTPS | + +### 15.2 XSS 防护 + +| 场景 | 防护措施 | +| ------------------------ | ---------------------------------------------- | +| 考试题目内容展示 | React 默认转义,禁止 `dangerouslySetInnerHTML` | +| 通知内容(含富文本) | DOMPurify 清洗后渲染(project_rules §4) | +| URL 参数 `?examId=` | Zod 校验为 UUID 格式,禁止任意字符 | +| localStorage 存储草稿 | 仅存答案数据,不存敏感信息;登出时清除 | +| 主观题文本作答 | textarea 默认转义;服务端二次清洗 | + +### 15.3 CSRF 防护 + +- student-portal 仅消费 GraphQL POST + 登录 POST,所有 mutation 经 urql client +- urql client 自动注入 `X-Requested-With: XMLHttpRequest` 头 +- 后端 BFF 校验该头 + 同源 Cookie SameSite=Strict(project_rules §4) + +### 15.4 考试作答安全(前端配合) + +| 安全点 | 前端措施 | 服务端最终判定 | +| ------------------------ | ------------------------------------------------------------ | -------------- | +| 防作弊(切屏/复制/多标签)| §11.4 边界场景记录 | 是 | +| 答案篡改 | 草稿仅前端临时存储,提交时服务端校验题目有效性 + 答案格式 | 是 | +| 时间篡改 | 倒计时基于服务器 `expiresAt`,不依赖客户端时间 | 是 | +| 重复提交 | 提交前 query 提交状态,避免重复 | 是 | +| 越权访问他人考试 | BFF DataScope=L0 校验,前端 URL 篡改 `?examId=` 无效 | 是 | + +### 15.5 敏感数据处理 + +| 数据 | 敏感级别 | 前端处理 | +| -------------- | -------- | -------------------------------------------------- | +| 学生姓名 | 中 | 默认展示,截图时脱敏(P5+) | +| 学生成绩 | 高 | 默认遮罩,点击"查看"展示;页面离开 5s 后自动遮罩 | +| 考试作答内容 | 高 | 不缓存到 localStorage(仅 IDB 草稿),提交后清除 | +| 学生 ID | 低 | URL 可携带,但 BFF 校验本人权限 | +| 通知内容 | 中 | 不缓存到 localStorage,仅 TanStack Query 内存缓存 | + +--- + +## 16. 跨标签与跨设备同步 + +### 16.1 同步机制矩阵 + +| 场景 | 同步机制 | 同步内容 | 冲突解决 | +| ----------------------- | ------------------------------- | ----------------------------------------- | ------------------- | +| 同浏览器多标签考试检测 | BroadcastChannel API | 考试作答中标签切换检测 | 阻止多标签作答 | +| 考试作答草稿跨标签 | BroadcastChannel + IDB | 草稿变更(仅同一考试) | 最后写入胜出(LWW) | +| 通知未读数跨标签同步 | BroadcastChannel | unread count | 服务端为准 | +| 跨设备状态同步 | WebSocket 事件(P5) | 通知变更 | 服务端为准 | +| 网络恢复后状态对齐 | 重连后批量 invalidate + refetch | 全部学生维度数据 | 服务端为准 | + +### 16.2 BroadcastChannel 实现(考试作答防多标签) + +```typescript +// apps/student-portal/src/lib/examTabGuard.ts +const EXAM_CHANNEL_NAME = "student-exam-guard"; + +// 进入考试页时检测是否有其他标签正在作答同一考试 +export function useExamTabGuard(examId: string) { + useEffect(() => { + const channel = new BroadcastChannel(EXAM_CHANNEL_NAME); + const tabId = `tab-${Date.now()}-${Math.random().toString(36).slice(2)}`; + + // 广播:我正在作答此考试 + channel.postMessage({ type: "exam-entered", examId, tabId, ts: Date.now() }); + + // 监听其他标签的响应 + const onMessage = (event: MessageEvent) => { + const msg = event.data; + if (msg.tabId === tabId) return; + if (msg.type === "exam-entered" && msg.examId === examId) { + // 已有其他标签在作答,警告 + toast.warning(t("exam.multiTabDetected")); + // 记录可疑行为 + recordSuspiciousBehavior("multi-tab-exam"); + } + }; + channel.addEventListener("message", onMessage); + + return () => { + channel.postMessage({ type: "exam-left", examId, tabId }); + channel.close(); + }; + }, [examId]); +} +``` + +### 16.3 考试草稿跨标签恢复 + +若学生在 Tab A 开始作答,关闭 Tab A 后在 Tab B 重新打开: + +- IDB 草稿跨标签共享(同源策略保证) +- Tab B 进入考试页时检测 IDB 草稿 +- 弹 `DraftRecovery` 提示"检测到未完成的作答草稿,是否恢复?" +- 用户确认后从 IDB 加载草稿 + +--- + +## 17. i18n 深化 + +> ai07 初稿仅提到 next-intl。ai14 补全多语言策略。 + +### 17.1 支持语言矩阵 + +| 语言 | locale | 阶段 | 完成度要求 | +| --------------- | ------ | ----------- | ---------- | +| 简体中文 | zh-CN | P3 强制 | 100% | +| 英文 | en-US | P6 海外扩展 | 100% | +| 繁体中文 | zh-TW | P6 海外扩展 | 100% | +| 日文 | ja-JP | P6+ 未来 | ≥ 80% | +| 阿拉伯文(RTL) | ar-SA | P6+ 未来 | ≥ 80% | + +### 17.2 locale 路由策略 + +**采用 URL 前缀策略**(与 Shell 共享,由 Shell 配置): + +``` +/zh-CN/dashboard +/en-US/dashboard +/dashboard → 默认重定向到浏览器首选语言 +``` + +- Next.js 中间件根据 `Accept-Language` 头自动重定向 +- 用户主动切换语言时写入 Cookie `NEXT_LOCALE`,下次访问直接命中 +- student-portal 不维护 locale 路由,复用 Shell 中间件 + +### 17.3 翻译文件组织 + +``` +apps/student-portal/src/i18n/messages/ +├─ zh-CN/ +│ ├─ common.json # 通用文案(确认/取消/加载中等) +│ ├─ dashboard.json +│ ├─ homework.json +│ ├─ exams.json +│ ├─ exam-taking.json # 考试作答专用文案(含倒计时/自动保存/断网提示) +│ ├─ grades.json +│ ├─ attendance.json +│ ├─ learning-path.json +│ ├─ diagnostic.json +│ ├─ weakness.json +│ ├─ notifications.json +│ └─ errors.json # 错误码 → i18n key 映射 +├─ en-US/ +│ └─ ... (镜像 zh-CN 结构) +└─ index.ts # 按需加载 messages +``` + +按路由切分 message bundle,避免首屏加载全部翻译。 + +### 17.4 国际化格式 + +| 数据类型 | 库 | 示例(zh-CN) | 示例(en-US) | +| -------- | ------------------------------------- | --------------------- | ------------------- | +| 日期 | `Intl.DateTimeFormat` | 2026年7月10日 | July 10, 2026 | +| 时间 | 同上 | 下午3:30 | 3:30 PM | +| 数字 | `Intl.NumberFormat` | 1,234.56 | 1,234.56 | +| 百分比 | 同上 | 85.5% | 85.5% | +| 成绩等级 | 自定义映射表 | 优秀/良好/及格/不及格 | A/B/C/D/F | +| 时区 | `Intl.DateTimeFormat` with `timeZone` | Asia/Shanghai | America/Los_Angeles | +| 倒计时 | 自定义(HH:mm:ss 格式) | 01:30:00 | 01:30:00 | + +### 17.5 RTL 支持(P6+ 预留) + +- Tailwind CSS logical properties:`ms-*`/`me-*`/`ps-*`/`pe-*` 替代 `ml-*`/`mr-*`/`pl-*`/`pr-*` +- 设计令牌预留 RTL 语义令牌:`--space-inline-start` / `--space-inline-end` +- 图标方向敏感(如返回箭头)需根据 `dir` 属性翻转 + +--- + +## 18. 移动端与 PWA + +> 学生端在移动端使用比例较高(学生多在课后/自习时间查看作业/成绩/学情),移动端策略必须前置。考试作答移动端体验需要特别考虑。 + +### 18.1 响应式断点 + +| 断点 | 宽度 | 典型设备 | student-portal 布局变化 | +| -------------- | ----------- | ---------------------- | --------------------------------------------------- | +| `sm` (default) | < 640px | iPhone/Android 手机 | 单列布局;考试作答区全屏;侧栏导航抽屉化 | +| `md` | 640-1024px | iPad Mini/Android 平板 | 双列布局(侧栏 + 内容);考试作答区优化 | +| `lg` | 1024-1280px | iPad Pro/小笔记本 | 三列布局(侧栏 + 内容 + 详情);学情图表完整展示 | +| `xl` | > 1280px | 桌面 | 三列布局;考试作答区居中固定宽度 | + +### 18.2 移动端交互优化 + +| 场景 | 移动端优化 | +| -------------- | ------------------------------------------ | +| 考试作答 | 题目纵向滚动;选项触摸友好;倒计时顶部固定 | +| 作业提交 | 附件拍照上传;底部固定提交按钮 | +| 查看成绩 | 卡片式纵向滚动;图表触摸缩放 | +| 通知列表 | 左滑标记已读、右滑删除(iOS 风格) | +| 学情诊断 | 图表简化为单维度;横屏展示完整雷达图 | +| 表单提交 | 底部固定按钮;软键盘弹出时自动避让 | +| 长列表 | 无限滚动 + 骨架屏 | + +### 18.3 PWA 配置(P5+ 引入) + +```json +// apps/student-portal/public/manifest.json +{ + "name": "Edu 学生端", + "short_name": "EduStudent", + "start_url": "/dashboard", + "display": "standalone", + "orientation": "portrait", + "background_color": "#ffffff", + "theme_color": "#1677ff", + "icons": [ + { "src": "/icons/student-192.png", "sizes": "192x192", "type": "image/png" }, + { "src": "/icons/student-512.png", "sizes": "512x512", "type": "image/png" } + ], + "shortcuts": [ + { "name": "我的作业", "url": "/my-homework" }, + { "name": "我的考试", "url": "/my-exams" }, + { "name": "我的成绩", "url": "/my-grades" } + ] +} +``` + +### 18.4 Service Worker 策略(P5+) + +| 资源类型 | 缓存策略 | TTL | +| ----------------------- | --------------------------- | ------- | +| 静态资源(JS/CSS/图片) | Cache First + 网络更新 | 24 小时 | +| 学生 dashboard 数据 | Stale While Revalidate | 30 秒 | +| 考试作答页 | **Network Only** | — | +| 考试题目数据 | **Network Only** | — | +| 通知列表 | Network Only | — | +| API 401 响应 | 不缓存 | — | + +> 考试作答相关资源强制 Network Only,防止缓存泄露答案。 + +--- + +## 19. 长远愿景与演进路径 + +### 19.1 阶段演进路线 + +```mermaid +graph LR + P3[P3 核心教学
学生端 MVP
dashboard+homework+exams+take+grades] --> P4[P4 学情分析
diagnostic+weakness+learning-path] + P4 --> P5[P5 推送
通知中心+WebSocket+防作弊增强] + P5 --> P6[P6 硬化
PWA+A11y+性能+安全+多语言] + P6 --> P7[P7+ 扩展
AI 辅导+错题推荐+学习计划] + P7 --> P8[P8+ 多租户
学区/教育局版] +``` + +### 19.2 未来功能铺垫(架构预留) + +| 未来功能 | 架构预留点 | 启用阶段 | +| -------------------------- | ------------------------------------------------------------------------------ | -------- | +| AI 辅导(个性化答疑) | API 路由 `/api/v1/student/ai/*` 预留;SSE 复用 teacher-portal 模式 | P7 | +| 错题智能推荐 | `WeaknessList` 组件抽象推荐策略;GraphQL query `recommendedWeakness` 预留 | P7 | +| 学习计划(自动生成) | `LearningPathMap` 组件预留计划编辑模式;GraphQL mutation `generatePlan` | P7 | +| 同学协作(学习小组) | `NotificationFeed` 抽象为通用消息流;WebSocket 事件协议预留 `group.*` 类型 | P7+ | +| 移动端原生壳 | PWA → Capacitor 打包;MF 不变 | P8+ | +| 离线模式(考试作答断网增强)| Service Worker + IDB 队列(P5+ 引入) | P5+ | +| 推送通知(Web Push) | Service Worker PushManager + VAPID(P5+ 引入) | P5+ | +| 学区/教育局版多租户 | URL 路由前缀 `/{tenantId}/student/*` 预留;TanStack Query key 加 tenantId 维度 | P8+ | +| lockdown 浏览器(防作弊) | 考试作答页检测 lockdown 环境;启用更严格策略 | P6+ | + +### 19.3 模块解耦与演化 + +| 演化方向 | 触发条件 | 迁移策略 | +| ------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------- | +| student-portal 拆分为多个 Remote | bundle > 200KB 或团队规模 > 5 人 | 按场景域拆分:student-core-remote(dashboard/homework/grades)+ student-exam-remote(考试作答) | +| MF 2.0 → 3.0 升级 | MF 3.0 稳定且解决 SSR 问题 | Shell 端 `@module-federation/nextjs-mf` 升级;student-portal 仅改 `name`/`filename` 字段 | +| 切换为原生 SSR(脱离 MF) | SEO 需求强烈或 MF 维护成本过高 | 保留 GraphQL 请求层和组件库;移除 MF 配置;独立部署为完整 Next.js 应用 | +| 状态管理迁移(Zustand → Jotai) | Zustand 性能瓶颈或团队偏好 | 逐 slice 迁移;Hook 接口保持不变 | +| GraphQL → 更轻量协议 | GraphQL 性能瓶颈 | 评估 RPC / tRPC;urql client 替换为对应 client | + +### 19.4 监控与降级 + +| 监控项 | 阈值 | 触发动作 | +| ------------------------ | --------------- | ------------------------------------------------------ | +| student-portal 5xx 错误率 | > 1% | 告警 SRE;自动切换到只读模式(隐藏提交按钮) | +| MF Remote 加载失败 | 加载超时 10s | Fallback 到 Shell 内置的最小化 dashboard(静态引导页) | +| WebSocket 连接失败 | 重试 5 次仍失败 | 降级为 HTTP 轮询(每 60s 拉取通知列表) | +| BFF 响应延迟 | P95 > 3s | 前端展示"加载缓慢"提示;自动缩短缓存 TTL | +| 考试作答自动保存失败率 | > 5% | 告警;UI 提示学生手动保存;增加重试频率 | +| 考试提交失败 | 单次失败 | 自动重试 + 入 IDB 队列;3 次失败后人工介入提示 | + +--- + +**AI Agent**: ai14 (student-portal remote) +**Branch**: feat-review-student-portal-docs-9yN6Av **Coordinator**: coord-ai +**Predecessor**: ai07(初版起草,ai14 接管审计与补全) diff --git a/apps/student-portal/docs/02-architecture-design.md b/apps/student-portal/docs/02-architecture-design.md index 0de7ce1..2477aa2 100644 --- a/apps/student-portal/docs/02-architecture-design.md +++ b/apps/student-portal/docs/02-architecture-design.md @@ -1,11 +1,24 @@ # 模块架构设计文档 — student-portal -> AI:ai07(TS/React · 学习场景域前端 remote) -> 阶段:阶段 2 交付物 -> 日期:2026-07-09 -> 关联:[阶段 1 理解确认书](./01-understanding.md)、[004 架构影响地图](../../../docs/architecture/004_architecture_impact_map.md) §5.4、[pending-features P3](../../../docs/architecture/roadmap/pending-features.md)、[teacher-portal 阶段 2 架构设计](../../teacher-portal/docs/02-architecture-design.md) +> AI:ai14(TS/React · 学习场景域前端 remote) +> 阶段:阶段 2 交付物(v2 — ai14 接管审计与补全版) +> 初版日期:2026-07-09(ai07 起草) +> 审计日期:2026-07-10(ai14 修订:协议 REST→GraphQL、端口 3001→4001、所有权 ai07→ai14、MF 配置 ARB-002、路由前缀、错误码前缀、长远架构补全) +> 关联:[阶段 1 理解确认书](./01-understanding.md)、[004 架构影响地图](../../../docs/architecture/004_architecture_impact_map.md) §5.4、[pending-features P3](../../../docs/architecture/roadmap/pending-features.md)、[teacher-portal 阶段 2 架构设计](../../teacher-portal/docs/02-architecture-design.md)、[teacher-portal 阶段 3 长远架构](../../teacher-portal/docs/03-long-term-architecture.md)、[known-issues §2.15](../../../docs/troubleshooting/known-issues.md)、[coord 仲裁 ARB-001](../../../docs/architecture/issues/coord.md#1-arb-001teacher-bff-graphql-schema-第一版)、[coord 仲裁 ARB-002](../../../docs/architecture/issues/coord.md#2-arb-002mf-shell-暴露清单)、[student-bff 契约](../../../docs/architecture/issues/contracts/student-bff_contract.md)、[student-portal 契约](../../../docs/architecture/issues/contracts/student-portal_contract.md) > 状态:待 coord 交叉审查 +> **v2 审计修订摘要**(ai14 → ai07 初稿): +> +> 1. **协议修订**:REST → **GraphQL over HTTP**(ARB-001 已裁决 student-bff 走 GraphQL Yoga + ActionState 信封 + DataLoader;前端 all-in GraphQL,复用 Shell 暴露的 urql client 单例) +> 2. **端口修订**:3001 → **4001**(004 §1.2 强制 4 端 4000-4003;[port-allocation](../../../infra/port-allocation.md) §4 硬约束;3001 已被 classes 历史占用) +> 3. **所有权修订**:ai07 → **ai14**(ai-allocation.md §3.2 L94;ai07=classes/core-edu 交接) +> 4. **MF 配置修订**:按 ARB-002,Shell 暴露 `GraphQLProvider`/`useGraphQLClient`/`urql`/`graphql` 单例;student-portal 不再实现 ApiClient,不重复创建 GraphQL client +> 5. **路由修订**:`/student/*` → `/*`(无前缀,与 student-portal_contract.md §1.2 对齐;student-portal 是独立 dev server :4001) +> 6. **登录路径修订**:`/iam/login` → `POST /api/auth/login`(iam 仅 gRPC,登录由 api-gateway 聚合) +> 7. **错误码前缀修订**:`EXAMS_`/`HOMEWORK_`/`GRADES_` → **`CORE_EDU_`**(known-issues §2.15);`STUDENT_BFF_` → **`BFF_STUDENT_`** +> 8. **遗漏补全**:考试作答架构设计(断网恢复/时间对齐/防作弊/IDB 队列)、详细组件设计、跨标签同步、API 版本管理、监控与降级、模块演化、长远架构愿景 +> 9. **新增章节**:§14 考试作答架构设计、§15 详细组件设计、§16 跨标签同步实现、§17 API 版本管理、§18 监控与降级、§19 模块演化与解耦、§20 长远架构愿景 + --- ## 1. 模块内部分层图(student-portal Remote 视角) @@ -13,131 +26,148 @@ ```mermaid graph TB subgraph Browser["浏览器(学生)"] - URL[URL 路由 /student/*] + URL[URL 路由 /*
无 /student 前缀] end - subgraph Shell["teacher-portal(Shell 宿主)"] - AppShell[AppShell
左栏导航 + 主内容区] - RootLayout[RootLayout
字体/令牌/i18n/Query Provider] - SharedDeps["共享依赖暴露
react/react-dom/@tanstack/react-query/zustand/nuqs
ui-components/ui-tokens/contracts/hooks"] + subgraph Shell["teacher-portal(Shell 宿主 :4000)"] + AppShell[AppShell
左栏导航 + 主内容区
按 scope=student 过滤视口] + RootLayout[RootLayout
字体/令牌/i18n/GraphQL/Query Provider] + GraphQLProvider["GraphQLProvider
urql client 单例(ARB-002)
含 exchanges: cache/auth/error/retry"] + SharedDeps["共享依赖暴露(singleton)
react/react-dom/urql/graphql/@tanstack/react-query
zustand/nuqs/@edu/ui-components/@edu/ui-tokens
@edu/contracts/@edu/hooks/@edu/shared-ts"] + Rewrites["rewrites /api/v1/* + /api/auth/* → api-gateway"] end - subgraph RemoteStudent["student-portal(Remote)"] - StudentPages["学习场景页面
dashboard/homework/submit/exams/take
diagnostic(P4)/weakness(P4)/notifications(P5)"] - ExamTaking[ExamTaking 组件
倒计时 + 自动保存] - StudentApiClient[ApiClient 实例
注入 student scope token] + subgraph RemoteStudent["student-portal(Remote :4001)"] + StudentPages["学习场景页面
dashboard/my-homework/my-exams/take
my-grades/my-attendance/learning-path
diagnostic(P4)/weakness(P4)/notifications(P5)"] + ExamTaking[ExamTaking 组件
倒计时 + 自动保存 + 断网恢复 + 防作弊] + StudentHooks["GraphQL Hooks
useMyExams/useMyHomework/useExamTaking
useSubmitHomework/useMyGrades 等"] + IDBQueue["IDB 队列
断网恢复重试队列
考试草稿持久化"] end - subgraph Shared["共享层(packages/)"] + subgraph Shared["共享层(packages/,由 Shell 暴露)"] UITokens[ui-tokens
三层设计令牌] - UIComponents[ui-components
shadcn + A11y + ErrorBoundary] + UIComponents[ui-components
shadcn + A11y + ErrorBoundary + RequirePermission] Contracts[contracts
Permissions 常量 + 类型] - Hooks[hooks
usePermission/useAuth/useA11y] - LibTS[shared-ts
ApiClient/Logger/通用工具] + Hooks[hooks
usePermission/useAuth/useViewports/useA11y] + LibTS[shared-ts
Logger/Tracer/通用工具] end - subgraph Gateway["api-gateway"] - GW[Gin 路由/鉴权/限流] + subgraph Gateway["api-gateway :8080"] + GW[Gin 路由/JWT 验签/限流] end - subgraph PushGW["push-gateway(P5)"] + subgraph BFF["student-bff :3009"] + BFFGraphQL[GraphQL Yoga endpoint
POST /graphql] + end + + subgraph PushGW["push-gateway :8081(P5)"] WS[WebSocket /ws] end Browser --> URL URL --> RootLayout RootLayout --> AppShell + RootLayout --> GraphQLProvider AppShell -->|动态加载 Remote| RemoteStudent - RemoteStudent -->|复用| SharedDeps - RemoteStudent --> ExamTaking - RemoteStudent --> StudentApiClient + RemoteStudent -->|消费 singleton| SharedDeps + RemoteStudent --> StudentPages + StudentPages --> ExamTaking + StudentPages --> StudentHooks + StudentHooks -->|复用 urql client| GraphQLProvider + ExamTaking --> IDBQueue - Shell --> UITokens - Shell --> UIComponents - Shell --> Contracts - Shell --> Hooks - Shell --> LibTS - RemoteStudent --> UITokens - RemoteStudent --> UIComponents - RemoteStudent --> Contracts - RemoteStudent --> Hooks + SharedDeps --> UITokens + SharedDeps --> UIComponents + SharedDeps --> Contracts + SharedDeps --> Hooks + SharedDeps --> LibTS - StudentApiClient -->|fetch /api/v1/student/*| GW - StudentApiClient -->|fetch /api/v1/iam/*| GW - StudentApiClient -->|fetch /api/v1/notifications/*| GW + StudentHooks -->|POST /api/v1/student/graphql| Rewrites + Rewrites --> GW + GW --> BFFGraphQL RemoteStudent -.->|P5 WebSocket| WS WS -.->|推送事件| RemoteStudent ``` -### 1.1 Remote 角色定位 - -student-portal 作为 **Remote 子应用**,由 teacher-portal Shell 动态加载。与 Shell 的职责分工: +### 1.1 Remote 与 Shell 的职责边界 | 职责 | Shell(teacher-portal) | Remote(student-portal) | | -------------------------------- | ----------------------- | ------------------------ | | RootLayout(字体/令牌/Provider) | ✅ 提供 | ❌ 复用 | | AppShell(左栏 + 主内容区) | ✅ 提供 | ❌ 复用 | +| GraphQLProvider(urql client) | ✅ 提供(ARB-002) | ❌ 复用单例 | | 共享依赖暴露(singleton) | ✅ 提供 | ❌ 消费 | -| 登录页 | ✅ 提供 | ❌ 复用 | -| 路由表 `/student/*` | ❌ 由 Remote 暴露 | ✅ 提供 | +| 登录页 | ✅ 提供(P2 不走 MF) | ❌ 复用 | +| rewrites `/api/v1/*` | ✅ 提供 | ❌ 依赖 Shell | +| 路由表 `/*`(无 /student 前缀) | ❌ 由 Remote 暴露 | ✅ 提供 | | 学习场景页面 | ❌ | ✅ | -| ApiClient 实例 | ❌ 提供 ApiClient 类 | ✅ 注入 student scope | -| 业务组件(ExamTaking 等) | ❌ | ✅ | +| GraphQL 业务 Hooks | ❌ | ✅ | +| 考试作答组件(ExamTaking 等) | ❌ | ✅ | +| IDB 断网恢复队列 | ❌ | ✅ | -### 1.2 MF 配置(student-portal/next.config.js) +### 1.2 MF 配置(student-portal/next.config.js,Remote 角色) ```javascript -// student-portal/next.config.js(Remote) +// apps/student-portal/next.config.js(Remote) const NextFederationPlugin = require("@module-federation/nextjs-mf"); -const remotes = (isServer) => ({ - teacher: `teacher_app@http://localhost:3000/_next/static/${isServer ? "ssr" : "chunks"}/remoteEntry.js`, -}); - module.exports = { reactStrictMode: true, + transpilePackages: [ + "@edu/ui-tokens", + "@edu/ui-components", + "@edu/hooks", + "@edu/contracts", + "@edu/shared-ts", + ], webpack(config, { isServer }) { config.plugins.push( new NextFederationPlugin({ name: "student_app", filename: "static/chunks/remoteEntry.js", - remotes: remotes(isServer), + // Remote 暴露页面入口 + 考试作答组件(供 Shell 路由复用) exposes: { "./pages": "./src/pages", "./ExamTaking": "./src/components/ExamTaking", }, + // Remote 反向引用 Shell 暴露的共享组件 + GraphQL 单例(可选,多数通过 singleton shared 解决) + remotes: { + teacher: `teacher_app@http://localhost:4000/_next/static/${isServer ? "ssr" : "chunks"}/remoteEntry.js`, + }, shared: { react: { singleton: true, requiredVersion: "^18.3.0" }, "react-dom": { singleton: true, requiredVersion: "^18.3.0" }, - "@tanstack/react-query": { singleton: true }, + // ARB-002:GraphQL 相关依赖由 Shell 暴露为 singleton + urql: { singleton: true, requiredVersion: "^2.2.0" }, + graphql: { singleton: true, requiredVersion: "^16.8.0" }, + "@tanstack/react-query": { singleton: true, requiredVersion: "^5.0.0" }, zustand: { singleton: true }, nuqs: { singleton: true }, + "@edu/ui-tokens": { singleton: true }, + "@edu/ui-components": { singleton: true }, + "@edu/hooks": { singleton: true }, + "@edu/contracts": { singleton: true }, + "@edu/shared-ts": { singleton: true }, }, extraOptions: { exposePages: false }, }), ); return config; }, - async rewrites() { - return [ - { - source: "/api/v1/:path*", - destination: `${process.env.API_GATEWAY_URL || "http://localhost:8080"}/api/v1/:path*`, - }, - ]; - }, + // student-portal 不实现 rewrites,依赖 teacher-portal Shell 的 rewrites 代理 /api/v1/* 与 /api/auth/* }; ``` -**关键点**: - -- `name: 'student_app'`:Remote 应用名,与 Shell 中 `remotes.student` 对应 -- `exposes`:暴露页面入口 `./pages` 和 student 特有组件 `./ExamTaking` -- `remotes.teacher`:引用 Shell 提供的 AppShell 和 shared-deps -- `shared`:与 Shell 一致的 singleton 策略,保证 React/Query/Zustand 单例 -- `rewrites`:与 Shell 一致的 `/api/v1/*` 代理到 api-gateway +> **说明**(ARB-002 对齐): +> +> - `name: 'student_app'`:Remote 应用名,被 Shell 在 `remotes` 中引用为 `student: 'student_app@http://localhost:4001/...'` +> - Shell 端口 **4000**(ARB-002 MF URL),student-portal dev 端口 **4001** +> - `urql`/`graphql` 声明为 `singleton: true`,确保与 Shell 共享同一 GraphQL client 实例(ARB-002 强制) +> - `shared` 全部 `singleton: true`,避免 React 多实例、Zustand store 分裂、GraphQL cache 分裂 +> - `transpilePackages` 列出本地 `packages/*` 软链依赖,确保 SWC 正确编译 +> - student-portal **不实现 rewrites**,所有 `/api/v1/*` 与 `/api/auth/*` 请求由 Shell 的 rewrites 代理到 api-gateway ## 2. 领域模型(前端视角) @@ -149,22 +179,42 @@ module.exports = { ### 2.2 视口模型(Viewport) -复用 Shell 的 ViewportItem 模型,但 `scope` 字段值为 `'student'`。来源:`GET /api/v1/student/viewports`(student-bff 聚合 iam 视口配置)。AppShell 按 `scope='student'` 过滤渲染学生端导航。 +复用 Shell 的 ViewportItem 模型,但 `scope` 字段值为 `'student'`。来源:student-bff GraphQL `viewports` query(聚合 iam 视口配置)。AppShell 按 `scope='student'` 过滤渲染学生端导航。 ### 2.3 权限模型(Permission) -复用 Shell 的 PermissionState 模型。来源:`GET /api/v1/iam/effective-permissions` → `{ permissions, viewports, dataScope }`。学生 dataScope 固定为 L0(仅本人)。 +复用 Shell 的 PermissionState 模型。来源:`POST /api/v1/student/graphql` query `currentUser` → `{ permissions, viewports, dataScope }`。学生 dataScope 固定为 **L0(仅本人)**。 ### 2.4 student-portal 特有视图模型 ```typescript -// 考试作答草稿(Zustand L3,断网恢复用) +// 考试作答草稿(Zustand L3 + IDB,断网恢复用) interface ExamTakingDraft { examId: string; + studentId: string; answers: Record; // questionId → answer - startedAt: number; + startedAt: number; // 客户端开始时间戳 + serverStartedAt: number; // 服务器开始时间戳(用于倒计时校正) lastSavedAt: number | null; - durationSeconds: number; // 考试时长(秒) + durationSeconds: number; // 考试时长(秒,来自服务器) + expiresAt: string; // ISO 8601 UTC,考试截止时间(来自服务器) + suspiciousBehaviors: SuspiciousBehaviorRecord[]; // 防作弊记录 +} + +// 答案输入(联合类型,按题型区分) +type AnswerInput = + | { type: "single-choice"; optionId: string } + | { type: "multiple-choice"; optionIds: string[] } + | { type: "fill-blank"; values: string[] } + | { type: "short-answer"; text: string } + | { type: "essay"; text: string; attachments?: AttachmentRef[] }; + +// 可疑行为记录(防作弊,前端仅记录,服务端最终判定) +interface SuspiciousBehaviorRecord { + type: "tab-switch" | "copy-paste" | "fullscreen-exit" | "multi-tab" | "window-blur"; + timestamp: number; + duration?: number; // 持续时长(ms) + details?: string; } // 作业提交表单(react-hook-form L5) @@ -174,196 +224,357 @@ interface HomeworkSubmitForm { attachments?: File[]; // 附件(图片/PDF) note?: string; // 学生备注 } -``` -## 3. 数据模型(前端缓存策略) +// 学情诊断视图模型(P4) +interface DiagnosticViewModel { + examId: string; + examName: string; + score: number; + maxScore: number; + knowledgePoints: Array<{ + id: string; + name: string; + mastery: number; // 0-1 + questionCount: number; + correctCount: number; + }>; + radar: Array<{ axis: string; value: number }>; // 多维雷达图数据 + trend: Array<{ date: string; score: number }>; // 趋势线数据 +} -前端无数据库,仅有缓存层。student-portal 缓存策略偏短(学生数据实时性要求高): +// 错题本视图模型(P4) +interface WeaknessViewModel { + questionId: string; + questionContent: string; // 题目内容(脱敏后) + knowledgePointId: string; + knowledgePointName: string; + mastery: number; // 0-1,掌握度 + wrongCount: number; + lastWrongAt: string; // ISO 8601 + recommendedAction: "review" | "practice" | "mastered"; +} -| 数据类型 | 存储 | TTL | 失效策略 | -| ------------------------- | ------------------------- | ---- | --------------------------------------------------------- | -| Session(token + user) | localStorage + Zustand | — | 复用 Shell:access 15min / refresh 7day,401 自动 refresh | -| 权限列表 | TanStack Query cache | 5min | 复用 Shell:角色变更事件 invalidate | -| 视口列表(scope=student) | TanStack Query cache | 5min | 复用 Shell | -| 学生 Dashboard 聚合数据 | TanStack Query cache | 30s | staleTime 30s,事件触发 invalidate | -| 我的作业列表 | TanStack Query cache | 30s | staleTime 30s,提交后 invalidate | -| 我的考试列表 | TanStack Query cache | 30s | staleTime 30s,ExamPublished 事件 invalidate | -| 考试作答草稿 | Zustand L3 + localStorage | — | 卸载不销毁,自动保存(每 30s + blur 时) | -| 学情诊断数据 | TanStack Query cache | 30s | staleTime 30s(实时性由 BFF 决定) | -| 错题本列表 | TanStack Query cache | 30s | staleTime 30s | -| 通知列表(P5) | TanStack Query cache | 30s | staleTime 30s,WebSocket 事件 invalidate | -| URL 状态(分页/筛选) | nuqs | — | 永久(可分享) | -| 表单临时态(作业提交) | react-hook-form | — | 卸载即销毁 | - -## 4. API 设计(前端 → 后端) - -前端不设计后端 API,仅声明消费的端点。详见 [01-understanding.md §3.1](./01-understanding.md)。 - -### 4.1 统一 API 请求层(复用 Shell ApiClient) - -student-portal **不重复实现 ApiClient 类**,复用 `packages/shared-ts/src/api-client.ts`(详见 [teacher-portal 阶段 2 §4.1](../../teacher-portal/docs/02-architecture-design.md#41-统一-api-请求层libapits))。 - -student-portal 仅注入不同 baseUrl/token 和 scope 标记: - -```typescript -// apps/student-portal/src/lib/api.ts -import { ApiClient } from "@edu/shared-ts"; -import { useAuth } from "@edu/hooks"; - -export function useStudentApi(): ApiClient { - const { getToken, logout } = useAuth(); - return useMemo( - () => - new ApiClient({ - baseUrl: "", // 走 Next.js rewrites - getToken, - onUnauthorized: logout, - scope: "student", // 日志/trace 标记 - }), - [getToken, logout], - ); +// 学习路径节点(P4) +interface LearningPathNode { + id: string; + name: string; + knowledgePointId: string; + status: "locked" | "available" | "in-progress" | "completed"; + dependencies: string[]; // 前置节点 ID + mastery: number; + recommendedOrder: number; } ``` -**职责**(与 Shell 一致,由 shared-ts ApiClient 承担): +## 3. 数据模型(前端缓存层) -- 自动注入 `Authorization: Bearer ${token}` -- 401 自动 refresh token 一次,失败调 `onUnauthorized` -- 解析 `ActionState`,success=false 抛 `ApiError` -- 按 `error.code` 前缀路由 i18n key -- 全局错误 toast(除 401) -- 请求/响应 trace_id 透传(从响应头 `X-Request-Id` 提取) +student-portal 无数据库,仅有 GraphQL cache(urql)+ TanStack Query cache + Zustand L3 + IDB。**学生数据实时性要求高,缓存策略偏短**: -### 4.2 TanStack Query 约定 +| 数据类型 | 存储 | TTL | 失效策略 | +| ------------------------- | ------------------------- | ------- | ------------------------------------------------------------------ | +| Session(token + user) | localStorage + Zustand | — | 复用 Shell:access 15min / refresh 7day,401 自动 refresh | +| 权限列表 | urql cache | 5min | 复用 Shell:角色变更事件 invalidate | +| 视口列表(scope=student) | urql cache | 5min | 复用 Shell | +| 学生 Dashboard 聚合数据 | urql cache | 30s | staleTime 30s,WebSocket 事件触发 invalidate | +| 我的作业列表 | urql cache | 30s | staleTime 30s,提交后 invalidate | +| 我的考试列表 | urql cache | 30s | staleTime 30s,ExamPublished 事件 invalidate | +| 考试题目数据 | urql cache | **0s** | 考试作答页禁缓存(防预渲染泄露答案);进入时强制 refetch | +| 考试作答草稿 | Zustand L3 + IDB | — | 卸载不销毁,自动保存(每 30s + blur 时);提交成功后清除 IDB | +| 学情诊断数据 | urql cache | 30s | staleTime 30s(实时性由 BFF 决定) | +| 错题本列表 | urql cache | 30s | staleTime 30s | +| 学习路径 | urql cache | 5min | staleTime 5min(低频变更) | +| 通知列表(P5) | urql cache | 30s | staleTime 30s,WebSocket 事件 invalidate | +| 服务器时间偏移 | Zustand L3(内存) | — | 每次进入考试页同步一次 | +| 断网重试队列 | IDB | — | 网络恢复后批量重试,成功后清除 | +| URL 状态(分页/筛选) | nuqs | — | 永久(可分享);考试作答页 URL 不携带答案(防泄露) | +| 表单临时态(作业提交) | react-hook-form | — | 卸载即销毁 | +| 防作弊行为记录 | Zustand L3(内存队列 100)| — | 队列满后批量上报,上报后清空 | + +> **缓存策略说明**:学生数据(作业/考试/成绩)频变且实时性要求高,30s 短缓存平衡新鲜度与 BFF 压力;考试题目数据强制 0s 禁缓存防止泄露;考试作答草稿用 IDB 持久化保证断网恢复。 + +## 4. API 设计(前端 → 后端) + +前端不设计后端 API,仅声明消费的 GraphQL 操作。详见 [01-understanding.md §3.1](./01-understanding.md#31-消费的后端-ap经-api-gateway-代理)。 + +### 4.1 GraphQL 请求层(复用 Shell 暴露的 urql client 单例) + +student-portal **不重复创建 GraphQL client**,复用 Shell 暴露的 `GraphQLProvider`(ARB-002)。urql client 配置详见 [teacher-portal 阶段 2 §4.1](../../teacher-portal/docs/02-architecture-design.md#41-统一-api-请求层libapits)。 + +student-portal 仅封装业务 Hooks,消费 Shell 的 `useGraphQLClient()`: ```typescript -// Query Key 命名:[scope, resource, ...args] +// apps/student-portal/src/lib/graphql.ts +import { useGraphQLClient } from "@edu/hooks"; +import { useQuery, useMutation } from "@tanstack/react-query"; +import { gql } from "urql"; + +// 学生 Dashboard 聚合查询 +const STUDENT_DASHBOARD = gql` + query StudentDashboard { + studentDashboard { + upcomingHomework { id title dueAt subject { id name } status } + upcomingExams { id name startsAt expiresAt durationSeconds subject { id name } status } + recentGrades { id examName score maxScore grade submittedAt } + attendanceRate + learningStreakDays + } + } +`; + +export function useStudentDashboard() { + const client = useGraphQLClient(); + return useQuery({ + queryKey: ["student", "dashboard"], + queryFn: () => client.query(STUDENT_DASHBOARD, {}).toPromise(), + staleTime: 30 * 1000, // 30s + }); +} + +// 考试作答相关 +const MY_EXAMS = gql` + query MyExams($status: ExamStatus) { + myExams(status: $status) { + id name startsAt expiresAt durationSeconds + subject { id name } + status questionCount + } + } +`; + +const EXAM_DETAIL = gql` + query ExamDetail($examId: ID!) { + exam(id: $examId) { + id name durationSeconds startsAt expiresAt + questions { + id type content options { id text } + score maxScore + } + } + } +`; + +const SAVE_EXAM_ANSWER = gql` + mutation SaveExamAnswer($examId: ID!, $questionId: ID!, $answer: AnswerInput!) { + saveExamAnswer(examId: $examId, questionId: $questionId, answer: $answer) { + savedAt + ok + } + } +`; + +const SUBMIT_EXAM = gql` + mutation SubmitExam($examId: ID!) { + submitExam(examId: $examId) { + submissionId submittedAt + } + } +`; + +export function useMyExams(status?: ExamStatus) { + const client = useGraphQLClient(); + return useQuery({ + queryKey: ["student", "exams", { status }], + queryFn: () => client.query(MY_EXAMS, { status }).toPromise(), + staleTime: 30 * 1000, + }); +} + +export function useExamDetail(examId: string) { + const client = useGraphQLClient(); + return useQuery({ + queryKey: ["student", "exam", examId], + queryFn: () => client.query(EXAM_DETAIL, { examId }).toPromise(), + staleTime: 0, // 禁缓存,防泄露 + }); +} +``` + +### 4.2 GraphQL 操作清单(对齐 student-bff 契约) + +| 操作类型 | 操作名 | 用途 | 阶段 | +| ---------- | --------------------- | --------------------------------- | ---- | +| query | `currentUser` | 当前学生信息 + 权限 + 视口 | P3 | +| query | `myClasses` | 我的班级列表 | P3 | +| query | `myExams` | 我的考试列表 | P3 | +| query | `exam` | 考试详情(含题目) | P3 | +| query | `examSubmissionStatus`| 考试提交状态(防重复提交) | P3 | +| query | `examResult` | 考试结果 | P3 | +| query | `myHomework` | 我的作业列表 | P3 | +| query | `homeworkDetail` | 作业详情 | P3 | +| mutation | `submitHomework` | 提交作业 | P3 | +| query | `myGrades` | 我的成绩列表 | P3 | +| query | `myAttendance` | 我的考勤 | P3 | +| query | `studentDashboard` | 学生仪表盘聚合 | P3 | +| query | `serverTime` | 服务器时间(倒计时校正) | P3 | +| mutation | `saveExamAnswer` | 保存考试答案(自动保存) | P3 | +| mutation | `submitExam` | 提交考试 | P3 | +| mutation | `uploadAttachment` | 上传附件 | P3 | +| mutation | `recordExamSuspiciousBehavior` | 记录可疑行为 | P3 | +| query | `textbooks` | 教材列表 | P4 | +| query | `chapters` | 章节列表 | P4 | +| query | `learningPath` | 学习路径 | P4 | +| query | `myWeakness` | 错题本 | P4 | +| query | `myTrend` | 学习趋势 | P4 | +| query | `myNotifications` | 通知列表 | P5 | +| mutation | `markAsRead` | 标记通知已读 | P5 | + +### 4.3 Query Key 命名约定 + +```typescript +// GraphQL operation → TanStack Query key queryKey: ["student", "dashboard"]; -queryKey: ["student", "homework", { status, page }]; queryKey: ["student", "exams", { status }]; -queryKey: ["student", "exam-taking", examId]; -queryKey: ["student", "diagnostic"]; +queryKey: ["student", "exam", examId]; // 考试详情 +queryKey: ["student", "homework", { status, page }]; +queryKey: ["student", "homework", homeworkId]; +queryKey: ["student", "grades", { subjectId }]; +queryKey: ["student", "attendance", { month }]; +queryKey: ["student", "diagnostic", { examId }]; queryKey: ["student", "weakness", { knowledgePointId }]; +queryKey: ["student", "learning-path"]; queryKey: ["student", "notifications", { unreadOnly }]; queryKey: ["session", "effective-permissions"]; // 复用 Shell queryKey: ["session", "viewports", "student"]; // 复用 Shell - -// Mutation 约定 -const submitHomework = useMutation({ - mutationFn: (input) => - api.post(`/api/v1/student/homework/${input.homeworkId}/submit`, input), - onSuccess: () => { - queryClient.invalidateQueries({ queryKey: ["student", "homework"] }); - toast.success(t("homework.submitSuccess")); - }, - onError: (e: ApiError) => toast.error(e.message), -}); - -const saveExamAnswer = useMutation({ - mutationFn: (input) => - api.post(`/api/v1/student/exams/${input.examId}/answers`, input), - onSuccess: (data) => { - // 更新本地草稿的 lastSavedAt - examTakingStore.updateLastSavedAt(data.savedAt); - }, - onError: (e: ApiError) => { - // 草稿保留在本地,下次 blur/定时重试 - logger.warn("exam answer save failed", { examId: e.details }); - }, -}); ``` ## 5. 事件设计 -前端不发布 Kafka 事件,仅消费 WebSocket 推送(P5)。 +前端不发布 Kafka 事件,仅消费 WebSocket 推送(P5)+ 浏览器原生事件(防作弊)。 -### 5.1 WebSocket 推送(P5) +### 5.1 WebSocket 推送事件(P5) -| 事件 | 触发 | student-portal 前端动作 | -| ----------------------------- | -------------- | --------------------------------------------------------------- | -| `NotificationRequested` | msg 服务投递 | toast 提示 + 通知中心未读数 +1 | -| `ExamPublished` | 教师发布考试 | toast + `["student","exams"]` invalidate + dashboard invalidate | -| `GradeRecorded` | 教师录入成绩 | toast + `["student","grades"]` invalidate | -| `HomeworkDeadlineApproaching` | 作业截止前提醒 | toast + 作业列表高亮 + `["student","homework"]` invalidate | +| 事件 | 触发 | student-portal 前端动作 | +| ----------------------------- | -------------- | ------------------------------------------------------------------------------------ | +| `NotificationRequested` | msg 服务投递 | toast 提示 + 通知中心未读数 +1 + `["student","notifications"]` invalidate | +| `ExamPublished` | 教师发布考试 | toast + `["student","exams"]` invalidate + `["student","dashboard"]` invalidate | +| `ExamExtended` | 教师延长考试 | 重新拉取 `exam` query → 更新 `expiresAt` → 重置倒计时(待 ai10 msg 确认事件名) | +| `ExamQuestionReordered` | 教师调整题目顺序 | 重新拉取 `exam` query → 草稿按 questionId 映射(不依赖序号)(待 ai10 确认) | +| `GradeRecorded` | 教师录入成绩 | toast + `["student","grades"]` invalidate + `["student","dashboard"]` invalidate | +| `HomeworkDeadlineApproaching` | 作业截止前提醒 | toast + 作业列表高亮 + `["student","homework"]` invalidate | ### 5.2 WebSocket 连接管理(P5) ```typescript // apps/student-portal/src/lib/ws.ts(P5 实现) +import { useAuth } from "@edu/hooks"; +import { useQueryClient } from "@tanstack/react-query"; + +const RECONNECT_STRATEGY = { + maxRetries: 5, + backoff: "exponential", // 1s, 2s, 4s, 8s, 16s + onMaxRetriesExceeded: "fallback-polling", // 降级为 HTTP 轮询 60s +}; + export function useStudentWebSocket() { const { getToken } = useAuth(); const queryClient = useQueryClient(); + const retryCount = useRef(0); useEffect(() => { - const ws = new WebSocket( - `${process.env.NEXT_PUBLIC_PUSH_GATEWAY_URL}/ws?token=${getToken()}`, - ); - ws.onmessage = (event) => { - const msg = JSON.parse(event.data) as PushMessage; - switch (msg.type) { - case "NotificationRequested": - toast.info(t(msg.payload.title)); - queryClient.invalidateQueries({ - queryKey: ["student", "notifications"], - }); - break; - case "ExamPublished": - toast.info(t("exam.published", { name: msg.payload.examName })); - queryClient.invalidateQueries({ queryKey: ["student", "exams"] }); - queryClient.invalidateQueries({ queryKey: ["student", "dashboard"] }); - break; - case "GradeRecorded": - toast.success(t("grade.recorded")); - queryClient.invalidateQueries({ queryKey: ["student", "grades"] }); - break; - case "HomeworkDeadlineApproaching": - toast.warning( - t("homework.deadlineApproaching", { - name: msg.payload.homeworkName, - }), - ); - queryClient.invalidateQueries({ queryKey: ["student", "homework"] }); - break; - } + const connect = () => { + const ws = new WebSocket( + `${process.env.NEXT_PUBLIC_PUSH_GATEWAY_URL}/ws?token=${getToken()}`, + ); + + ws.onmessage = (event) => { + const msg = JSON.parse(event.data) as PushMessage; + handlePushMessage(msg, queryClient); + }; + + ws.onclose = () => { + if (retryCount.current < RECONNECT_STRATEGY.maxRetries) { + const delay = Math.pow(2, retryCount.current) * 1000; + setTimeout(connect, delay); + retryCount.current += 1; + } else { + // 降级为 HTTP 轮询 + startPollingFallback(queryClient); + } + }; + + ws.onerror = () => ws.close(); + + return () => ws.close(); }; - return () => ws.close(); + + return connect(); }, [getToken, queryClient]); } + +function handlePushMessage(msg: PushMessage, queryClient: QueryClient) { + switch (msg.type) { + case "NotificationRequested": + toast.info(t(msg.payload.title)); + queryClient.invalidateQueries({ queryKey: ["student", "notifications"] }); + break; + case "ExamPublished": + toast.info(t("exam.published", { name: msg.payload.examName })); + queryClient.invalidateQueries({ queryKey: ["student", "exams"] }); + queryClient.invalidateQueries({ queryKey: ["student", "dashboard"] }); + break; + case "ExamExtended": + // 重新拉取考试详情,更新 expiresAt + queryClient.invalidateQueries({ queryKey: ["student", "exam", msg.payload.examId] }); + queryClient.invalidateQueries({ queryKey: ["student", "exams"] }); + break; + case "ExamQuestionReordered": + queryClient.invalidateQueries({ queryKey: ["student", "exam", msg.payload.examId] }); + break; + case "GradeRecorded": + toast.success(t("grade.recorded")); + queryClient.invalidateQueries({ queryKey: ["student", "grades"] }); + queryClient.invalidateQueries({ queryKey: ["student", "dashboard"] }); + break; + case "HomeworkDeadlineApproaching": + toast.warning(t("homework.deadlineApproaching", { name: msg.payload.homeworkName })); + queryClient.invalidateQueries({ queryKey: ["student", "homework"] }); + break; + } +} ``` -### 5.3 考试作答自动保存(SSE / HTTP 轮询) +### 5.3 浏览器原生事件(防作弊,考试作答页) -> 考试作答的自动保存采用 HTTP POST(每 30s + blur 时),不使用 SSE。SSE 仅 teacher-portal 用于 AI 流式出题,student-portal 不涉及。 +| 事件 | 用途 | 处理 | +| ------------------- | --------------------------------- | --------------------------------------------------- | +| `visibilitychange` | 切屏检测 | 记录切换次数 + 时长;超阈值警告;上报服务端 | +| `blur` / `focus` | 窗口失焦检测 | 同上 | +| `copy` / `paste` | 复制粘贴检测 | 阻止默认行为 + 警告;主观题允许粘贴自己输入(待确认)| +| `fullscreenchange` | 全屏退出检测 | 警告 + 记录 | +| `contextmenu` | 右键禁用 | 考试作答页 `preventDefault()` | ## 6. 横切关注点对齐清单 ### 6.1 权限(前端等价) -| 路由 | requiredPermission | -| ------------------------------ | ------------------------ | -| `/student/dashboard` | `STUDENT_DASHBOARD_VIEW` | -| `/student/homework` | `HOMEWORK_READ_OWN` | -| `/student/homework/:id/submit` | `HOMEWORK_SUBMIT` | -| `/student/exams` | `EXAMS_READ_OWN` | -| `/student/exams/:id/take` | `EXAMS_TAKE` | -| `/student/diagnostic` | `DIAGNOSTIC_READ_OWN` | -| `/student/weakness` | `WEAKNESS_READ_OWN` | -| `/student/notifications` | `NOTIFICATION_READ_OWN` | +| 路由 | requiredPermission | +| -------------------------- | ------------------------ | +| `/dashboard` | `STUDENT_DASHBOARD_VIEW` | +| `/my-homework` | `HOMEWORK_READ_OWN` | +| `/my-homework/:id/submit` | `HOMEWORK_SUBMIT` | +| `/my-exams` | `EXAMS_READ_OWN` | +| `/my-exams/:id/take` | `EXAMS_TAKE` | +| `/my-exams/:id/result` | `EXAMS_RESULT_VIEW` | +| `/my-grades` | `GRADES_READ_OWN` | +| `/my-attendance` | `ATTENDANCE_READ_OWN` | +| `/learning-path` | `LEARNING_PATH_VIEW` | +| `/diagnostic` | `DIAGNOSTIC_READ_OWN` | +| `/weakness` | `WEAKNESS_READ_OWN` | +| `/notifications` | `NOTIFICATION_READ_OWN` | -> 完整权限点常量集中在 `packages/contracts/src/permissions.ts`(待建立,coord 负责 contracts,ai07 负责调用)。L3 组件级视口用 ``。权限点后缀 `_OWN` 强调学生仅能操作自己的数据(DataScope L0)。 +> 路由前缀**不带** `/student/`(student-portal 是独立 dev server :4001)。权限点常量集中在 `packages/contracts/src/permissions.ts`(coord 维护)。L3 组件级视口用 ``。权限点后缀 `_OWN` 强调学生仅能操作自己的数据(DataScope L0)。 ### 6.2 错误码清单(前端 i18n 路由) -| 前缀 | 来源服务 | i18n key 模式 | -| -------------- | ----------- | ------------------------- | -| `IAM_` | iam | `iam.error.{{code}}` | -| `CORE_EDU_` | core-edu | `coreEdu.error.{{code}}` | -| `EXAMS_` | core-edu | `exams.error.{{code}}` | -| `HOMEWORK_` | core-edu | `homework.error.{{code}}` | -| `GRADES_` | core-edu | `grades.error.{{code}}` | -| `BFF_STUDENT_` | student-bff | `bff.error.{{code}}` | -| `GW_` | api-gateway | `gateway.error.{{code}}` | -| `NETWORK_` | 前端网络层 | `network.error.{{code}}` | +| 前缀 | 来源服务 | i18n key 模式 | +| --------------- | ----------- | -------------------------- | +| `IAM_` | iam | `iam.error.{{code}}` | +| `CORE_EDU_` | core-edu | `coreEdu.error.{{code}}` | +| `BFF_STUDENT_` | student-bff | `bffStudent.error.{{code}}`| +| `GW_` | api-gateway | `gateway.error.{{code}}` | +| `NETWORK_` | 前端网络层 | `network.error.{{code}}` | + +> **错误码前缀统一**(known-issues §2.15):core-edu 子域(考试/作业/成绩/考勤)统一用 `CORE_EDU_`,不再用 `EXAMS_`/`HOMEWORK_`/`GRADES_`;student-bff 用 `BFF_STUDENT_`,不再用 `STUDENT_BFF_`。前端 GraphQL 请求层根据 `extensions.code` 前缀路由 i18n key。 ### 6.3 Logger @@ -379,14 +590,16 @@ logger.error("homework submit failed", { homeworkId, error: err.code }); ### 6.4 Metrics(Web Vitals) -| 指标 | 类型 | 上报 | -| ----------------------------- | ---- | --------------------------------------------------- | -| `student_portal_lcp_seconds` | LCP | `next/web-vitals` → `POST /api/v1/admin/web-vitals` | -| `student_portal_cls` | CLS | 同上 | -| `student_portal_fid_seconds` | FID | 同上 | -| `student_portal_ttfb_seconds` | TTFB | 同上 | +| 指标 | 类型 | 上报 | +| ----------------------------- | ---- | ---------------------------------------------------------- | +| `student_portal_lcp_seconds` | LCP | `next/web-vitals` → `POST /api/v1/admin/web-vitals` | +| `student_portal_cls` | CLS | 同上 | +| `student_portal_fid_seconds` | FID | 同上 | +| `student_portal_ttfb_seconds` | TTFB | 同上 | +| `student_portal_exam_save_failed` | Counter | 考试自动保存失败计数 | +| `student_portal_offline_duration` | Histogram | 离线时长(秒) | -P6 接入,P3-P5 暂缓。 +P6 接入,P3-P5 暂缓(考试作答自动保存失败率除外,P3 即上报)。 ### 6.5 Tracer(OTel browser SDK,P6) @@ -394,14 +607,14 @@ P6 接入,P3-P5 暂缓。 ### 6.6 健康检查 -| 端点 | 用途 | 实现 | -| ----------------- | ---------------------- | -------------------------------------------------------------- | -| `GET /api/health` | Dockerfile HEALTHCHECK | Next.js Route Handler,返回 `{ status: 'ok', ts: Date.now() }` | -| `GET /api/ready` | K8s readinessProbe | 检查 `process.env.API_GATEWAY_URL` 可达 + 内存 < 阈值 | +| 端点 | 用途 | 实现 | +| ----------------- | ---------------------- | -------------------------------------------------------------------- | +| `GET /api/health` | Dockerfile HEALTHCHECK | Next.js Route Handler,返回 `{ status: 'ok', ts: Date.now() }` | +| `GET /api/ready` | K8s readinessProbe | 检查 `process.env.API_GATEWAY_URL` 可达 + 内存 < 阈值 + Shell MF 可达 | ### 6.7 优雅关闭 -Next.js 无长连接(除 WS),无需特殊处理。WS 在 P5 由 push-gateway 管理,前端断线自动重连(指数退避,最多 5 次)。 +Next.js 无长连接(除 WS),无需特殊处理。WS 在 P5 由 push-gateway 管理,前端断线自动重连(指数退避,最多 5 次,5 次后降级 HTTP 轮询)。 ## 7. 共享组件库(复用 Shell 暴露 + student 特有) @@ -409,10 +622,10 @@ Next.js 无长连接(除 WS),无需特殊处理。WS 在 P5 由 push-gatew | 组件 | 用途 | 来源 | | ------------------------------------------ | --------------------------------------------------------------------------------------------------- | ------------------------------ | -| `AppShell` | 左侧栏 + 主内容区布局 | teacher-portal Shell 暴露 | +| `AppShell` | 左侧栏 + 主内容区布局(按 scope=student 过滤视口) | teacher-portal Shell 暴露 | | `RequirePermission` | L3 组件级视口控制(无权限不渲染 children) | Shell 暴露 | | `ErrorBoundary` | React 渲染异常兜底(fallback UI) | Shell 暴露 | -| `Loading` | 骨架屏(Skeleton) | Shell 暴露 | +| `Loading` / `Skeleton` | 骨架屏 | Shell 暴露 | | `Empty` | 空态(插画 + 文案 + CTA) | Shell 暴露 | | `Modal` / `Dialog` | 全局 Modal(ModalRoot + Zustand ui-store) | Shell 暴露(shadcn/ui) | | `Toast` | 全局 toast(错误/成功/警告) | Shell 暴露(shadcn/ui sonner) | @@ -421,15 +634,20 @@ Next.js 无长连接(除 WS),无需特殊处理。WS 在 P5 由 push-gatew | `Chart` | 图表封装(recharts) | Shell 暴露 | | `A11y` 工具集 | useA11yId / mergeA11yProps / describeInput / focus-trap / skip-link / visually-hidden / aria-status | Shell 暴露 | | `Form` | react-hook-form + zodResolver 封装 | Shell 暴露 | +| `GraphQLProvider` | urql client 单例(ARB-002) | Shell 暴露 | -### 7.2 student-portal 特有组件(不暴露给 Shell) +### 7.2 student-portal 特有组件(不暴露给 Shell,除 ExamTaking) -| 组件 | 用途 | 来源 | 是否暴露给 Shell | -| ----------------- | --------------------------------------------- | ---- | ------------------------------------------- | -| `ExamTaking` | 考试作答(倒计时 + 自动保存 + 断网恢复) | 新建 | ✅ 暴露 `./ExamTaking`(供 Shell 路由复用) | -| `HomeworkSubmit` | 作业提交表单(react-hook-form + zodResolver) | 新建 | ❌ 内部使用 | -| `DiagnosticChart` | 学情诊断图表(recharts 多维雷达 + 趋势线) | 新建 | ❌ 内部使用 | -| `WeaknessList` | 错题本列表(按知识点聚合 + 掌握度标签) | 新建 | ❌ 内部使用 | +| 组件 | 用途 | 来源 | 是否 MF 暴露 | +| ----------------- | --------------------------------------------- | ---- | --------------------------------------- | +| `ExamTaking` | 考试作答(倒计时 + 自动保存 + 断网恢复 + 防作弊) | 新建 | ✅ 暴露 `./ExamTaking`(供 Shell 路由复用) | +| `HomeworkSubmit` | 作业提交表单(react-hook-form + zodResolver) | 新建 | ❌ 内部使用 | +| `DiagnosticChart` | 学情诊断图表(recharts 多维雷达 + 趋势线) | 新建 | ❌ 内部使用 | +| `WeaknessList` | 错题本列表(按知识点聚合 + 掌握度标签) | 新建 | ❌ 内部使用 | +| `LearningPathMap` | 学习路径图(知识点前置依赖可视化) | 新建 | ❌ 内部使用 | +| `ExamResultView` | 考试结果页(得分 + 错题分析 + 知识点掌握度) | 新建 | ❌ 内部使用 | +| `CountdownTimer` | 倒计时组件(基于服务器时间,避免客户端篡改) | 新建 | ❌ 内部使用 | +| `DraftRecovery` | 草稿恢复弹窗(断网恢复后提示是否恢复作答) | 新建 | ❌ 内部使用 | ### 7.3 不使用的组件(与 teacher-portal 差异) @@ -437,19 +655,45 @@ Next.js 无长连接(除 WS),无需特殊处理。WS 在 P5 由 push-gatew - 不使用 `SSEViewer`:学生不参与 AI 出题 - 不使用 `ChildSwitcher`:学生无多子女切换(家长端特有) - 不使用 `UserManagementTable`:学生不管理用户 +- 不使用 `RolePermissionMatrix`:学生不管理权限 -## 8. 共享 Hooks(复用 Shell 暴露) +## 8. 共享 Hooks(复用 Shell 暴露 + student 特有) + +### 8.1 复用 Shell 暴露的 Hooks | Hook | 职责 | 来源 | | --------------------- | --------------------------------------------------- | ---------- | | `useAuth()` | 会话状态(user/token/refresh/login/logout) | Shell 暴露 | | `usePermission()` | 权限查询(hasPermission/hasAny/hasAll + dataScope) | Shell 暴露 | | `useViewports(scope)` | 视口列表(按 scope 过滤) | Shell 暴露 | -| `useApi()` | ApiClient 实例(注入 token + 401 处理) | Shell 暴露 | +| `useGraphQLClient()` | urql client 实例(ARB-002 单例) | Shell 暴露 | | `useA11yId()` | 唯一 ARIA ID 生成 | Shell 暴露 | | `useAriaLive()` | aria-live 区域管理 | Shell 暴露 | | `useToast()` | 全局 toast(Zustand ui-store) | Shell 暴露 | +### 8.2 student-portal 特有 Hooks + +| Hook | 职责 | +| ------------------------- | ----------------------------------------------------- | +| `useStudentDashboard()` | 学生仪表盘聚合查询 | +| `useMyExams(status?)` | 我的考试列表 | +| `useExamDetail(examId)` | 考试详情(含题目,禁缓存) | +| `useExamTaking(examId)` | 考试作答状态(草稿 + 倒计时 + 自动保存 + 断网队列) | +| `useSaveExamAnswer()` | 保存答案 mutation(自动保存) | +| `useSubmitExam()` | 提交考试 mutation | +| `useMyHomework(status?)` | 我的作业列表 | +| `useSubmitHomework()` | 提交作业 mutation | +| `useMyGrades(subjectId?)` | 我的成绩列表 | +| `useMyAttendance(month?)` | 我的考勤 | +| `useDiagnostic(examId?)` | 学情诊断(P4) | +| `useMyWeakness(kpId?)` | 错题本(P4) | +| `useLearningPath()` | 学习路径(P4) | +| `useMyNotifications()` | 通知列表(P5) | +| `useServerTime()` | 服务器时间同步(倒计时校正) | +| `useExamTabGuard(examId)` | 考试多标签检测(BroadcastChannel) | +| `useAntiCheat(examId)` | 防作弊行为采集(visibilitychange/copy/paste 等) | +| `useOfflineQueue()` | 断网恢复队列(IDB 读写 + 重连重试) | + ## 9. 设计令牌三层(复用 Shell 提供的 packages/ui-tokens/) student-portal **不独立维护设计令牌**,复用 Shell 暴露的 `packages/ui-tokens/`(详见 [teacher-portal 阶段 2 §9](../../teacher-portal/docs/02-architecture-design.md#9-设计令牌三层packagesui-tokens待建立ai07-维护))。 @@ -467,131 +711,1339 @@ student-portal 的 ESLint flat config 与 Shell 共用,确保规则一致。 | 方向 | 对方服务 | 协议 | 接口/事件 | 用途 | 阶段 | | ------ | ------------ | ------------------ | ------------------------------------ | ---------------------------- | ---- | -| 调用 | api-gateway | HTTP/REST | `/api/v1/*` 代理 | 全部业务请求 | P1+ | +| 调用 | api-gateway | GraphQL over HTTP | `POST /api/v1/student/graphql` | 全部业务请求 | P3+ | +| 调用 | api-gateway | HTTP | `POST /api/auth/login` | 学生登录 | P2+ | | 调用 | push-gateway | WebSocket | `ws://push-gateway/ws` | 实时推送 | P5 | | 被调用 | — | — | — | 前端不暴露接口给其他服务 | — | -| 消费 | student-bff | HTTP(经 Gateway) | `GET /student/viewports` 等 | 学生场景聚合 | P3+ | -| 消费 | iam | HTTP(经 Gateway) | `/iam/*` | 登录/权限/视口 | P2+ | -| 消费 | core-edu | HTTP(经 Gateway) | `/exams/*` `/homework/*` `/grades/*` | 教学核心(学生视角) | P3+ | -| 消费 | data-ana | HTTP(经 Gateway) | `/analytics/*` | 学情分析 | P4+ | -| 消费 | msg | HTTP(经 Gateway) | `/notifications/*` | 通知中心 | P5+ | +| 消费 | student-bff | GraphQL | dashboard/myExams/myHomework 等 | 学生场景聚合 | P3+ | +| 消费 | iam | GraphQL(经 BFF) | currentUser(权限/视口) | 会话/权限 | P3+ | +| 消费 | core-edu | GraphQL(经 BFF) | exam/homework/grades 相关 | 教学核心(学生视角) | P3+ | +| 消费 | content | GraphQL(经 BFF) | textbooks/chapters/learningPath | 内容资源 | P4+ | +| 消费 | data-ana | GraphQL(经 BFF) | myWeakness/myTrend/diagnostic | 学情分析 | P4+ | +| 消费 | msg | GraphQL(经 BFF) | myNotifications/markAsRead | 通知中心 | P5+ | | 依赖 | coord 维护 | — | `packages/shared-proto` | TS 类型(仅 contracts 部分) | P1+ | -| 依赖 | coord 维护 | — | `packages/shared-ts`(待建) | ApiClient/Logger/通用工具 | P3+ | -| 依赖 | ai07 维护 | — | `packages/ui-tokens`(待建) | 三层设计令牌 | P3+ | -| 依赖 | ai07 维护 | — | `packages/ui-components`(待建) | shadcn + 共享组件 | P3+ | -| 依赖 | ai07 维护 | — | `packages/hooks`(待建) | usePermission/useAuth 等 | P3+ | -| 依赖 | coord 维护 | — | `packages/contracts`(待建) | Permissions 常量 + 类型 | P3+ | +| 依赖 | coord 维护 | — | `packages/shared-ts` | Logger/Tracer/通用工具 | P3+ | +| 依赖 | coord 维护 | — | `packages/contracts` | Permissions 常量 + 类型 | P3+ | +| 依赖 | ai13 维护 | — | `packages/ui-tokens` | 三层设计令牌 | P3+ | +| 依赖 | ai13 维护 | — | `packages/ui-components` | shadcn + 共享组件 | P3+ | +| 依赖 | ai13 维护 | — | `packages/hooks` | usePermission/useAuth 等 | P3+ | -> **proto 不直接消费**:前端不调用 gRPC,BFF 把 gRPC 聚合为 REST 暴露给前端。前端仅消费 `packages/contracts/src/permissions.ts` 中的权限点常量(TS 文件,非 proto 生成)。 +> **proto 不直接消费**:前端不调用 gRPC,student-bff 把 gRPC 聚合为 GraphQL 暴露给前端。前端仅消费 `packages/contracts/src/permissions.ts` 中的权限点常量(TS 文件,非 proto 生成)。 ## 11. 风险与假设 ### 11.1 假设 -1. **假设 coord 建立 `packages/shared-ts`、`packages/contracts`**:包含 ApiClient、Logger、Permissions 常量、通用类型。若 coord 未建立,ai07 自行在 `apps/student-portal/src/shared/` 内实现,后续提取到 packages。 -2. **假设 ai04 student-bff 提供 `GET /student/viewports`、`GET /student/dashboard`、`GET /student/homework`、`POST /student/homework/:id/submit`、`GET /student/diagnostic`**:返回 `ActionState` 结构。错误码前缀 `BFF_STUDENT_`(待 ai04 确认)。 -3. **假设 teacher-portal Shell 已就绪**:AppShell + 共享依赖暴露 + MF 配置(P2 收尾完成)。student-portal 作为 Remote 才能挂载。 -4. **假设 Next.js 14+ Module Federation 2.0 稳定**:`@module-federation/nextjs-mf` 在 Next.js App Router 下可用。若不稳定,降级为 4 端独立部署 + 各自 Shell(重复实现 AppShell)。 +1. **假设 coord 建立 `packages/shared-ts`、`packages/contracts`**:包含 Logger、Tracer、Permissions 常量、通用类型。若 coord 未建立,ai14 自行在 `apps/student-portal/src/shared/` 内实现,后续提取到 packages。 +2. **假设 ai13 teacher-portal Shell 按 ARB-002 暴露 GraphQL 单例**:`GraphQLProvider`/`useGraphQLClient`/`urql`/`graphql` singleton。若 Shell 未暴露,student-portal 降级为自建 urql client(违反 ARB-002,需 coord 仲裁)。 +3. **假设 ai04 student-bff 提供 GraphQL endpoint `POST /graphql`**:含 §4.2 全部 query/mutation。错误码前缀 `BFF_STUDENT_`(ARB-001 已确认)。 +4. **假设 teacher-portal Shell 已就绪**:AppShell + 共享依赖暴露 + MF 配置 + GraphQLProvider(P2 收尾完成)。student-portal 作为 Remote 才能挂载。 +5. **假设 Next.js 14+ Module Federation 2.0 稳定**:`@module-federation/nextjs-mf` 在 Next.js App Router + urql singleton 下可用。若不稳定,降级为 4 端独立部署 + 各自 Shell(重复实现 AppShell + GraphQLProvider)。 +6. **假设 ai10 msg 提供 WebSocket 事件**:`ExamExtended`/`ExamQuestionReordered` 事件名待 ai10 确认(见 issues/contracts)。 ### 11.2 技术风险 | 风险 | 影响 | 缓解 | | ----------------------- | ----------------------------------------------------------- | ---------------------------------------------------------------------- | -| MF Remote SSR 对齐复杂 | Remote 在 SSR 时需 Shell 提供上下文 | 优先 CSR,SSR 仅用于首屏 dashboard;MF 2.0 支持 SSR | -| 共享依赖版本漂移 | Remote 与 Shell 的 react/react-dom 版本不一致导致运行时错误 | MF `shared.singleton: true` + CI 检查版本对齐 | -| 考试作答断网丢失 | 学生作答过程中断网,草稿丢失 | Zustand L3 + localStorage 双写,每 30s + blur 时自动保存,重连后重试 | +| MF Remote SSR 对齐复杂 | Remote 在 SSR 时需 Shell 提供上下文 | 优先 CSR,SSR 仅用于首屏 dashboard;考试作答页强制 CSR(防缓存) | +| GraphQL singleton 分裂 | Remote 与 Shell 的 urql client 不是同一实例,cache 分裂 | MF `shared.singleton: true` + ARB-002 强制 + CI 检查 | +| 共享依赖版本漂移 | Remote 与 Shell 的 react/urql 版本不一致导致运行时错误 | MF `shared.singleton: true` + `requiredVersion` + CI 检查版本对齐 | +| 考试作答断网丢失 | 学生作答过程中断网,草稿丢失 | Zustand L3 + IDB 双写,每 30s + blur 时自动保存,重连后批量重试 | | 考试倒计时不准 | 学生端时间与服务器时间偏差 | 倒计时基于服务器返回的 `expiresAt`,前端仅做展示,提交以服务器时间为准 | +| 考试题目缓存泄露 | 考试题目被缓存到 CDN/Service Worker,泄露答案 | 考试作答页 `ssr: false` + urql cache staleTime 0 + Security Header 防缓存 | | 缓存陈旧导致看到旧作业 | 学生看到已截止的作业 | staleTime 30s + 截止时间客户端校验 + 提交时服务端二次校验 | -| Token 刷新竞态 | 多请求同时 401 触发多次 refresh | ApiClient 全局单例 + refresh promise 复用(复用 Shell) | +| Token 刷新竞态 | 多请求同时 401 触发多次 refresh | urql auth exchange 全局单例 + refresh promise 复用(复用 Shell) | | 权限缓存陈旧 | 角色变更后前端 5min 内仍用旧权限 | iam 角色变更发 Kafka 事件 → msg 推送 WebSocket → 前端 invalidate | -| TanStack Query 缓存膨胀 | 长时间使用后缓存项过多 | `gcTime` 5min + `staleTime` 按数据类型分级 | +| IDB 存储空间不足 | 考试草稿 + 断网队列累积超过浏览器配额 | 提交成功后立即清除 IDB 草稿;定期清理 7 天前的未提交草稿 | +| BroadcastChannel 兼容性 | Safari < 15.4 不支持 | 降级为 `localStorage` 事件(storage event listener) | ### 11.3 未决设计决策(需 coord 仲裁) -与 teacher-portal 相同的 4 项(详见 [teacher-portal 阶段 2 §11.3](../../teacher-portal/docs/02-architecture-design.md#113-未决设计决策需-coord-仲裁)): - -1. **packages 归属**:`ui-tokens` / `ui-components` / `hooks` 是 ai07 维护还是 coord 维护?建议:ai07 维护(前端专属),coord 仅维护 `shared-ts` / `contracts`(跨语言/跨服务)。 -2. **GraphQL vs REST**:student-bff 是 REST 还是 GraphQL?前端 API 请求层是否需要 GraphQL client(urql/apollo)?建议:P3-P4 用 REST,若 BFF 切 GraphQL 再引入 urql。 -3. **i18n key 命名**:`error.{{service}}.{{code_snake_case}}` 还是其他模式?建议:与 teacher-portal 对齐。 -4. **MF 暴露粒度**:Shell 暴露整个 AppShell 还是更细粒度的组件?建议:暴露 AppShell 整体 + 各 Remote 自行决定内部布局。 +| 决策 | 当前方案 | 状态 | +| ------------------------------ | ------------------------------------- | ------------------- | +| GraphQL vs REST | **GraphQL**(ARB-001 已裁决) | ✅ 已裁决 | +| MF Shell 暴露清单 | **GraphQLProvider + urql singleton** | ✅ 已裁决(ARB-002)| +| packages 归属 | ai13 维护 ui-*/hooks,coord 维护 shared-ts/contracts | ✅ 已确认 | +| 考试作答防作弊事件名 | `ExamExtended`/`ExamQuestionReordered`| ⚠️ 待 ai10 msg 确认 | +| 附件上传协议 | GraphQL mutation `uploadAttachment` | ⚠️ 待 ai04 确认是否走 multipart | +| 主观题是否允许粘贴 | 阻止粘贴(待产品确认) | ⚠️ 待产品决策 | +| 考试作答页是否强制全屏 | 不强制(P6+ lockdown 浏览器才强制) | ⚠️ 待产品决策 | ## 12. coord 交叉审查所需信息 ### 12.1 端口矩阵 -| 端 | dev 端口 | 生产端口 | 备注 | -| -------------- | -------- | -------- | ------------- | -| student-portal | 3001 | 3001 | Remote 子应用 | +| 端 | dev 端口 | 生产端口 | 备注 | +| -------------- | -------- | -------- | ------------------------------------- | +| student-portal | **4001** | **4001** | MF Remote 子应用(P3 首个 Remote) | -> 与 [full-stack-runbook](../../../docs/standards/full-stack-runbook.md) 端口矩阵对齐。 +> 与 [port-allocation](../../../infra/port-allocation.md) §4 对齐(4000-4003 强制 4 端 portal)。 -### 12.2 依赖的共享包(需 coord 建立) +### 12.2 依赖的共享包(需 coord / ai13 建立) -| 包 | 路径 | 维护方 | 内容 | -| --------------- | ------------------------- | ------------ | ------------------------------------------------- | -| `shared-ts` | `packages/shared-ts/` | coord | ApiClient、Logger、通用工具 | -| `contracts` | `packages/contracts/` | coord | Permissions 常量、ActionState 类型、UserInfo 类型 | -| `ui-tokens` | `packages/ui-tokens/` | ai07(建议) | 三层设计令牌 | -| `ui-components` | `packages/ui-components/` | ai07(建议) | shadcn + ErrorBoundary + RequirePermission | -| `hooks` | `packages/hooks/` | ai07(建议) | usePermission、useAuth、useViewports | +| 包 | 路径 | 维护方 | 内容 | +| --------------- | ------------------------- | ------ | ------------------------------------------------- | +| `shared-ts` | `packages/shared-ts/` | coord | Logger、Tracer、通用工具 | +| `contracts` | `packages/contracts/` | coord | Permissions 常量、ActionState 类型、UserInfo 类型 | +| `ui-tokens` | `packages/ui-tokens/` | ai13 | 三层设计令牌 | +| `ui-components` | `packages/ui-components/` | ai13 | shadcn + ErrorBoundary + RequirePermission + GraphQLProvider | +| `hooks` | `packages/hooks/` | ai13 | usePermission、useAuth、useViewports、useGraphQLClient | ### 12.3 依赖的后端契约(需对应 AI 确认) -| 契约 | 提供方 | 当前状态 | -| ------------------------------------------------------------------ | ------------------ | --------------- | -| `POST /iam/login`、`GET /iam/effective-permissions`、`GET /iam/me` | iam | ✅ 已实现 | -| `GET /student/viewports`、`GET /student/dashboard` 等 | student-bff | 📐 待 ai04 设计 | -| `/exams/*` `/homework/*` `/grades/*` | core-edu | ✅ 已实现(P3) | -| `/analytics/*` | data-ana | ✅ 已实现(P4) | -| `/notifications/*` + WebSocket 推送 | msg + push-gateway | 📐 待 P5 | +| 契约 | 提供方 | 当前状态 | +| ----------------------------------------------------- | ------------------ | --------------- | +| `POST /api/auth/login` | api-gateway | ✅ 已实现 | +| GraphQL `POST /api/v1/student/graphql`(§4.2 全部操作)| student-bff | 📐 待 ai04 设计 | +| `/exams/*` `/homework/*` `/grades/*`(gRPC,经 BFF) | core-edu | ✅ 已实现(P3) | +| `/analytics/*`(gRPC,经 BFF) | data-ana | ✅ 已实现(P4) | +| `/notifications/*` + WebSocket 推送 | msg + push-gateway | 📐 待 P5 | +| WebSocket 事件 `ExamExtended`/`ExamQuestionReordered` | msg | ⚠️ 待 ai10 确认 | ### 12.4 错误码前缀(前端 i18n 路由依赖) 前端不产生错误码,仅消费。需各服务确认错误码前缀不重叠: -| 前缀 | 服务 | 状态 | -| ------------------------------ | ----------- | --------------- | -| `IAM_` | iam | ✅ 已用 | -| `EXAMS_`/`HOMEWORK_`/`GRADES_` | core-edu | ⚠️ 待确认 | -| `BFF_STUDENT_` | student-bff | ⚠️ 待 ai04 确认 | -| `GW_` | api-gateway | ✅ 已用 | -| `NETWORK_` | 前端 | ai07 自有 | +| 前缀 | 服务 | 状态 | +| --------------- | ----------- | --------------- | +| `IAM_` | iam | ✅ 已用 | +| `CORE_EDU_` | core-edu | ✅ 已确认(§2.15)| +| `BFF_STUDENT_` | student-bff | ✅ 已确认(ARB-001)| +| `GW_` | api-gateway | ✅ 已用 | +| `NETWORK_` | 前端 | ai14 自有 | ### 12.5 不产生 Kafka 事件 前端不发布/消费 Kafka 事件。WebSocket 推送由 push-gateway 消费 Kafka 转发。 -## 13. 实施路线(ai07 自用) +## 13. 实施路线(ai14 自用) -### P3(student-portal 起步) +### P3(student-portal 起步 — 核心教学) -1. 建 `apps/student-portal/`(Remote 角色) -2. 配置 MF(`exposes: { './pages', './ExamTaking' }`,`remotes: { teacher: ... }`) -3. 实现 Dashboard + 我的作业 + 提交作业 + 我的考试 + 作答考试 -4. 复用 Shell 的 AppShell + 共享组件(RequirePermission/ErrorBoundary/Loading/Empty/DataTable/Form/Chart) -5. 考试作答自动保存(HTTP POST 每 30s + blur 时,Zustand L3 + localStorage 双写草稿) +1. 建 `apps/student-portal/`(Remote 角色),配置 MF(ARB-002:urql/graphql singleton) +2. 实现 GraphQL Hooks 层(§8.2 全部 P3 Hooks),复用 Shell `useGraphQLClient()` +3. 实现 Dashboard + 我的作业 + 提交作业 + 我的考试 + 作答考试 + 考试结果 + 我的成绩 + 我的考勤 +4. **考试作答核心**(§14 详述):CountdownTimer + 自动保存 + IDB 断网恢复 + 防作弊采集 + DraftRecovery +5. 复用 Shell 的 AppShell + 共享组件(RequirePermission/ErrorBoundary/Loading/Empty/DataTable/Form/Chart) 6. 配置 Dockerfile 多阶段构建 + `/api/health` + `/api/ready` route -7. 补 Vitest 单测 + Playwright E2E(覆盖率 ≥ 80%) +7. 补 Vitest 单测 + Playwright E2E(覆盖率 ≥ 80%,含考试作答边界场景 6 个 E2E) +8. 接入 MSW Mock(GraphQL handlers + mock-socket) -### P4(学情诊断 + 错题本) +### P4(学情诊断 + 错题本 + 学习路径) 1. 实现学情诊断页面(DiagnosticChart 多维雷达 + 趋势线) 2. 实现错题本页面(WeaknessList 按知识点聚合 + 掌握度标签) +3. 实现学习路径页面(LearningPathMap 知识点前置依赖可视化) +4. 接入 content 服务 GraphQL(textbooks/chapters/learningPath) ### P5(推送 + 通知中心) -1. student-portal 接入 WebSocket(push-gateway) +1. student-portal 接入 WebSocket(push-gateway),指数退避重连 + HTTP 轮询降级 2. 实现通知中心页面(通知列表 + 未读数 + 标记已读) -3. 处理 4 类推送事件(NotificationRequested/ExamPublished/GradeRecorded/HomeworkDeadlineApproaching) +3. 处理 6 类推送事件(NotificationRequested/ExamPublished/ExamExtended/ExamQuestionReordered/GradeRecorded/HomeworkDeadlineApproaching) ### P6(硬化) 1. Web Vitals + OTel browser SDK 接入 -2. A11y WCAG 2.2 AA 审计 -3. 性能优化(MF shared 单例验证、bundle 分析) +2. A11y WCAG 2.2 AA 审计(考试作答页键盘可操作 + 屏幕阅读器友好) +3. 性能优化(MF shared 单例验证、bundle 分析、代码分割) +4. PWA 配置(manifest + Service Worker,考试作答页 Network Only) +5. 隐私合规完善(PIPL/未成年人保护法强制项) +6. 多语言(en-US/zh-TW)100% 完成度 --- -**AI Agent**: ai07 (student-portal remote) -**Branch**: docs/student-portal-stage1-stage2-design-ai07 +## 14. 考试作答架构设计(ai14 新增 — 核心复杂场景) + +> 考试作答是学生端最复杂、最易出问题的场景,必须在架构中预留所有边界场景的处理。本节是 ai14 新增,对齐 [01-understanding.md §11](./01-understanding.md#11-考试作答边界场景学生端特有必须覆盖)。 + +### 14.1 考试作答状态机 + +```mermaid +stateDiagram-v2 + [*] --> NotStarted: 进入 /my-exams/:id/take(早于 startsAt) + [*] --> InProgress: 进入(startsAt ≤ now ≤ expiresAt) + NotStarted --> InProgress: 到达 startsAt + + InProgress --> AutoSaving: 每 30s / blur + AutoSaving --> InProgress: 保存成功 + AutoSaving --> OfflineMode: 保存失败(网络中断) + + OfflineMode --> InProgress: 网络恢复 + 队列重试成功 + OfflineMode --> AutoSubmit: 倒计时归零 + + InProgress --> ConfirmSubmit: 学生点击提交 + ConfirmSubmit --> Submitting: 确认提交 + ConfirmSubmit --> InProgress: 取消提交 + + Submitting --> Submitted: 提交成功 + Submitting --> Submitting: 重试(查询提交状态,防重复) + Submitting --> IDBQueue: 提交失败入队 + + AutoSubmit --> Submitting: 倒计时归零自动提交 + + IDBQueue --> Submitting: 网络恢复后重试 + + Submitted --> [*]: 跳转 /my-exams/:id/result + Submitted --> ClearDraft: 清除 IDB 草稿 + ClearDraft --> [*] +``` + +### 14.2 倒计时与服务器时间对齐 + +```typescript +// apps/student-portal/src/lib/serverTimeSync.ts +import { useGraphQLClient } from "@edu/hooks"; + +const SERVER_TIME_QUERY = gql` + query ServerTime { + serverTime + } +`; + +export function useServerTimeSync() { + const client = useGraphQLClient(); + const [offset, setOffset] = useState(0); // serverTime - clientTime(ms) + + const sync = useCallback(async () => { + const requestStart = Date.now(); + const result = await client.query(SERVER_TIME_QUERY, {}).toPromise(); + const requestEnd = Date.now(); + if (result.data?.serverTime) { + const serverTime = new Date(result.data.serverTime).getTime(); + const roundTrip = requestEnd - requestStart; + const estimatedClientTimeAtServer = requestStart + roundTrip / 2; + setOffset(serverTime - estimatedClientTimeAtServer); + } + }, [client]); + + useEffect(() => { + sync(); + // 每 5 分钟重新同步一次 + const interval = setInterval(sync, 5 * 60 * 1000); + return () => clearInterval(interval); + }, [sync]); + + // 获取校正后的当前时间 + const getCorrectedTime = () => Date.now() + offset; + + return { offset, sync, getCorrectedTime }; +} + +// 倒计时 Hook +export function useCountdownTimer(expiresAt: string, serverTimeOffset: number) { + const [remaining, setRemaining] = useState(0); + + useEffect(() => { + const calculate = () => { + const correctedNow = Date.now() + serverTimeOffset; + const expiry = new Date(expiresAt).getTime(); + const diff = expiry - correctedNow; + setRemaining(Math.max(0, Math.floor(diff / 1000))); + }; + calculate(); + const interval = setInterval(calculate, 1000); + return () => clearInterval(interval); + }, [expiresAt, serverTimeOffset]); + + return { + remaining, + formatted: formatDuration(remaining), + isExpired: remaining === 0, + }; +} + +function formatDuration(seconds: number): string { + const h = Math.floor(seconds / 3600); + const m = Math.floor((seconds % 3600) / 60); + const s = seconds % 60; + return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`; +} +``` + +### 14.3 自动保存与断网恢复(IDB 队列) + +```typescript +// apps/student-portal/src/lib/examQueue.ts +import { openDB } from "idb"; + +const DB_NAME = "student-exam"; +const DB_VERSION = 1; +const DRAFT_STORE = "drafts"; +const QUEUE_STORE = "queue"; + +async function getDB() { + return openDB(DB_NAME, DB_VERSION, { + upgrade(db) { + if (!db.objectStoreNames.contains(DRAFT_STORE)) { + db.createObjectStore(DRAFT_STORE, { keyPath: "examId" }); + } + if (!db.objectStoreNames.contains(QUEUE_STORE)) { + db.createObjectStore(QUEUE_STORE, { keyPath: "id", autoIncrement: true }); + } + }, + }); +} + +// 保存草稿到 IDB(断网恢复用) +export async function saveDraftToIDB(draft: ExamTakingDraft): Promise { + const db = await getDB(); + await db.put(DRAFT_STORE, draft); +} + +// 从 IDB 加载草稿 +export async function loadDraftFromIDB(examId: string): Promise { + const db = await getDB(); + return db.get(DRAFT_STORE, examId); +} + +// 清除草稿(提交成功后) +export async function clearDraftFromIDB(examId: string): Promise { + const db = await getDB(); + await db.delete(DRAFT_STORE, examId); +} + +// 入队失败的保存请求(断网重试用) +export async function enqueueFailedSave(item: { + examId: string; + questionId: string; + answer: AnswerInput; + queuedAt: number; +}): Promise { + const db = await getDB(); + await db.add(QUEUE_STORE, item); +} + +// 出队并重试 +export async function processQueue( + retryFn: (item: { examId: string; questionId: string; answer: AnswerInput }) => Promise, +): Promise { + const db = await getDB(); + const tx = db.transaction(QUEUE_STORE, "readwrite"); + const allItems = await tx.store.getAll(); + + for (const item of allItems) { + const success = await retryFn({ + examId: item.examId, + questionId: item.questionId, + answer: item.answer, + }); + if (success) { + await tx.store.delete(item.id); + } + } + await tx.done; +} + +// 监听网络恢复事件 +export function useOfflineQueue_recovery(retryFn: (item: any) => Promise) { + useEffect(() => { + const handleOnline = () => { + processQueue(retryFn); + }; + window.addEventListener("online", handleOnline); + // 页面可见时也尝试处理队列 + document.addEventListener("visibilitychange", () => { + if (document.visibilityState === "visible" && navigator.onLine) { + processQueue(retryFn); + } + }); + return () => { + window.removeEventListener("online", handleOnline); + }; + }, [retryFn]); +} +``` + +### 14.4 考试作答自动保存策略 + +```typescript +// apps/student-portal/src/hooks/useExamTaking.ts +export function useExamTaking(examId: string) { + const client = useGraphQLClient(); + const { offset, getCorrectedTime } = useServerTimeSync(); + const [draft, setDraft] = useState(null); + const [isOnline, setIsOnline] = useState(navigator.onLine); + + // 进入考试页时加载草稿 + useEffect(() => { + loadDraftFromIDB(examId).then((saved) => { + if (saved) { + // 检测到未完成草稿,弹 DraftRecovery + showDraftRecoveryDialog(saved).then((restore) => { + if (restore) setDraft(saved); + else setDraft(createNewDraft(examId)); + }); + } else { + setDraft(createNewDraft(examId)); + } + }); + }, [examId]); + + // 自动保存(每 30s + blur) + useEffect(() => { + if (!draft) return; + + const autoSave = async () => { + if (!isOnline) { + // 离线:入 IDB 队列 + await saveDraftToIDB(draft); + return; + } + try { + const result = await client + .mutation(SAVE_EXAM_ANSWER, { + examId, + questionId: "batch", // 批量保存 + answer: draft.answers, + }) + .toPromise(); + if (result.data?.saveExamAnswer?.ok) { + setDraft((prev) => ({ ...prev!, lastSavedAt: Date.now() })); + await saveDraftToIDB(draft); // 同步到 IDB + } + } catch (err) { + // 保存失败,入队列 + await enqueueFailedSave({ + examId, + questionId: "batch", + answer: draft.answers as any, + queuedAt: Date.now(), + }); + logger.warn("exam auto-save failed, queued", { examId, error: err }); + } + }; + + const interval = setInterval(autoSave, 30 * 1000); // 每 30s + const onBlur = () => autoSave(); // blur 时 + + window.addEventListener("blur", onBlur); + return () => { + clearInterval(interval); + window.removeEventListener("blur", onBlur); + }; + }, [draft, client, examId, isOnline]); + + // 监听网络状态 + useEffect(() => { + const updateOnline = () => setIsOnline(navigator.onLine); + window.addEventListener("online", updateOnline); + window.addEventListener("offline", updateOnline); + return () => { + window.removeEventListener("online", updateOnline); + window.removeEventListener("offline", updateOnline); + }; + }, []); + + // 网络恢复后处理队列 + useOfflineQueue_recovery(async (item) => { + try { + const result = await client + .mutation(SAVE_EXAM_ANSWER, { + examId: item.examId, + questionId: item.questionId, + answer: item.answer, + }) + .toPromise(); + return result.data?.saveExamAnswer?.ok ?? false; + } catch { + return false; + } + }); + + // 更新答案 + const updateAnswer = useCallback((questionId: string, answer: AnswerInput) => { + setDraft((prev) => { + if (!prev) return prev; + return { + ...prev, + answers: { ...prev.answers, [questionId]: answer }, + }; + }); + }, []); + + return { + draft, + isOnline, + serverTimeOffset: offset, + correctedNow: getCorrectedTime(), + updateAnswer, + }; +} +``` + +### 14.5 防作弊采集(前端配合,服务端最终判定) + +```typescript +// apps/student-portal/src/hooks/useAntiCheat.ts +export function useAntiCheat(examId: string) { + const behaviorsRef = useRef([]); + const [warning, setWarning] = useState(null); + + const record = useCallback( + (type: SuspiciousBehaviorRecord["type"], details?: string) => { + const record_item: SuspiciousBehaviorRecord = { + type, + timestamp: Date.now(), + details, + }; + behaviorsRef.current.push(record_item); + + // 队列满 100 条后批量上报 + if (behaviorsRef.current.length >= 100) { + flushBehaviors(); + } + }, + [examId], + ); + + const flushBehaviors = useCallback(async () => { + if (behaviorsRef.current.length === 0) return; + const batch = behaviorsRef.current.splice(0); + try { + await client + .mutation(RECORD_SUSPICIOUS_BEHAVIOR, { + examId, + behaviors: batch, + }) + .toPromise(); + } catch (err) { + // 上报失败,重新入队 + behaviorsRef.current.unshift(...batch); + } + }, [examId]); + + // 切屏检测 + useEffect(() => { + let switchCount = 0; + const handleVisibility = () => { + if (document.visibilityState === "hidden") { + switchCount += 1; + record("tab-switch", `switch #${switchCount}`); + if (switchCount >= 3) { + setWarning(t("exam.antiCheat.tooManyTabSwitches")); + toast.warning(t("exam.antiCheat.tooManyTabSwitches")); + } + } + }; + document.addEventListener("visibilitychange", handleVisibility); + return () => document.removeEventListener("visibilitychange", handleVisibility); + }, [record]); + + // 复制粘贴检测 + useEffect(() => { + const handleCopy = (e: ClipboardEvent) => { + e.preventDefault(); + record("copy-paste", "copy attempted"); + toast.warning(t("exam.antiCheat.copyDisabled")); + }; + const handlePaste = (e: ClipboardEvent) => { + e.preventDefault(); + record("copy-paste", "paste attempted"); + toast.warning(t("exam.antiCheat.pasteDisabled")); + }; + document.addEventListener("copy", handleCopy); + document.addEventListener("paste", handlePaste); + return () => { + document.removeEventListener("copy", handleCopy); + document.removeEventListener("paste", handlePaste); + }; + }, [record]); + + // 全屏退出检测 + useEffect(() => { + const handleFullscreen = () => { + if (!document.fullscreenElement) { + record("fullscreen-exit"); + toast.warning(t("exam.antiCheat.fullscreenExit")); + } + }; + document.addEventListener("fullscreenchange", handleFullscreen); + return () => document.removeEventListener("fullscreenchange", handleFullscreen); + }, [record]); + + // 窗口失焦检测 + useEffect(() => { + const handleBlur = () => { + record("window-blur"); + }; + window.addEventListener("blur", handleBlur); + return () => window.removeEventListener("blur", handleBlur); + }, [record]); + + // 右键禁用 + useEffect(() => { + const handleContext = (e: MouseEvent) => { + e.preventDefault(); + }; + document.addEventListener("contextmenu", handleContext); + return () => document.removeEventListener("contextmenu", handleContext); + }, []); + + // 卸载时 flush + useEffect(() => { + return () => { + flushBehaviors(); + }; + }, [flushBehaviors]); + + return { warning, flushBehaviors }; +} +``` + +### 14.6 考试提交防重复 + +```typescript +// apps/student-portal/src/hooks/useSubmitExam.ts +export function useSubmitExam(examId: string) { + const client = useGraphQLClient(); + const queryClient = useQueryClient(); + const [submitting, setSubmitting] = useState(false); + + const submit = useCallback(async () => { + setSubmitting(true); + try { + // 提交前先查询提交状态,防重复 + const statusResult = await client + .query(EXAM_SUBMISSION_STATUS, { examId }) + .toPromise(); + + if (statusResult.data?.examSubmissionStatus?.submitted) { + // 已提交,跳转结果页 + toast.info(t("exam.alreadySubmitted")); + router.push(`/my-exams/${examId}/result`); + return; + } + + // 执行提交 + const result = await client + .mutation(SUBMIT_EXAM, { examId }) + .toPromise(); + + if (result.data?.submitExam) { + // 提交成功,清除 IDB 草稿 + await clearDraftFromIDB(examId); + queryClient.invalidateQueries({ queryKey: ["student", "exams"] }); + queryClient.invalidateQueries({ queryKey: ["student", "dashboard"] }); + toast.success(t("exam.submitSuccess")); + router.push(`/my-exams/${examId}/result`); + } else if (result.error) { + // 提交失败,入 IDB 队列 + toast.error(t("exam.submitFailed")); + // 入队,稍后重试 + } + } catch (err) { + // 网络错误,入 IDB 队列 + toast.error(t("exam.submitFailedNetwork")); + } finally { + setSubmitting(false); + } + }, [examId, client, queryClient]); + + return { submit, submitting }; +} +``` + +--- + +## 15. 详细组件设计(ai14 新增) + +### 15.1 ExamTaking 组件 + +```typescript +// apps/student-portal/src/components/ExamTaking.tsx +interface ExamTakingProps { + examId: string; +} + +export function ExamTaking({ examId }: ExamTakingProps) { + const { draft, isOnline, serverTimeOffset, updateAnswer } = useExamTaking(examId); + const { data: exam } = useExamDetail(examId); + const { remaining, formatted, isExpired } = useCountdownTimer( + exam?.expiresAt ?? "", + serverTimeOffset, + ); + const { warning } = useAntiCheat(examId); + const { submit, submitting } = useSubmitExam(examId); + const [showConfirmSubmit, setShowConfirmSubmit] = useState(false); + + // 倒计时归零自动提交 + useEffect(() => { + if (isExpired && !submitting) { + toast.info(t("exam.timeUp")); + submit(); + } + }, [isExpired, submitting, submit]); + + // 考试延时事件 + useEffect(() => { + // 由 WebSocket 事件触发 exam query invalidate,exam.expiresAt 更新后倒计时自动重置 + }, [exam?.expiresAt]); + + if (!draft || !exam) return ; + + const unansweredCount = exam.questions.filter((q) => !draft.answers[q.id]).length; + + return ( +
+ {/* 顶部固定:倒计时 + 在线状态 */} +
+
+ + +
+ {warning &&
{warning}
} +
+ + {/* 题目区域 */} +
+ {exam.questions.map((q, index) => ( + updateAnswer(q.id, answer)} + /> + ))} +
+ + {/* 底部固定:提交按钮 */} +
+ +
+ + {/* 提交确认弹窗 */} + + + {unansweredCount > 0 && ( +

+ {t("exam.unansweredWarning", { count: unansweredCount })} +

+ )} +

{t("exam.confirmSubmit")}

+
+ + +
+
+
+ + {/* 草稿恢复弹窗由 useExamTaking 内部触发 */} + +
+ ); +} +``` + +### 15.2 CountdownTimer 组件 + +```typescript +// apps/student-portal/src/components/CountdownTimer.tsx +interface CountdownTimerProps { + remaining: number; // 秒 + formatted: string; // HH:mm:ss + isExpired: boolean; +} + +export function CountdownTimer({ remaining, formatted, isExpired }: CountdownTimerProps) { + const isUrgent = remaining <= 300 && remaining > 0; // 最后 5 分钟 + const isCritical = remaining <= 60 && remaining > 0; // 最后 1 分钟 + + return ( +
+ {isExpired ? t("exam.timeUp") : formatted} +
+ ); +} +``` + +### 15.3 DraftRecovery 组件 + +```typescript +// apps/student-portal/src/components/DraftRecovery.tsx +interface DraftRecoveryProps { + examId: string; +} + +export function DraftRecovery({ examId }: DraftRecoveryProps) { + const [open, setOpen] = useState(false); + const [savedDraft, setSavedDraft] = useState(null); + + useEffect(() => { + loadDraftFromIDB(examId).then((draft) => { + if (draft && Object.keys(draft.answers).length > 0) { + setSavedDraft(draft); + setOpen(true); + } + }); + }, [examId]); + + const handleRestore = () => { + // 父组件通过 context 接收恢复的草稿 + setOpen(false); + }; + + const handleDiscard = async () => { + await clearDraftFromIDB(examId); + setOpen(false); + }; + + return ( + + +

{t("exam.draftRecovery.title")}

+

+ {t("exam.draftRecovery.description", { + answeredCount: savedDraft ? Object.keys(savedDraft.answers).length : 0, + lastSavedAt: savedDraft?.lastSavedAt, + })} +

+
+ + +
+
+
+ ); +} +``` + +### 15.4 HomeworkSubmit 组件 + +```typescript +// apps/student-portal/src/components/HomeworkSubmit.tsx +interface HomeworkSubmitProps { + homeworkId: string; +} + +const homeworkSchema = z.object({ + answers: z.array( + z.object({ + questionId: z.string(), + answer: answerInputSchema, + }), + ), + note: z.string().max(500).optional(), +}); + +export function HomeworkSubmit({ homeworkId }: HomeworkSubmitProps) { + const { data: homework } = useHomeworkDetail(homeworkId); + const { mutate, isPending } = useSubmitHomework(); + const form = useForm({ + resolver: zodResolver(homeworkSchema), + }); + + const onSubmit = (data: HomeworkSubmitForm) => { + mutate({ homeworkId, ...data }); + }; + + if (!homework) return ; + + return ( +
+ + {homework.questions.map((q, index) => ( + + ))} + + {/* 附件上传 */} + + + {/* 学生备注 */} +