docs(teacher-portal): ai07 阶段1+2 拆分到4端portal的docs目录

删除合并版README,按portal拆分8份文档(每端01-understanding+02-architecture-design)

teacher-portal(shell/P2)+student-portal(remote/P3)+parent-portal(remote/P4)+admin-portal(remote/P6)

AI Agent: ai07 (4 portals)

Branch: docs/portals-stage1-stage2-design-ai07
This commit is contained in:
SpecialX
2026-07-09 18:23:27 +08:00
parent fd5b6e19ae
commit e691cd267d
9 changed files with 3457 additions and 945 deletions

View File

@@ -0,0 +1,233 @@
# 模块理解确认书 — admin-portal
> AIai07TS/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 P6](../../../docs/architecture/roadmap/pending-features.md)、[known-issues §2.12](../../../docs/troubleshooting/known-issues.md)、[teacher-portal 阶段1](../../teacher-portal/docs/01-understanding.md)、[teacher-portal 阶段2](../../teacher-portal/docs/02-architecture-design.md)
---
## 1. 我在架构中的位置
- **层级**L2 微前端层004 §3.1 六层架构中的前端层)
- **MF 角色****Remote 子应用**,挂载到 teacher-portal Shell主应用
- **上游(谁调用我)**:浏览器(系统管理员 / 校管理员)
- **下游(同步)**api-gatewayREST经 teacher-portal Shell 的 Next.js `rewrites` 代理 `/api/v1/*`
- **下游(推送)**:— **不消费推送**,管理端用轮询)
- **BFF 对接**teacher-bff 复用(`/admin/*` 聚合)+ iam 直连(`/iam/*` 用户/角色/权限/视口 CRUD
- **通信方式**HTTP/REST前端→Gateway
- **不直连**:前端不直连任何业务服务或 BFF 后端实例,全部经 api-gateway 代理
**说明**
- admin-portal 作为 Remote 子应用,挂载到 teacher-portal Shell 提供的 AppShell + 共享依赖react/react-dom/@tanstack/react-query/zustand/nuqs/ui-components/ui-tokens/contracts/hooks
- 路由前缀 `/admin/*` 由 teacher-portal Shell 动态加载 admin-portal Remote 模块
- 场景域 BFF 复用策略004 §5.4):系统/校管理员复用 teacher-portal Shell + teacher-bff`/admin/*` 视口)+ iam 直连,不单独建 portal 后端
- 全部业务请求经 api-gateway 代理admin-portal 本身不实现 rewrites依赖 Shell 的 rewrites
## 2. 我的限界上下文
### 2.1 我负责的聚合 / 实体(前端视图模型)
- 用户、角色、权限、视口(管理场景域前端视图)
- 组织(学校/年级/班级层级)
- 平台监控(运行时指标、用户活动、错误统计)
- 会话状态Session、视口Viewport、权限Permission与 teacher-portal 共享,引用 teacher-portal 文档)
### 2.2 业务领域
- **管理场景域**(前端场景域:管理场景域,对应后端 iam 限界上下文 + teacher-bff 管理视口)
### 2.3 不负责
- 教学业务编排(班级/考试/作业/成绩 CRUD归 teacher-portal
- 学生作答界面(归 student-portal
- 家长多子女切换(归 parent-portal
- 教师仪表盘(归 teacher-portaladmin-portal 仅有管理仪表盘)
### 2.4 数据范围
- DataScope L3-L5校管理员 L3 学校 / 区教研员 L4 / 系统管理员 L5 全平台)
- 不出现 L1班级/ L2年级级别的教师数据视角
## 3. 我与外部的契约
### 3.1 消费的后端 API经 api-gateway 代理)
| 路径前缀 | 下游 BFF/服务 | 关键端点 |
| ------------------------- | --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/api/v1/iam/*`(管理用) | iam | `GET /iam/users``POST /iam/users``PUT /iam/users/:id``GET /iam/roles``GET /iam/permissions``GET /iam/viewports``PUT /iam/viewports/:id` |
| `/api/v1/admin/*` | teacher-bff 复用 + iam 直连 | `GET /admin/dashboard``GET /admin/monitoring/metrics``GET /admin/stats/users``GET /admin/stats/active-sessions` |
| `/api/v1/notifications/*` | msg | 通知中心P5 |
### 3.2 统一响应契约
所有后端响应遵循 `ActionState` 结构(迁移指南 §7.5
```typescript
type ActionState<T> =
| { success: true; data: T }
| {
success: false;
error: { code: string; message: string; details?: unknown };
};
```
错误码前缀按服务名大写admin-portal 涉及:`IAM_``BFF_TEACHER_``GW_``NETWORK_`)。前端 API 请求层根据 `error.code` 前缀路由到对应的 i18n key。
### 3.3 推送契约
**— N/A**
admin-portal **不消费** WebSocket 推送或 SSE 流式响应。管理端场景对实时性要求低,采用**轮询**策略:
- 平台监控页60s 轮询 `GET /api/v1/admin/monitoring/metrics`
- 用户活动统计5min 轮询 `GET /api/v1/admin/stats/active-sessions`
- 通知中心P5HTTP 长轮询或定时拉取 `GET /api/v1/notifications`(不走 push-gateway
> 长期监控指标推荐用 `<iframe>` 嵌入 Grafana 面板PlatformMonitor 组件),不经过 BFF。
### 3.4 proto 不直接消费
前端不调用 gRPCBFF 把 gRPC 聚合为 REST 暴露给前端。前端仅消费 `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 | admin-portal = **Remote** |
| 样式 | Tailwind CSS 3.4+ | 配合设计令牌三层模型(与 teacher-portal 共享) |
| 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复用 Shell | 全局 UI 状态 |
| 状态管理 L5 Form | react-hook-form + zodResolver | 表单状态 |
| 富文本 | — **不使用** | 管理端无富文本场景,不引入 Tiptap |
| 图表 | recharts | 管理仪表盘、用户活动统计 |
| i18n | next-intl | BFF/服务返回 i18n key + 参数,前端翻译 |
| A11y | eslint-plugin-jsx-a11yerror 级) | WCAG 2.2 AA |
| 字体 | Intersans/ Frauncesserif/ JetBrains Monomono | 复用 teacher-portal RootLayout 加载,不重复引入 |
> 技术栈与 teacher-portal **完全一致**差异仅在MF 角色Remote 而非 Shell、不使用 Tiptap、不消费 WebSocket/SSE 推送、数据范围 L3-L5。
## 5. 我的阶段归属
- **阶段**P6硬化阶段
- **当前状态**:❌ **全为待建**admin-portal 当前为空目录,无任何代码);📐 需设计(待全部业务服务稳定)
- **依赖上游阶段**P6依赖 teacher-portal Shell 已就绪 + iam 已实现用户/角色/权限/视口 CRUD + teacher-bff 已实现 `/admin/*` 复用)
## 6. 我需要对齐的黄金模板项(对照 classes 服务)
> 前端无 `@RequirePermission` 装饰器(后端概念),对齐项改造为前端等价物。
| 对齐项 | classes后端黄金模板 | admin-portal 前端等价 | 当前状态 |
| --------------------- | ------------------------------------- | ------------------------------------------------------------------------ | -------------------------- |
| 权限校验 | `@RequirePermission(Permissions.XXX)` | `usePermission().hasPermission("XXX")` Hook + `<RequirePermission>` 组件 | ❌ 待建(无现有代码) |
| 错误码前缀统一 | `CLASSES_*``IAM_*` | API 请求层根据 `error.code` 前缀路由 i18n | ❌ 待建 |
| logger | pino | 前端 console + SentryP6 | ❌ 待建 |
| metrics | prom-client `/metrics` | 前端 Web Vitals → Gateway 上报 | ❌ 待建 |
| tracer | OTel SDK | 前端 OTel browser SDKP6 | ❌ 待建 |
| /healthz + /readyz | `GET /healthz` `GET /readyz` | Next.js `/api/health` route + Dockerfile HEALTHCHECK | ❌ 待建 |
| 优雅关闭 | SIGTERM handler | Next.js 无长连接,无需 | ✅ N/A |
| 测试覆盖率 ≥ 80% | Vitest | Vitest + @testing-library/react + Playwright E2E | ❌ 待建0% |
| Dockerfile 多阶段构建 | builder + runtime | builder + runtime | ❌ 待建 |
| Zod 输入验证 | class-validator + Zod schema | react-hook-form + zodResolver | ❌ 待建 |
| GlobalErrorFilter | NestJS 全局异常过滤器 | React ErrorBoundary + API 请求层统一错误处理 | ❌ 待建 |
| 设计令牌三层 | — | primitive.css / semantic-light/dark.css / tailwind-theme.css复用 | ❌ 待建(复用 Shell 暴露) |
| A11y 工具集 | — | useA11yId / mergeA11yProps / describeInput / focus-trap复用 Shell | ❌ 待建(复用 Shell 暴露) |
---
## 附admin-portal 现状审计(对齐黄金模板)
### 审计表
| 维度 | 状态 | 说明 |
| ------------------------------------ | ------ | ------------------------------------------------------------------------- |
| 权限装饰器(前端等价 usePermission | ❌ | 待建,复用 Shell 暴露的 `usePermission` Hook + `<RequirePermission>` 组件 |
| 错误码前缀 | ❌ | 待建,复用 Shell 暴露的 ApiClient统一请求层 |
| logger | ❌ | 待建,复用 `packages/shared-ts/src/logger.ts` |
| metrics | ❌ | 待建Web Vitals 上报 `admin_portal_*` |
| tracer | ❌ | 待建OTel browser SDKP6 |
| /healthz | ❌ | 待建Next.js Route Handler |
| /readyz | ❌ | 待建Next.js Route Handler |
| 优雅关闭 | ✅ N/A | Next.js 无长连接 |
| 测试覆盖率 | ❌ | 待建,目标 ≥ 80% |
| Dockerfile 多阶段 | ❌ | 待建builder + runtime |
| Zod 输入验证 | ❌ | 待建react-hook-form + zodResolver |
| GlobalErrorFilterErrorBoundary | ❌ | 待建,复用 Shell 暴露的 ErrorBoundary |
| 设计令牌三层 | ❌ | 待建,复用 Shell 暴露的 `packages/ui-tokens/` |
| A11y 工具集 | ❌ | 待建,复用 Shell 暴露的 `packages/ui-components/` |
| Module Federation 配置 | ❌ | 待建next.config.js 配置 Remote 角色 |
| 5 层状态管理 | ❌ | 待建,复用 Shell 暴露的 nuqs/TanStack Query/Zustand |
| 共享组件库 | ❌ | 待建,复用 Shell 暴露 + admin 特有 4 个组件 |
| i18n | ❌ | 待建next-intl |
| API 请求层 | ❌ | 待建,复用 Shell 暴露的 ApiClient |
| ESLint flat config 自定义规则 | ❌ | 待建no-hardcoded-fonts / design-tokens 规则 |
### 现有文件清单
```
apps/admin-portal/ # 空目录(待建)
```
**说明**admin-portal 当前为空目录,所有维度均为 ❌ 待建状态。无现有文件、无现有代码、无现有违规点。P6 阶段从零开始搭建。
### L1 导航菜单(视口)
| 视口 key | 标签i18n key | 路由 | 权限 |
| -------------- | ------------------------ | --------------------- | ----------------------- |
| `dashboard` | `admin.nav.dashboard` | `/admin/dashboard` | `ADMIN_DASHBOARD_VIEW` |
| `users` | `admin.nav.users` | `/admin/users` | `IAM_USER_READ` |
| `roles` | `admin.nav.roles` | `/admin/roles` | `IAM_ROLE_READ` |
| `permissions` | `admin.nav.permissions` | `/admin/permissions` | `IAM_PERMISSION_READ` |
| `viewports` | `admin.nav.viewports` | `/admin/viewports` | `IAM_VIEWPORT_READ` |
| `organization` | `admin.nav.organization` | `/admin/organization` | `ORG_MANAGE` |
| `monitoring` | `admin.nav.monitoring` | `/admin/monitoring` | `ADMIN_MONITORING_VIEW` |
### L2 路由表
| 路由 | 页面 | 权限 |
| --------------------- | ---------- | ----------------------- |
| `/admin/dashboard` | 管理仪表盘 | `ADMIN_DASHBOARD_VIEW` |
| `/admin/users` | 用户管理 | `IAM_USER_READ` |
| `/admin/users/new` | 新建用户 | `IAM_USER_CREATE` |
| `/admin/users/:id` | 用户编辑 | `IAM_USER_UPDATE` |
| `/admin/roles` | 角色管理 | `IAM_ROLE_READ` |
| `/admin/permissions` | 权限管理 | `IAM_PERMISSION_READ` |
| `/admin/viewports` | 视口配置 | `IAM_VIEWPORT_READ` |
| `/admin/organization` | 组织管理 | `ORG_MANAGE` |
| `/admin/monitoring` | 平台监控 | `ADMIN_MONITORING_VIEW` |
### L3 组件级差异admin-portal 特有)
**复用 Shell 暴露的组件**AppShell、RequirePermission、ErrorBoundary、Loading、Empty、DataTable、Form、Chart、Toast、Modal、Button/Input/Select/Textarea、A11y 工具集
**admin-portal 特有组件**
| 组件 | 用途 | 来源 |
| ---------------------- | --------------------------------------- | ---- |
| `UserManagementTable` | 用户管理表格(列表/筛选/分页/批量操作) | 新建 |
| `RolePermissionMatrix` | 角色-权限矩阵编辑器checkbox 网格) | 新建 |
| `ViewportConfigEditor` | 视口配置编辑器(拖拽排序 + 权限绑定) | 新建 |
| `PlatformMonitor` | 平台监控Grafana iframe embed | 新建 |
**不使用的组件**RichTextEditorTiptap、ExamTaking、SSEViewer、ChildSwitcher 等(这些归 teacher-portal / student-portal / parent-portal
### L4 数据层差异
| 维度 | admin-portal | teacher-portal |
| ------------ | --------------------------------- | -------------------------------------- |
| 主要数据来源 | iam 直连 + teacher-bff 复用 | teacher-bff 聚合 + core-edu/content/ai |
| 缓存策略 | **5min 长缓存**(管理数据低频变) | 5min / 30s 混合(实时性差异) |
| 实时性要求 | 低(轮询 60s / 5min | 高WebSocket 推送 + SSE 流式) |
| 推送消费 | ❌ 不消费 | ✅ 消费 WebSocket + SSE |
---
**AI Agent**: ai07 (admin-portal remote)
**Branch**: docs/admin-portal-stage1-stage2-design-ai07
**Coordinator**: coord-ai

View File

@@ -0,0 +1,670 @@
# 模块架构设计文档 — admin-portal
> AIai07TS/React · 管理场景域前端 remote
> 阶段:阶段 2 交付物
> 日期2026-07-09
> 关联:[阶段 1 理解确认书](./01-understanding.md)、[004 架构影响地图](../../../docs/architecture/004_architecture_impact_map.md) §5.4、[pending-features P6](../../../docs/architecture/roadmap/pending-features.md)、[teacher-portal 阶段2](../../teacher-portal/docs/02-architecture-design.md)
> 状态:待 coord 交叉审查
---
## 1. 模块内部分层图简化版admin-portal Remote + Shell 引用 + Gateway
```mermaid
graph TB
subgraph Browser["浏览器(系统/校管理员)"]
URL[URL 路由 /admin/*]
end
subgraph Shell["teacher-portalShell 宿主)"]
AppShell[AppShell<br/>左栏导航 + 主内容区<br/>按 scope=admin 过滤视口]
RootLayout[RootLayout<br/>字体/令牌/i18n Provider<br/>TanStack QueryClientProvider<br/>Zustand StoreProvider]
Router[Next.js App Router<br/>动态加载 admin Remote]
SharedDeps["共享依赖暴露singleton<br/>react/react-dom/@tanstack/react-query/zustand/nuqs<br/>ui-components/ui-tokens/contracts/hooks/shared-ts"]
Rewrites["rewrites /api/v1/* → api-gateway"]
end
subgraph RemoteAdmin["admin-portalRemote 子应用)"]
AdminPages[管理场景页面<br/>dashboard/users/roles/permissions/viewports/organization/monitoring]
AdminComponents["admin 特有组件<br/>UserManagementTable/RolePermissionMatrix/ViewportConfigEditor/PlatformMonitor"]
AdminHooks["admin 业务 Hooks<br/>useUsers/useRoles/usePermissions/useViewports/useMonitoring"]
end
subgraph Shared["共享层packages/,由 Shell 暴露)"]
UITokens[ui-tokens<br/>三层设计令牌]
UIComponents[ui-components<br/>shadcn + A11y + ErrorBoundary + RequirePermission]
Contracts[contracts<br/>Permissions 常量 + 类型]
Hooks[hooks<br/>usePermission/useAuth/useViewports/useApi]
LibTS[shared-ts<br/>ApiClient/Logger/Tracer]
end
subgraph Gateway["api-gateway"]
GW[Gin 路由/鉴权/限流]
end
subgraph Backend["后端服务"]
IAM[iam<br/>用户/角色/权限/视口 CRUD]
BFF[teacher-bff<br/>/admin/* 聚合]
MSG[msg<br/>/notifications/*P5]
end
Browser --> URL
URL --> RootLayout
RootLayout --> AppShell
AppShell --> Router
Router -->|动态加载 /admin/*| RemoteAdmin
RemoteAdmin -->|消费 singleton| SharedDeps
SharedDeps --> UITokens
SharedDeps --> UIComponents
SharedDeps --> Contracts
SharedDeps --> Hooks
SharedDeps --> LibTS
AdminPages --> AdminComponents
AdminPages --> AdminHooks
AdminHooks -->|useApi → ApiClient| LibTS
AdminComponents --> UIComponents
AdminPages -->|fetch /api/v1/iam/*| Rewrites
AdminPages -->|fetch /api/v1/admin/*| Rewrites
AdminPages -->|fetch /api/v1/notifications/*| Rewrites
Rewrites --> GW
GW --> IAM
GW --> BFF
GW --> MSG
AppShell -->|fetch /api/v1/iam/effective-permissions| Rewrites
```
### 1.1 Remote 与 Shell 的职责边界
| 职责 | 归属 | 说明 |
| -------------------------------- | -------------------- | --------------------------------------------------------------------- |
| RootLayout字体/令牌/Provider | teacher-portal Shell | admin-portal 复用,不重复引入 |
| AppShell左栏 + 主内容区) | teacher-portal Shell | admin-portal 通过 `<AppShell scope="admin">` 渲染管理端视口 |
| 路由表 `/admin/*` | teacher-portal Shell | Shell 注册 `/admin/*` 路由组,动态 import admin Remote 模块 |
| 登录页 | teacher-portal Shell | 统一登录入口,按角色重定向到 `/admin/dashboard` |
| rewrites `/api/v1/*` | teacher-portal Shell | admin-portal 不实现 rewrites依赖 Shell |
| 管理场景页面 | admin-portal Remote | `/admin/*` 下的所有 page.tsx |
| 管理特有组件 | admin-portal Remote | UserManagementTable 等 4 个 |
| 管理业务 Hooks | admin-portal Remote | useUsers/useRoles/usePermissions/useViewports/useMonitoring |
| 共享组件库 | Shell 暴露 | AppShell/RequirePermission/ErrorBoundary/DataTable/Form/Chart 等 |
| 共享 Hooks | Shell 暴露 | usePermission/useAuth/useViewports/useApi/useA11yId |
| ApiClient | Shell 暴露 | `packages/shared-ts/src/api-client.ts`admin-portal 通过 useApi 获取 |
### 1.2 MF 配置admin-portal/next.config.jsRemote 角色)
```javascript
// admin-portal/next.config.jsRemote
const NextFederationPlugin = require("@module-federation/nextjs-mf");
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: "admin_app",
filename: "static/chunks/remoteEntry.js",
// Remote 不暴露任何模块给 ShellShell 通过 dynamic import 加载 admin 的 pages
exposes: {
"./pages": "./src/pages",
},
// Remote 反向引用 Shell 暴露的共享组件(可选,多数通过 singleton shared 解决)
remotes: {
teacher: `teacher_app@http://localhost:3000/_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 },
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;
},
// admin-portal 不实现 rewrites依赖 teacher-portal Shell 的 rewrites 代理 /api/v1/*
};
```
> **说明**
>
> - admin-portal 作为 Remote`name: 'admin_app'`,被 Shell 在 `remotes` 中引用为 `admin: 'admin_app@http://localhost:3003/...'`
> - admin-portal 不实现 `rewrites`,所有 `/api/v1/*` 请求由 Shell 的 rewrites 代理到 api-gateway
> - `shared` 全部声明为 `singleton: true`,确保与 Shell 共享同一实例(避免 React 多实例报错、Zustand store 分裂)
> - `transpilePackages` 列出本地 packages/* 软链依赖,确保 SWC 正确编译
## 2. 领域模型(前端视角)
前端不持有业务聚合根,仅持有"视图模型"ViewModel和"会话状态"。
### 2.1 会话状态 / 视口 / 权限(与 teacher-portal 共享)
**Session**、**Viewport**、**Permission** 三个模型与 teacher-portal 完全共享,定义和存储策略见 [teacher-portal 阶段2 §2.1-2.3](../../teacher-portal/docs/02-architecture-design.md#2-领域模型前端视角)。
admin-portal 作为 Remote通过 Shell 暴露的 `useAuth()` / `usePermission()` / `useViewports('admin')` Hook 消费这些模型,**不重复定义**。
### 2.2 管理场景视图模型admin-portal 特有)
```typescript
// 用户管理视图模型
interface UserViewModel {
id: string;
email: string;
name: string;
roles: RoleViewModel[]; // 用户拥有的角色
status: "active" | "disabled" | "locked";
dataScope: DataScope; // L0-L5
organizationId: string | null; // 所属组织
lastLoginAt: number | null;
createdAt: number;
updatedAt: number;
}
// 角色管理视图模型
interface RoleViewModel {
id: string;
name: string;
code: string; // 角色编码,如 'school_admin'
description: string;
permissions: PermissionViewModel[]; // 角色拥有的权限
userCount: number; // 该角色下的用户数(用于删除前校验)
dataScope: DataScope; // 角色默认数据范围
isSystem: boolean; // 系统预置角色不可删除
createdAt: number;
updatedAt: number;
}
// 权限管理视图模型
interface PermissionViewModel {
id: string;
code: string; // 'IAM_USER_READ' 等
name: string; // 显示名
description: string;
resource: string; // 资源类型 'user' | 'role' | 'permission' | 'viewport' | 'org' | 'monitoring'
action: string; // 'read' | 'create' | 'update' | 'delete' | 'manage'
isSystem: boolean; // 系统预置权限不可删除
}
// 视口配置视图模型(管理端可编辑)
interface ViewportConfigViewModel {
id: string;
key: string; // 'dashboard' | 'users' | ...
label: string; // i18n key
route: string; // '/admin/dashboard'
icon: string | null;
sortOrder: number;
requiredPermission: string | null;
scope: "teacher" | "student" | "parent" | "admin";
isVisible: boolean; // 是否在导航显示
}
// 平台监控视图模型
interface MonitoringMetricsViewModel {
timestamp: number;
activeUsers: number; // 当前在线用户数
totalUsers: number;
requestsPerMinute: number;
errorRate: number; // 0-1
avgResponseTimeMs: number;
serviceHealth: Array<{
serviceName: string;
status: "healthy" | "degraded" | "down";
latencyMs: number;
}>;
}
```
### 2.3 数据范围控制admin-portal 特有)
```typescript
// admin-portal 用户可见的数据范围由 dataScope 决定
// L3 校管理员:仅见本校用户/角色/组织
// L4 区教研员:仅见本区
// L5 系统管理员:全平台
interface AdminDataScopeFilter {
dataScope: DataScope; // L3-L5
schoolId?: string; // L3 时必填
districtId?: string; // L4 时必填
}
// 所有列表查询 API 自动注入此 filter由 ApiClient 拦截器添加)
```
## 3. 数据模型(前端缓存层)
admin-portal 无数据库,仅有 TanStack Query 缓存层。**管理数据低频变,采用 5min 长缓存**策略:
| 数据类型 | 存储 | TTL | 失效策略 |
| ----------------------- | ---------------------- | --------------------------- | -------------------------------------------------- |
| Sessiontoken + user | localStorage + Zustand | access 15min / refresh 7day | 401 自动 refreshrefresh 失败跳登录(复用 Shell |
| 权限列表 | TanStack Query cache | 5min | 角色变更主动 invalidate复用 Shell |
| 视口列表 | TanStack Query cache | 5min | 视口配置变更主动 invalidate |
| 用户列表 | TanStack Query cache | 5min | staleTime 5minmutation 后 invalidate |
| 角色列表 | TanStack Query cache | 5min | staleTime 5minmutation 后 invalidate |
| 权限列表(全量) | TanStack Query cache | 30min | staleTime 30min权限点极少变更 |
| 视口配置列表 | TanStack Query cache | 5min | staleTime 5minmutation 后 invalidate |
| 组织树 | TanStack Query cache | 5min | staleTime 5min |
| 平台监控指标 | TanStack Query cache | 60s | staleTime 60srefetchInterval 60s 轮询) |
| 用户活动统计 | TanStack Query cache | 5min | staleTime 5minrefetchInterval 5min 轮询) |
| URL 状态(分页/筛选) | nuqs | — | 永久(可分享) |
| 表单临时态 | react-hook-form | — | 卸载即销毁 |
> **缓存策略说明**:管理数据(用户/角色/权限/视口/组织低频变更5min 长缓存减少 BFF 压力监控指标需要相对实时60s 轮询权限点常量几乎不变30min 长缓存。所有 mutation 成功后主动 invalidate 对应 queryKey确保 UI 立即刷新。
## 4. API 设计(前端 → 后端)
前端不设计后端 API仅声明消费的端点。详见 [01-understanding.md §3.1](./01-understanding.md#31-消费的后端-api经-api-gateway-代理)。
### 4.1 统一 API 请求层(复用 Shell 暴露的 ApiClient
admin-portal **不重复实现** ApiClient通过 Shell 暴露的 `useApi()` Hook 获取 ApiClient 实例。ApiClient 定义见 [teacher-portal 阶段2 §4.1](../../teacher-portal/docs/02-architecture-design.md#41-统一-api-请求层libapits)。
```typescript
// admin-portal 业务 Hook 示例(消费 Shell 暴露的 useApi
import { useApi } from "@edu/hooks";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
export function useUsers(filter: AdminDataScopeFilter) {
const api = useApi();
return useQuery({
queryKey: ["admin", "users", filter],
queryFn: () => api.get<UserViewModel[]>("/api/v1/iam/users", filter),
staleTime: 5 * 60 * 1000, // 5min
});
}
export function useCreateUser() {
const api = useApi();
const queryClient = useQueryClient();
return useMutation({
mutationFn: (input: CreateUserInput) =>
api.post("/api/v1/iam/users", input),
onSuccess: () =>
queryClient.invalidateQueries({ queryKey: ["admin", "users"] }),
});
}
```
### 4.2 TanStack Query 约定
```typescript
// Query Key 命名:[scope, resource, ...args]
queryKey: ["admin", "users", { schoolId, status }];
queryKey: ["admin", "users", userId]; // 详情
queryKey: ["admin", "roles", { dataScope }];
queryKey: ["admin", "permissions"]; // 全量30min 缓存
queryKey: ["admin", "viewports", { scope }]; // 按 scope 过滤
queryKey: ["admin", "organization", { parentId }];
queryKey: ["admin", "monitoring", "metrics"]; // 60s 轮询
queryKey: ["admin", "stats", "active-sessions"]; // 5min 轮询
// Mutation 约定mutation 后主动 invalidate
const createUser = useMutation({
mutationFn: (input) => api.post("/api/v1/iam/users", input),
onSuccess: () =>
queryClient.invalidateQueries({ queryKey: ["admin", "users"] }),
onError: (e: ApiError) => toast.error(e.message),
});
// 轮询约定(监控指标)
const useMonitoringMetrics = () => {
const api = useApi();
return useQuery({
queryKey: ["admin", "monitoring", "metrics"],
queryFn: () =>
api.get<MonitoringMetricsViewModel>("/api/v1/admin/monitoring/metrics"),
staleTime: 60 * 1000, // 60s
refetchInterval: 60 * 1000, // 60s 轮询
});
};
```
## 5. 事件设计
**— N/A**
admin-portal **不消费** WebSocket 推送(不走 push-gateway**不消费** SSE 流式响应。管理端场景对实时性要求低,采用**轮询**策略:
| 场景 | 轮询方式 | 说明 |
| -------------- | ----------------------------------------------- | ---------------------------- |
| 平台监控指标 | TanStack Query `refetchInterval: 60s` | 实时性要求中等 |
| 用户活动统计 | TanStack Query `refetchInterval: 5min` | 实时性要求低 |
| 通知中心P5 | TanStack Query `refetchInterval: 30s` | 不走 push-gatewayHTTP 拉取 |
| 长期监控面板 | `<iframe>` 嵌入 GrafanaPlatformMonitor 组件) | 不经过 BFF直连 Grafana |
> 管理端不接入 push-gateway 的原因:管理员场景低频,推送基础设施成本不划算;轮询策略对 BFF 压力可控5min TTL 缓存命中率高)。
## 6. 横切关注点对齐清单
### 6.1 权限(前端等价)
| 路由 | requiredPermission |
| --------------------- | ----------------------- |
| `/admin/dashboard` | `ADMIN_DASHBOARD_VIEW` |
| `/admin/users` | `IAM_USER_READ` |
| `/admin/users/new` | `IAM_USER_CREATE` |
| `/admin/users/:id` | `IAM_USER_UPDATE` |
| `/admin/roles` | `IAM_ROLE_READ` |
| `/admin/permissions` | `IAM_PERMISSION_READ` |
| `/admin/viewports` | `IAM_VIEWPORT_READ` |
| `/admin/organization` | `ORG_MANAGE` |
| `/admin/monitoring` | `ADMIN_MONITORING_VIEW` |
> 完整权限点常量集中在 `packages/contracts/src/permissions.ts`coord 维护。L3 组件级视口用 `<RequirePermission perm="IAM_USER_CREATE"><Button>新建用户</Button></RequirePermission>`(复用 Shell 暴露组件)。
### 6.2 错误码清单(前端 i18n 路由)
| 前缀 | 来源服务 | i18n key 模式 |
| -------------- | ----------- | ------------------------ |
| `IAM_` | iam | `iam.error.{{code}}` |
| `BFF_TEACHER_` | teacher-bff | `bff.error.{{code}}` |
| `GW_` | api-gateway | `gateway.error.{{code}}` |
| `NETWORK_` | 前端网络层 | `network.error.{{code}}` |
> admin-portal 仅涉及 4 个错误码前缀iam / teacher-bff / gateway / 网络层),不消费 core-edu/content/msg/ai 服务,不涉及 `CORE_EDU_` / `CONTENT_` / `MSG_` / `AI_` 前缀。
### 6.3 Logger
```typescript
// 复用 packages/shared-ts/src/logger.tsShell 暴露)
interface Logger {
info(msg: string, meta?: Record<string, unknown>): void;
warn(msg: string, meta?: Record<string, unknown>): void;
error(msg: string, meta?: Record<string, unknown>): void;
}
// 实现:开发环境 console + 结构化;生产环境 → SentryP6admin-portal 本身就是 P6 阶段)
// 必含字段trace_id从响应头提取、user_id、scope='admin'、path
```
### 6.4 MetricsWeb Vitals
| 指标 | 类型 | 上报 |
| --------------------------- | ---- | --------------------------------------------------- |
| `admin_portal_lcp_seconds` | LCP | `next/web-vitals``POST /api/v1/admin/web-vitals` |
| `admin_portal_cls` | CLS | 同上 |
| `admin_portal_fid_seconds` | FID | 同上 |
| `admin_portal_ttfb_seconds` | TTFB | 同上 |
> admin-portal 本身就是 P6 阶段Web Vitals 在建站时即接入(与 teacher-portal P6 同步)。
### 6.5 TracerOTel browser SDKP6
```typescript
// 复用 packages/shared-ts/src/tracer.tsShell 暴露)
import { WebTracerProvider } from "@opentelemetry/sdk-trace-web";
// BatchSpanProcessor → OTLP exporter → collector → Tempo
// 自动埋点fetch、XMLHttpRequest、document load、user interaction
// admin-portal 通过 Shell 的 TracerProvider 注入,不重复初始化
```
### 6.6 健康检查
| 端点 | 用途 | 实现 |
| ----------------- | ---------------------- | --------------------------------------------------------------- |
| `GET /api/health` | Dockerfile HEALTHCHECK | Next.js Route Handler返回 `{ status: 'ok', ts: Date.now() }` |
| `GET /api/ready` | K8s readinessProbe | 检查 `process.env.TEACHER_PORTAL_URL` 可达(依赖 Shell 已启动) |
### 6.7 优雅关闭
Next.js 无长连接admin-portal 不消费 WebSocket/SSE无需特殊处理。
### 6.8 横切关注点对齐清单(汇总)
| 对齐项 | teacher-portal 实现 | admin-portal 对齐方式 |
| --------------------- | ---------------------------------------------- | ------------------------------------------------------- |
| 权限校验 | `usePermission()` + `<RequirePermission>` | 复用 Shell 暴露,权限点用 `IAM_*` / `ADMIN_*` / `ORG_*` |
| 错误码前缀统一 | ApiClient 按 `error.code` 前缀路由 i18n | 复用 Shell 暴露的 ApiClient前缀集缩减为 4 个 |
| logger | `packages/shared-ts/src/logger.ts` | 复用 Shell 暴露scope 字段固定为 `'admin'` |
| metrics | Web Vitals → `POST /api/v1/admin/web-vitals` | admin-portal 本身 P6建站即接入 |
| tracer | OTel browser SDKShell 初始化) | 复用 Shell 的 TracerProvider不重复初始化 |
| /healthz + /readyz | Next.js `/api/health` + Dockerfile HEALTHCHECK | admin-portal 独立实现 Route Handler |
| 优雅关闭 | N/ANext.js 无长连接) | N/A |
| 测试覆盖率 ≥ 80% | Vitest + @testing-library/react + Playwright | 同 teacher-portal |
| Dockerfile 多阶段构建 | builder + runtime | 同 teacher-portal |
| Zod 输入验证 | react-hook-form + zodResolver | 同 teacher-portal |
| GlobalErrorFilter | React ErrorBoundary + API 请求层 | 复用 Shell 暴露的 ErrorBoundary |
| 设计令牌三层 | `packages/ui-tokens/`Shell 暴露) | 复用 Shell 暴露,不重复引入 |
| A11y 工具集 | `packages/ui-components/`Shell 暴露) | 复用 Shell 暴露 |
## 7. 共享组件库(复用 Shell 暴露 + admin 特有)
### 7.1 复用 Shell 暴露的组件
| 组件 | 用途 | 来源 |
| ------------------------------------------ | ---------------------------------- | ------------------------------------------- |
| `AppShell` | 左侧栏 + 主内容区布局 | teacher-portal Shell 暴露 |
| `RequirePermission` | L3 组件级视口控制 | teacher-portal Shell 暴露 |
| `ErrorBoundary` | React 渲染异常兜底 | teacher-portal Shell 暴露 |
| `Loading` | 骨架屏Skeleton | teacher-portal Shell 暴露 |
| `Empty` | 空态(插画 + 文案 + CTA | teacher-portal Shell 暴露 |
| `Modal` / `Dialog` | 全局 Modal | teacher-portal Shell 暴露shadcn/ui |
| `Toast` | 全局 toast | teacher-portal Shell 暴露sonner |
| `Button` / `Input` / `Select` / `Textarea` | 基础表单 | teacher-portal Shell 暴露shadcn/ui |
| `DataTable` | 表格(排序/分页/筛选) | teacher-portal Shell 暴露TanStack Table |
| `Chart` | 图表封装recharts | teacher-portal Shell 暴露 |
| `A11y` 工具集 | useA11yId / mergeA11yProps 等 | teacher-portal Shell 暴露 |
| `Form` | react-hook-form + zodResolver 封装 | teacher-portal Shell 暴露 |
### 7.2 admin-portal 特有组件(新建)
| 组件 | 用途 | 实现要点 |
| ---------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `UserManagementTable` | 用户管理表格(列表/筛选/分页/批量操作) | 基于 Shell 的 `DataTable` 封装;列:邮箱/姓名/角色/状态/数据范围/最后登录;筛选:角色/状态/组织;批量:启用/禁用/分配角色 |
| `RolePermissionMatrix` | 角色-权限矩阵编辑器checkbox 网格) | 行=角色,列=权限(按 resource 分组);勾选触发 `PUT /api/v1/iam/roles/:id/permissions`;系统预置角色只读 |
| `ViewportConfigEditor` | 视口配置编辑器(拖拽排序 + 权限绑定) | 基于 `@dnd-kit` 拖拽排序每行key/label/route/requiredPermission/scope/isVisible保存触发 `PUT /api/v1/iam/viewports/:id` |
| `PlatformMonitor` | 平台监控Grafana iframe embed | `<iframe>` 嵌入 Grafana 面板(按 serviceName 切换备选recharts 渲染 `MonitoringMetricsViewModel` |
### 7.3 不使用的组件(明确排除)
| 组件 | 归属 | 排除原因 |
| ---------------- | -------------- | ------------------ |
| `RichTextEditor` | teacher-portal | 管理端无富文本场景 |
| `ExamTaking` | student-portal | 管理端无作答场景 |
| `SSEViewer` | teacher-portal | 管理端不消费 SSE |
| `ChildSwitcher` | parent-portal | 管理端无多子女切换 |
## 8. 共享 Hooks复用 Shell 暴露 + admin 特有)
### 8.1 复用 Shell 暴露的 Hooks
| Hook | 职责 |
| --------------------- | ---------------------------------------------------- |
| `useAuth()` | 会话状态user/token/refresh/login/logout |
| `usePermission()` | 权限查询hasPermission/hasAny/hasAll + dataScope |
| `useViewports(scope)` | 视口列表(按 scope 过滤admin-portal 传 `'admin'` |
| `useApi()` | ApiClient 实例(注入 token + 401 处理) |
| `useA11yId()` | 唯一 ARIA ID 生成 |
| `useAriaLive()` | aria-live 区域管理 |
| `useToast()` | 全局 toastZustand ui-store |
### 8.2 admin-portal 特有业务 Hooks新建
| Hook | 职责 |
| ---------------------------- | ------------------------------------------------ |
| `useUsers(filter)` | 用户列表查询(含筛选) |
| `useUser(userId)` | 用户详情 |
| `useCreateUser()` | 创建用户 mutation |
| `useUpdateUser()` | 更新用户 mutation |
| `useToggleUserStatus()` | 启用/禁用用户 mutation |
| `useRoles(filter)` | 角色列表查询 |
| `useRole(roleId)` | 角色详情(含权限列表) |
| `useCreateRole()` | 创建角色 mutation |
| `useUpdateRolePermissions()` | 更新角色权限 mutationRolePermissionMatrix 用) |
| `usePermissions()` | 全量权限列表30min 缓存) |
| `useViewportsConfig(scope)` | 视口配置列表(可编辑) |
| `useUpdateViewport()` | 更新视口配置 mutationViewportConfigEditor 用) |
| `useOrganization(parentId)` | 组织树查询 |
| `useMonitoringMetrics()` | 平台监控指标60s 轮询) |
| `useActiveSessionsStats()` | 用户活动统计5min 轮询) |
## 9. 设计令牌三层(复用 Shell 暴露)
admin-portal **不重复建立**设计令牌,通过 Shell 暴露的 `packages/ui-tokens/` 消费。三层令牌结构见 [teacher-portal 阶段2 §9](../../teacher-portal/docs/02-architecture-design.md#9-设计令牌三层packagesui-tokens待建ai07-维护)。
**强制规则**project_rules §3.10admin-portal 同样遵守):
- 禁止 `#hex` 字面量ESLint `no-restricted-syntax`
- 禁止 `'Inter'`/`'Fraunces'`/`'JetBrains Mono'` 字面量ESLint `design-tokens/no-hardcoded-fonts`
- 禁止 `font-size: Npx`(用 `var(--font-size-1~9)`
- 禁止 Tailwind 任意值 `w-[Npx]`(用 `--space-*` 或默认阶梯)
## 10. 与其他模块的交互点(契约清单)
| 方向 | 对方服务 | 协议 | 接口/事件 | 用途 | 阶段 |
| ------ | -------------------- | ------------------ | ------------------------------------------- | ---------------------------- | ---- |
| 调用 | api-gateway | HTTP/REST | `/api/v1/*` 代理(经 Shell rewrites | 全部业务请求 | P1+ |
| 被调用 | — | — | — | 前端不暴露接口给其他服务 | — |
| 消费 | iam | HTTP经 Gateway | `/iam/*`(含用户/角色/权限/视口 CRUD | 用户/角色/权限/视口管理 | P2+ |
| 消费 | teacher-bff | HTTP经 Gateway | `/admin/*` | 平台监控、统计聚合 | P6+ |
| 消费 | msg | HTTP经 Gateway | `/notifications/*` | 通知中心 | P5+ |
| 依赖 | coord 维护 | — | `packages/shared-proto` | TS 类型(仅 contracts 部分) | P1+ |
| 依赖 | coord 维护 | — | `packages/shared-ts`(待建) | ApiClient/Logger/通用工具 | P6+ |
| 依赖 | ai07 维护 | — | `packages/ui-tokens`(待建) | 三层设计令牌 | P6+ |
| 依赖 | ai07 维护 | — | `packages/ui-components`(待建) | shadcn + 共享组件 | P6+ |
| 依赖 | ai07 维护 | — | `packages/hooks`(待建) | usePermission/useAuth 等 | P6+ |
| 依赖 | coord 维护 | — | `packages/contracts`(待建) | Permissions 常量 + 类型 | P6+ |
| 依赖 | teacher-portal Shell | — | Shell 暴露的 AppShell + 共享依赖 + rewrites | 宿主环境 | P6+ |
> **proto 不直接消费**:前端不调用 gRPCBFF 把 gRPC 聚合为 REST 暴露给前端。前端仅消费 `packages/contracts/src/permissions.ts` 中的权限点常量TS 文件,非 proto 生成)。
## 11. 风险与假设
### 11.1 假设
1. **假设 coord 建立 `packages/shared-ts`、`packages/contracts`**:包含 ApiClient、Logger、Permissions 常量、通用类型。若 coord 未建立ai07 自行在 `apps/teacher-portal/src/shared/` 内实现(已在 teacher-portal 阶段2 计划中admin-portal 通过 MF shared 消费。
2. **假设 iam 提供用户/角色/权限/视口 CRUD 端点**`IAM_USER_READ/CREATE/UPDATE``IAM_ROLE_READ``IAM_PERMISSION_READ``IAM_VIEWPORT_READ` 及对应 REST 端点。当前已实现known-issues §2.3 iam
3. **假设 teacher-portal Shell 已就绪**AppShell + 共享依赖暴露 + MF 配置 + rewrites。admin-portal 是 P6 阶段,依赖 teacher-portal P2-P5 已完成。
4. **假设 Next.js 14+ Module Federation 2.0 稳定**`@module-federation/nextjs-mf` 在 Next.js App Router 下可用。若不稳定admin-portal 降级为独立部署(重复实现 AppShell
5. **假设 Grafana 可嵌入 iframe**PlatformMonitor 组件用 `<iframe>` 嵌入 Grafana 面板。若 Grafana 配置了 `X-Frame-Options: DENY`,需协调 SRE 放开 iframe 嵌入白名单,或降级为 recharts 渲染监控指标。
### 11.2 技术风险
| 风险 | 影响 | 缓解 |
| ----------------------- | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| Shell 未就绪阻塞 admin | admin-portal 是 P6 阶段,依赖 teacher-portal P2-P5 完成 | P6 启动前确认 Shell 已暴露 AppShell + 共享依赖;若 Shell 延迟admin-portal 先用 mock Shell 开发 |
| MF SSR 对齐复杂 | Remote 在 SSR 时需 Shell 提供上下文 | 优先 CSRSSR 仅用于首屏 dashboardMF 2.0 支持 SSR |
| 共享依赖版本漂移 | Remote 与 Shell 的 react/react-dom 版本不一致导致运行时错误 | MF `shared.singleton: true` + CI 检查版本对齐 |
| Token 刷新竞态 | 多请求同时 401 触发多次 refresh | 复用 Shell 的 ApiClient 全局单例 + refresh promise 复用 |
| 权限缓存陈旧 | 角色变更后前端 5min 内仍用旧权限 | iam 角色变更后管理员手动 invalidateadmin-portal 本身就是管理端,可主动触发 |
| 数据范围越权 | L3 校管理员看到 L5 系统管理员视角的数据 | 所有列表 API 由后端强制注入 dataScope filter前端 `AdminDataScopeFilter` 仅作 UI 提示 |
| Grafana iframe 嵌入失败 | PlatformMonitor 组件白屏 | 降级为 recharts 渲染 `MonitoringMetricsViewModel` |
| 轮询对 BFF 压力 | 60s 监控轮询 + 5min 统计轮询增加 BFF 负载 | 5min TTL 缓存命中率高;监控指标直连 Grafana iframe 不经过 BFF |
### 11.3 未决设计决策(需 coord 仲裁)
> 以下 4 项与 teacher-portal 阶段2 §11.3 相同admin-portal 跟随 teacher-portal 决策:
1. **packages 归属**`ui-tokens` / `ui-components` / `hooks` 是 ai07 维护还是 coord 维护建议ai07 维护前端专属coord 仅维护 `shared-ts` / `contracts`(跨语言/跨服务)。
2. **GraphQL vs REST**004 §11.3 提到 BFF GraphQL Yoga + DataLoader但当前 teacher-bff 实现为 REST。前端 API 请求层是否需要 GraphQL clienturql/apollo建议P2-P5 用 RESTP6 admin-portal 同样用 REST未来 BFF 切 GraphQL 再统一引入。
3. **i18n key 命名**`iam.error.IAM_INVALID_CREDENTIALS` 还是 `error.iam.invalid_credentials`?建议:`error.{{service}}.{{code_snake_case}}`,与错误码前缀对齐。
4. **MF 暴露粒度**Shell 暴露整个 AppShell 还是暴露更细粒度的组件Sidebar、Header、Content建议暴露 AppShell 整体 + 各 Remote 自行决定内部布局。
## 12. coord 交叉审查所需信息
### 12.1 端口矩阵
| 端 | dev 端口 | 生产端口 | 备注 |
| ------------ | -------- | -------- | -------------------- |
| admin-portal | 3003 | 3003 | Remote挂载到 Shell |
> 与 [full-stack-runbook](../../../docs/standards/full-stack-runbook.md) 端口矩阵对齐。Shellteacher-portal在 3000其余 Remotestudent-portal 3001 / parent-portal 3002 / admin-portal 3003。
### 12.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 |
### 12.3 依赖的后端契约(需对应 AI 确认)
| 契约 | 提供方 | 当前状态 |
| ------------------------------------------------------------------- | --------------------- | -------------------------------- |
| `GET/POST/PUT /iam/users``GET /iam/roles``GET /iam/permissions` | iam | ✅ 已实现 |
| `GET/PUT /iam/viewports``PUT /iam/viewports/:id` | iam | ✅ 已实现 |
| `PUT /iam/roles/:id/permissions` | iam | ⚠️ 待确认(角色-权限矩阵) |
| `GET /admin/dashboard``GET /admin/monitoring/metrics` | teacher-bff | ✅ 已实现(复用) |
| `GET /admin/stats/users``GET /admin/stats/active-sessions` | teacher-bff | ⚠️ 待确认 |
| `POST /admin/web-vitals` | teacher-bff | ⚠️ 待确认Web Vitals 上报端点) |
| `GET /notifications/*` | msg | 📐 待 P5 |
| Grafana 面板 iframe 嵌入 | SREinfra/grafana/ | ⚠️ 待确认 X-Frame-Options |
### 12.4 错误码前缀(前端 i18n 路由依赖)
前端不产生错误码仅消费。admin-portal 涉及的前缀(需各服务确认不重叠):
| 前缀 | 服务 | 状态 |
| -------------- | ----------- | ----------------------- |
| `IAM_` | iam | ✅ 已用 |
| `BFF_TEACHER_` | teacher-bff | ⚠️ 待确认 |
| `GW_` | api-gateway | ✅ 已用 |
| `NETWORK_` | 前端 | ai07 自有(复用 Shell |
### 12.5 不产生 Kafka 事件
admin-portal 不发布/消费 Kafka 事件,不消费 WebSocket/SSE 推送。所有数据通过 HTTP 轮询获取。
## 13. 实施路线ai07 自用P6 阶段)
### P6admin-portal 建站 + 硬化)
1. **建 `apps/admin-portal/` 骨架**Remote 角色)
- `next.config.js` 配置 MF Remote见 §1.2
- `package.json` 引入 `@module-federation/nextjs-mf` + 软链 `@edu/*` 共享包
- `tsconfig.json` 沿用 `tsconfig.base.json`
- `tailwind.config.js` 引入 `@edu/ui-tokens`
- `Dockerfile` 多阶段构建builder + runtime
2. **实现用户/角色/权限/视口/组织/监控管理页面**
- `/admin/dashboard` — 管理仪表盘recharts 渲染统计图表)
- `/admin/users` + `/admin/users/new` + `/admin/users/:id` — 用户管理UserManagementTable + Form
- `/admin/roles` — 角色管理RolePermissionMatrix
- `/admin/permissions` — 权限管理DataTable 只读列表)
- `/admin/viewports` — 视口配置ViewportConfigEditor
- `/admin/organization` — 组织管理(树形 + DataTable
- `/admin/monitoring` — 平台监控PlatformMonitor = Grafana iframe + recharts
3. **实现 admin 特有业务 Hooks**(见 §8.2
4. **接入 5 层状态管理**(复用 Shell 暴露的 nuqs/TanStack Query/Zustand/Zustand-UI/react-hook-form
5. **接入 i18n**next-intladmin 命名空间)
6. **接入权限校验**`usePermission()` + `<RequirePermission>`,按 §6.1 路由表)
7. **Web Vitals + OTel browser SDK 接入**(复用 Shell 的 TracerProviderscope='admin'
8. **A11y WCAG 2.2 AA 审计**eslint-plugin-jsx-a11y error 级 + 手动审计)
9. **性能优化**MF shared 单例验证、bundle 分析、5min 长缓存验证)
10. **补 Vitest 单测 + Playwright E2E**(覆盖率 ≥ 80%
11. **补 `/api/health` + `/api/ready` Route Handler + Dockerfile HEALTHCHECK**
### P6 验收标准
- [ ] 所有 9 个路由页面可访问,权限校验生效
- [ ] MF shared 单例验证通过react/react-dom/Zustand/TanStack Query 不重复实例化)
- [ ] Web Vitals 上报到 `POST /api/v1/admin/web-vitals`
- [ ] OTel browser SDK trace 上报到 collector
- [ ] A11y 审计 0 个 error 级违规
- [ ] 测试覆盖率 ≥ 80%
- [ ] `/api/health` + `/api/ready` 返回 200
- [ ] Dockerfile 多阶段构建,非 root 用户HEALTHCHECK 配置
---
**AI Agent**: ai07 (admin-portal remote)
**Branch**: docs/admin-portal-stage1-stage2-design-ai07
**Coordinator**: coord-ai

View File

@@ -0,0 +1,235 @@
# 模块理解确认书 — parent-portal
> AIai07TS/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 ai05/ai07、[pending-features P4](../../../docs/architecture/roadmap/pending-features.md)、[known-issues §2.12](../../../docs/troubleshooting/known-issues.md)、[teacher-portal 阶段1](../../teacher-portal/docs/01-understanding.md)、[teacher-portal 阶段2](../../teacher-portal/docs/02-architecture-design.md)
---
## 1. 我在架构中的位置
- **层级**L2 微前端层004 §3.1 六层架构中的前端层)
- **MF 角色****Remote 子应用**,挂载到 teacher-portal Shell
- **上游(谁调用我)**:浏览器(家长)
- **下游(同步)**api-gatewayREST经 Next.js `rewrites` 代理 `/api/v1/*`
- **下游推送P5**push-gatewayWebSocket
- **BFF 对接**parent-bff待 ai05 设计)
- **通信方式**HTTP/REST前端→Gateway+ WebSocket前端→push-gatewayP5
- **不直连**:前端不直连任何业务服务或 BFF 后端实例,全部经 api-gateway 代理
**说明**
- 通过 `next.config.js``rewrites``/api/v1/*` 代理到 `api-gateway`
- MF 架构下parent-portal 作为 Remote 子应用挂载到 teacher-portal Shell复用 Shell 的 AppShell、共享依赖、权限 Hook、API 请求层
- 不独立提供 RootLayout / 登录页 / 字体加载 / 令牌初始化,全部由 Shell 提供
- 与 teacher-portal 共享会话状态Session、视口Viewport、权限Permission三个核心模型
## 2. 我的限界上下文
### 2.1 我负责的聚合 / 实体(前端视图模型)
- 多子女切换、通知偏好、学情查看、成绩通知(家长场景域前端视图)
- 会话状态Session、视口Viewport、权限Permission—— 与 teacher-portal 共享
- 多子女状态ChildSwitcher—— 家长端特有
### 2.2 业务领域
- **D5 家长场景域**(前端场景域:家长场景域)
### 2.3 不负责
- 教师沟通(归 teacher-portal
- 学生作答(归 student-portal
- 用户/角色/权限 CRUD归 admin-portal
- 成绩录入(归 teacher-portal家长端仅查看
### 2.4 数据范围
- DataScope L0仅子女—— 家长只能查看自己子女的数据,不能跨家庭
## 3. 我与外部的契约
### 3.1 消费的后端 API经 api-gateway 代理)
| 路径前缀 | 下游 BFF/服务 | 关键端点 |
| ------------------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/api/v1/parent/*` | parent-bff | `GET /parent/viewports``GET /parent/children``POST /parent/switch-child``GET /parent/notifications``PUT /parent/notification-preferences` |
| `/api/v1/iam/*` | iam | `POST /iam/login``GET /iam/me``GET /iam/effective-permissions` |
| `/api/v1/notifications/*` | msg | 通知中心P5 |
> parent-bff 聚合 iam + core-edu + data-ana + msg对外暴露家长场景的统一接口子女关联、视口、学情聚合
### 3.2 统一响应契约
所有后端响应遵循 `ActionState` 结构(迁移指南 §7.5
```typescript
type ActionState<T> =
| { success: true; data: T }
| {
success: false;
error: { code: string; message: string; details?: unknown };
};
```
错误码前缀按服务名大写(如 `IAM_``CORE_EDU_``GRADES_``HOMEWORK_``BFF_PARENT_``GW_``NETWORK_`)。前端 API 请求层根据 `error.code` 前缀路由到对应的 i18n key。
### 3.3 推送契约P5
| 协议 | 场景 |
| ------------------------- | -------------------------------- |
| WebSocketpush-gateway | 子女成绩发布、教师沟通、学校通知 |
### 3.4 proto 不直接消费
前端不调用 gRPCBFF 把 gRPC 聚合为 REST 暴露给前端。前端仅消费 `packages/contracts/src/permissions.ts` 中的权限点常量TS 文件,非 proto 生成)。
## 4. 我的技术栈
| 维度 | 选型 | 说明 |
| --------------------------- | -------------------------------------------------------- | ------------------------------------------------------- |
| 框架 | Next.js 14+App Router | 与 teacher-portal 一致MF Remote 角色 |
| 语言 | TypeScript 5.5+strict | 沿用 tsconfig.base.json |
| 微前端 | Module Federation 2.0@module-federation/nextjs-mf | parent-portal = Remote |
| 样式 | Tailwind CSS 3.4+ | 配合设计令牌三层模型(与 teacher-portal 共享) |
| UI 组件库 | shadcn/ui迁移指南 §7.2 | 复用 Shell 暴露的 `packages/ui-components/` |
| 状态管理 L1 URL | nuqs | 可分享、可刷新状态 |
| 状态管理 L2 Server | TanStack Query v5 | 服务端数据缓存、重试、乐观更新 |
| 状态管理 L3 Client Business | Zustand slice | 客户端业务状态(含 ChildSwitcher 多子女状态) |
| 状态管理 L4 Global UI | Zustand ui-store + ModalRoot | 全局 UI 状态(复用 Shell 暴露) |
| 状态管理 L5 Form | react-hook-form + zodResolver | 表单状态(通知偏好设置) |
| 富文本 | N/A | 家长端不使用 Tiptap |
| 图表 | recharts | 子女学情、Dashboard |
| i18n | next-intl | BFF/服务返回 i18n key + 参数,前端翻译 |
| A11y | eslint-plugin-jsx-a11yerror 级) | WCAG 2.2 AA |
| 字体 | Intersans/ Frauncesserif/ JetBrains Monomono | 由 Shell RootLayout 加载parent-portal 仅消费 CSS 变量 |
## 5. 我的阶段归属
- **阶段**P4
- **当前状态**:📐 需设计(待 parent-bff + data-ana 就绪apps/parent-portal/ 目录为空(待建)
- **依赖上游阶段**P4parent-bff + data-ana
## 6. 我需要对齐的黄金模板项(对照 classes 服务)
> 前端无 `@RequirePermission` 装饰器后端概念对齐项改造为前端等价物。parent-portal 与 teacher-portal 共享前端等价物实现。
| 对齐项 | classes后端黄金模板 | parent-portal 前端等价 | 当前状态 |
| --------------------- | ------------------------------------- | ------------------------------------------------------------------------ | -------- |
| 权限校验 | `@RequirePermission(Permissions.XXX)` | `usePermission().hasPermission("XXX")` Hook + `<RequirePermission>` 组件 | ❌ 待建 |
| 错误码前缀统一 | `CLASSES_*``IAM_*` | API 请求层根据 `error.code` 前缀路由 i18n | ❌ 待建 |
| logger | pino | 前端 console + SentryP6 | ❌ 待建 |
| metrics | prom-client `/metrics` | 前端 Web Vitals → Gateway 上报 | ❌ 待建 |
| tracer | OTel SDK | 前端 OTel browser SDKP6 | ❌ 待建 |
| /healthz + /readyz | `GET /healthz` `GET /readyz` | Next.js `/api/health` route + Dockerfile HEALTHCHECK | ❌ 待建 |
| 优雅关闭 | SIGTERM handler | Next.js 无长连接,无需 | ✅ 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 请求层统一错误处理 | ❌ 待建 |
| 设计令牌三层 | — | primitive.css / semantic-light/dark.css / tailwind-theme.css | ❌ 待建 |
| A11y 工具集 | — | useA11yId / mergeA11yProps / describeInput / focus-trap | ❌ 待建 |
---
## 附parent-portal 现状审计(对齐黄金模板)
### 审计表
| 维度 | 状态 | 说明 |
| ------------------------------------ | ------ | --------------------------------------------- |
| 权限装饰器(前端等价 usePermission | ❌ | 待建,复用 Shell 暴露的 usePermission Hook |
| 错误码前缀 | ❌ | 待建,复用 Shell 暴露的 ApiClient |
| logger | ❌ | 待建,复用 packages/shared-ts/src/logger.ts |
| metrics | ❌ | 待建Web Vitals 上报 |
| tracer | ❌ | 待建OTel browser SDKP6 |
| /healthz | ❌ | 待建Next.js Route Handler |
| /readyz | ❌ | 待建 |
| 优雅关闭 | ✅ N/A | Next.js 无长连接 |
| 测试覆盖率 | ❌ | 0%,无测试文件(待建) |
| Dockerfile 多阶段 | ❌ | 待建builder + runtime |
| Zod 输入验证 | ❌ | 待建react-hook-form + zodResolver |
| GlobalErrorFilterErrorBoundary | ❌ | 待建,复用 Shell 暴露的 ErrorBoundary |
| 设计令牌三层 | ❌ | 待建,复用 packages/ui-tokens |
| A11y 工具集 | ❌ | 待建,复用 Shell 暴露的 A11y 工具集 |
| Module Federation 配置 | ❌ | 待建Remote 角色) |
| 5 层状态管理 | ❌ | 待建(含 ChildSwitcher 多子女 Zustand slice |
| 共享组件库 | ❌ | 待建(复用 Shell 暴露 + 新增 ChildSwitcher |
| i18n | ❌ | 待建next-intl |
| API 请求层 | ❌ | 待建,复用 Shell 暴露的 ApiClient |
| ESLint flat config 自定义规则 | ❌ | 待建,复用 teacher-portal 配置 |
### 现有文件清单
```
apps/parent-portal/
└─ (空目录,待建)
```
> parent-portal 当前为空目录,所有维度均为 ❌ 待建状态。基础设施Shell 暴露的 AppShell、共享依赖、权限 Hook、API 请求层、设计令牌、UI 组件、A11y 工具集)由 teacher-portal Shell 在 P2 收尾时建立parent-portal 在 P4 启动时直接复用。
---
## 7. L1 导航菜单(视口)
家长端 L1 导航菜单由 parent-bff 通过 `GET /parent/viewports` 返回AppShell 按 `scope: 'parent'` 过滤渲染:
- Dashboard家长仪表盘
- 子女切换
- 成绩查看
- 作业查看
- 通知中心P5
- 通知偏好设置
## 8. L2 路由表
| 路由 | 页面 | 权限 |
| ----------------------- | -------------- | --------------------------- |
| `/parent/dashboard` | 家长仪表盘 | `PARENT_DASHBOARD_VIEW` |
| `/parent/children` | 子女列表 | `PARENT_CHILDREN_VIEW` |
| `/parent/grades` | 子女成绩 | `GRADES_READ_CHILD` |
| `/parent/homework` | 子女作业 | `HOMEWORK_READ_CHILD` |
| `/parent/notifications` | 通知中心P5 | `NOTIFICATION_READ_OWN` |
| `/parent/preferences` | 通知偏好 | `PARENT_PREFERENCES_UPDATE` |
> L3 组件级视口用 `<RequirePermission perm="PARENT_PREFERENCES_UPDATE"><Button>保存</Button></RequirePermission>`。
## 9. L3 组件级差异parent-portal 特有)
### 9.1 复用 Shell 暴露的组件
- AppShell左栏导航 + 主内容区)
- RequirePermissionL3 组件级视口控制)
- ErrorBoundaryReact 渲染异常兜底)
- Loading骨架屏
- Empty空态
- DataTable表格
- Formreact-hook-form + zodResolver 封装)
- Chartrecharts 封装)
### 9.2 parent-portal 特有组件
| 组件 | 用途 | 来源 |
| --------------- | ---------------------------------------------------------- | ---- |
| `ChildSwitcher` | 多子女切换组件(顶部 Tab切换后 invalidate 子女相关查询 | 新建 |
### 9.3 不使用的组件
- RichTextEditorTiptap—— 家长端不编辑富文本
- ExamTaking —— 学生考试专用
- SSEViewer —— AI 流式响应查看器(教师端专用)
- UserManagementTable —— 管理员端专用
## 10. L4 数据层差异
| 维度 | teacher-portal | parent-portal |
| ---------- | -------------- | -------------------------------------------------------------- |
| 主要数据源 | teacher-bff | parent-bff聚合 iam + core-edu + data-ana + msg |
| 缓存策略 | 5-30s 短缓存 | 5-30s 短缓存,**子女切换 invalidate** 子女相关查询 |
| 多子女状态 | N/A | ChildSwitcher Zustand slice当前子女 ID 持久化到 localStorage |
---
**AI Agent**: ai07 (parent-portal remote)
**Branch**: docs/parent-portal-stage1-stage2-design-ai07

View File

@@ -0,0 +1,546 @@
# 模块架构设计文档 — parent-portal
> AIai07TS/React · 家长场景域前端 remote
> 阶段:阶段 2 交付物
> 日期2026-07-09
> 关联:[阶段 1 理解确认书](./01-understanding.md)、[004 架构影响地图](../../../docs/architecture/004_architecture_impact_map.md) §5.4、[pending-features P4](../../../docs/architecture/roadmap/pending-features.md)、[teacher-portal 阶段2](../../teacher-portal/docs/02-architecture-design.md)
> 状态:待 coord 交叉审查
---
## 1. 模块内部分层图简化版Remote 角色)
```mermaid
graph TB
subgraph Browser["浏览器"]
URL[URL 路由]
end
subgraph Shell["teacher-portalShell 宿主)"]
AppShell[AppShell<br/>左栏导航 + 主内容区]
RootLayout[RootLayout<br/>字体/令牌/i18n Provider]
Router[Next.js App Router]
SharedDeps["共享依赖暴露<br/>react/react-dom/@tanstack/react-query/zustand/nuqs<br/>ui-components/ui-tokens/contracts/hooks/shared-ts"]
end
subgraph RemoteParent["parent-portalRemote 模块)"]
ParentPages[家长场景页面<br/>dashboard/children/grades/homework/notifications/preferences]
ChildSwitcher["ChildSwitcher<br/>多子女切换 + Zustand slice"]
end
subgraph Shared["共享层packages/"]
UITokens[ui-tokens<br/>三层设计令牌]
UIComponents[ui-components<br/>shadcn + A11y + ErrorBoundary]
Contracts[contracts<br/>Permissions 常量 + 类型]
Hooks[hooks<br/>usePermission/useAuth/useA11y]
LibTS[shared-ts<br/>ApiClient/Logger/通用工具]
end
subgraph Gateway["api-gateway"]
GW[Gin 路由/鉴权/限流]
end
subgraph PushGW["push-gatewayP5"]
WS[WebSocket Server]
end
Browser --> URL
URL --> RootLayout
RootLayout --> AppShell
AppShell --> Router
Router -->|动态加载 /parent/*| RemoteParent
RemoteParent --> SharedDeps
Shell --> UITokens
Shell --> UIComponents
Shell --> Contracts
Shell --> Hooks
RemoteParent --> UITokens
RemoteParent --> UIComponents
RemoteParent --> Contracts
RemoteParent --> Hooks
RemoteParent --> LibTS
AppShell -->|fetch /api/v1/iam/effective-permissions| Hooks
Hooks -->|透传 token| GW
RemoteParent -->|fetch /api/v1/parent/*| GW
RemoteParent -->|fetch /api/v1/iam/*| GW
RemoteParent -->|fetch /api/v1/notifications/*| GW
RemoteParent -.P5 WebSocket.-> WS
```
### 1.1 MF 拓扑选型
| 方案 | 选否 | 理由 |
| ----------------------------------------------------- | ---- | --------------------------------------------------------------------------------------------- |
| 4 端独立部署 + 独立域名 + 各自 Shell | ❌ | 4 套 Shell 重复,登录态/权限/组件库要重复实现 |
| 单 Shell + 4 Remote**采用**teacher-portal Shell | ✅ | teacher-portal 作为 Shell 宿主parent-portal 作为 Remote 动态加载,复用 Shell 的全部基础设施 |
| 单一 Next.js 应用 + 4 路由组 | ❌ | 违反"微前端独立部署"目标ADR-012 |
**Remote 职责**parent-portal
- 家长场景页面dashboard / children / grades / homework / notifications / preferences
- ChildSwitcher 多子女切换组件 + Zustand sliceL3 客户端业务状态)
- 不提供 RootLayout / 登录页 / 字体加载 / 令牌初始化(由 Shell 提供)
- 路由前缀 `/parent/*`
### 1.2 MF 配置parent-portal/next.config.jsRemote 角色)
```javascript
// parent-portal/next.config.jsRemote
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,
webpack(config, { isServer }) {
config.plugins.push(
new NextFederationPlugin({
name: "parent_app",
filename: "static/chunks/remoteEntry.js",
remotes: remotes(isServer),
exposes: {
"./pages": "./src/pages",
"./ChildSwitcher": "./src/components/ChildSwitcher",
},
shared: {
react: { singleton: true, requiredVersion: "^18.3.0" },
"react-dom": { singleton: true, requiredVersion: "^18.3.0" },
"@tanstack/react-query": { singleton: true },
zustand: { singleton: true },
nuqs: { 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*`,
},
];
},
};
```
> Shell 端配置对称:`teacher-portal/next.config.js` 的 `remotes.parent = parent_app@http://localhost:3002/_next/static/${isServer ? "ssr" : "chunks"}/remoteEntry.js`(详见 [teacher-portal 阶段2 §1.2](../../teacher-portal/docs/02-architecture-design.md#12-mf-配置teacher-portalnextconfigjs))。
## 2. 领域模型(前端视角)
前端不持有业务聚合根,仅持有"视图模型"ViewModel和"会话状态"。
### 2.1 会话状态Session / 视口Viewport / 权限Permission
**与 teacher-portal 共享**,定义详见 [teacher-portal 阶段2 §2.1-2.3](../../teacher-portal/docs/02-architecture-design.md#21-会话状态session)。parent-portal 作为 Remote 复用 Shell 暴露的 Session/Viewport/Permission 类型与 Zustand slice
- `Session`Zustand sessionSliceL3+ localStorage 持久化 + TanStack Query 缓存 `['session']`L2
- `ViewportItem`:来源 `GET /api/v1/parent/viewports`parent-bff 聚合 iam 视口配置AppShell 按 `scope: 'parent'` 过滤渲染
- `PermissionState`:来源 `GET /api/v1/iam/effective-permissions`,前端 TanStack Query 缓存 5min
### 2.2 多子女状态ChildSwitcher家长端特有
```typescript
interface ChildSwitcherState {
children: ChildInfo[]; // 当前家长关联的所有子女
currentChildId: string | null; // 当前选中的子女 ID
isLoading: boolean; // 加载状态
error: string | null; // 错误信息
switchChild: (childId: string) => Promise<void>; // 切换子女
refreshChildren: () => Promise<void>; // 刷新子女列表
}
interface ChildInfo {
id: string; // 子女 user_id
name: string; // 子女姓名
avatar?: string; // 头像 URL
grade: string; // 年级i18n key
schoolName: string; // 学校名称
classId: string; // 班级 ID
}
```
存储Zustand childSwitcherSliceL3+ localStorage 持久化 `currentChildId`(刷新恢复)+ TanStack Query 缓存 `['parent', 'children']`L2
**切换行为**:调用 `POST /api/v1/parent/switch-child` 成功后invalidate 所有 `['parent', 'children', currentChildId]` 前缀的查询(成绩、作业、学情等子女维度数据)。
## 3. 数据模型(前端)
前端无数据库,仅有缓存层:
| 数据类型 | 存储 | TTL | 失效策略 |
| ---------------------------- | ----------------------------------------- | --------------------------- | ------------------------------------------ |
| Sessiontoken + user | localStorage + ZustandShell 共享) | access 15min / refresh 7day | 401 自动 refreshrefresh 失败跳登录 |
| 权限列表 | TanStack Query cacheShell 共享) | 5min | 角色变更事件 invalidate |
| 视口列表 | TanStack Query cache | 5min | 同上 |
| 子女列表 | TanStack Query cache + Zustand slice | 5min | staleTime 5min切换子女不 invalidate 列表 |
| 当前选中子女 ID | localStorage + Zustand childSwitcherSlice | — | 永久(刷新恢复) |
| 子女成绩列表 | TanStack Query cache | 30s | **子女切换 invalidate** + 30s staleTime |
| 子女作业列表 | TanStack Query cache | 30s | **子女切换 invalidate** + 30s staleTime |
| 子女学情宽表 | TanStack Query cache | 30s | **子女切换 invalidate** + 30s staleTime |
| 通知偏好 | TanStack Query cache | 5min | mutation 后 invalidate |
| 通知列表P5 | TanStack Query cache | 30s | WebSocket 推送 invalidate |
| URL 状态(分页/筛选/子女ID | nuqs | — | 永久(可分享) |
| 表单临时态(通知偏好设置) | react-hook-form | — | 卸载即销毁 |
### 3.1 子女切换 invalidate 策略
```typescript
// packages/hooks/src/useChildSwitcher.tsai07 维护)
const useChildSwitcher = () => {
const queryClient = useQueryClient();
const switchChild = async (childId: string) => {
await api.post("/api/v1/parent/switch-child", { childId });
// 更新 Zustand slice
useChildSwitcherStore.getState().setCurrentChildId(childId);
// invalidate 所有子女维度数据
queryClient.invalidateQueries({ queryKey: ["parent", "children"] }); // 排除列表本身
queryClient.invalidateQueries({ queryKey: ["parent", "grades"] });
queryClient.invalidateQueries({ queryKey: ["parent", "homework"] });
queryClient.invalidateQueries({ queryKey: ["parent", "analytics"] });
};
return { switchChild, ...useChildSwitcherStore() };
};
```
## 4. API 设计(前端 → 后端)
前端不设计后端 API仅声明消费的端点。详见 [01-understanding.md §3.1](./01-understanding.md#31-消费的后端-api经-api-gateway-代理)。
### 4.1 统一 API 请求层
**复用 Shell 暴露的 ApiClient**,定义详见 [teacher-portal 阶段2 §4.1](../../teacher-portal/docs/02-architecture-design.md#41-统一-api-请求层lib-apits)。parent-portal 通过 MF `shared` 单例获取 ApiClient 实例:
```typescript
// parent-portal/src/lib/api.ts
import { useApi } from "teacher/hooks"; // 从 Shell 暴露的 hooks 包获取
export const useParentApi = () => {
const api = useApi(); // Shell 暴露的 ApiClient 单例
return {
getViewports: () => api.get("/api/v1/parent/viewports"),
getChildren: () => api.get("/api/v1/parent/children"),
switchChild: (childId: string) =>
api.post("/api/v1/parent/switch-child", { childId }),
getNotifications: (params?: Record<string, string>) =>
api.get("/api/v1/parent/notifications", params),
updateNotificationPreferences: (prefs: unknown) =>
api.put("/api/v1/parent/notification-preferences", prefs),
getChildGrades: (childId: string) =>
api.get(`/api/v1/parent/children/${childId}/grades`),
getChildHomework: (childId: string) =>
api.get(`/api/v1/parent/children/${childId}/homework`),
getChildAnalytics: (childId: string) =>
api.get(`/api/v1/parent/children/${childId}/analytics`),
};
};
```
### 4.2 TanStack Query 约定
```typescript
// Query Key 命名:[scope, resource, ...args]
queryKey: ["parent", "children"]; // 子女列表
queryKey: ["parent", "grades", currentChildId]; // 子女成绩(含子女 ID 维度)
queryKey: ["parent", "homework", currentChildId]; // 子女作业
queryKey: ["parent", "analytics", currentChildId]; // 子女学情
queryKey: ["parent", "notifications"]; // 通知列表
queryKey: ["parent", "preferences"]; // 通知偏好
queryKey: ["session", "viewports", "parent"]; // 家长端视口
// Mutation 约定
const switchChildMutation = useMutation({
mutationFn: (childId: string) =>
api.post("/api/v1/parent/switch-child", { childId }),
onSuccess: (_, childId) => {
useChildSwitcherStore.getState().setCurrentChildId(childId);
queryClient.invalidateQueries({ queryKey: ["parent", "grades"] });
queryClient.invalidateQueries({ queryKey: ["parent", "homework"] });
queryClient.invalidateQueries({ queryKey: ["parent", "analytics"] });
},
});
const updatePreferencesMutation = useMutation({
mutationFn: (prefs) =>
api.put("/api/v1/parent/notification-preferences", prefs),
onSuccess: () =>
queryClient.invalidateQueries({ queryKey: ["parent", "preferences"] }),
onError: (e: ApiError) => toast.error(e.message),
});
```
## 5. 事件设计
前端不发布 Kafka 事件,仅消费 WebSocket 推送P5
### 5.1 WebSocket 推送P5
| 事件 | 触发 | parent-portal 前端动作 |
| ----------------------- | ---------------- | ------------------------------- |
| `NotificationRequested` | msg 服务投递 | toast 提示 + 通知中心未读数 +1 |
| `GradeRecorded` | 教师录入子女成绩 | toast + 子女成绩列表 invalidate |
| `SchoolAnnouncement` | 学校通知 | toast + dashboard invalidate |
> WebSocket 连接由 Shell 建立统一连接管理parent-portal 通过 Zustand ui-store 订阅事件流。事件路由按 `event.type` 分发到对应 Remote 的 handler。
## 6. 横切关注点对齐清单
### 6.1 权限(前端等价)
| 路由 | requiredPermission |
| ----------------------- | --------------------------- |
| `/parent/dashboard` | `PARENT_DASHBOARD_VIEW` |
| `/parent/children` | `PARENT_CHILDREN_VIEW` |
| `/parent/grades` | `GRADES_READ_CHILD` |
| `/parent/homework` | `HOMEWORK_READ_CHILD` |
| `/parent/notifications` | `NOTIFICATION_READ_OWN` |
| `/parent/preferences` | `PARENT_PREFERENCES_UPDATE` |
> 完整权限点常量集中在 `packages/contracts/src/permissions.ts`待建立coord 负责。L3 组件级视口用 `<RequirePermission perm="PARENT_PREFERENCES_UPDATE"><Button>保存</Button></RequirePermission>`。
### 6.2 错误码清单(前端 i18n 路由)
| 前缀 | 来源服务 | i18n key 模式 |
| ------------- | ----------- | ------------------------- |
| `IAM_` | iam | `iam.error.{{code}}` |
| `CORE_EDU_` | core-edu | `coreEdu.error.{{code}}` |
| `GRADES_` | core-edu | `grades.error.{{code}}` |
| `HOMEWORK_` | core-edu | `homework.error.{{code}}` |
| `BFF_PARENT_` | parent-bff | `bff.error.{{code}}` |
| `GW_` | api-gateway | `gateway.error.{{code}}` |
| `NETWORK_` | 前端网络层 | `network.error.{{code}}` |
### 6.3 Logger
```typescript
// 复用 packages/shared-ts/src/logger.ts与 teacher-portal 共享)
// 实现:开发环境 console + 结构化;生产环境 → SentryP6
// 必含字段trace_id从响应头提取、user_id、scope=parent、path
```
### 6.4 MetricsWeb Vitals
| 指标 | 类型 | 上报 |
| ---------------------------- | ---- | --------------------------------------------------- |
| `parent_portal_lcp_seconds` | LCP | `next/web-vitals``POST /api/v1/admin/web-vitals` |
| `parent_portal_cls` | CLS | 同上 |
| `parent_portal_fid_seconds` | FID | 同上 |
| `parent_portal_ttfb_seconds` | TTFB | 同上 |
P6 接入P4-P5 暂缓。
### 6.5 TracerOTel browser SDKP6
```typescript
// 复用 packages/shared-ts/src/tracer.ts与 teacher-portal 共享)
import { WebTracerProvider } from "@opentelemetry/sdk-trace-web";
// BatchSpanProcessor → OTLP exporter → collector → Tempo
// 自动埋点fetch、XMLHttpRequest、document load、user interaction
// parent-portal 通过 MF shared 单例复用 Shell 的 TracerProvider
```
### 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` 可达 + 内存 < 阈值 |
### 6.7 优雅关闭
Next.js 无长连接(除 SSE/WS无需特殊处理。WS 在 P5 由 push-gateway 管理,前端断线自动重连。
## 7. 共享组件库(复用 Shell 暴露 + parent 特有)
### 7.1 复用 Shell 暴露的组件
| 组件 | 用途 | 来源 |
| ------------------------------------------ | ---------------------------------- | ------------------------- |
| `AppShell` | 左侧栏 + 主内容区布局 | teacher-portal Shell 暴露 |
| `RequirePermission` | L3 组件级视口控制 | teacher-portal Shell 暴露 |
| `ErrorBoundary` | React 渲染异常兜底fallback UI | teacher-portal Shell 暴露 |
| `Loading` | 骨架屏Skeleton | teacher-portal Shell 暴露 |
| `Empty` | 空态(插画 + 文案 + CTA | teacher-portal Shell 暴露 |
| `Modal` / `Dialog` | 全局 Modal | teacher-portal Shell 暴露 |
| `Toast` | 全局 toast | teacher-portal Shell 暴露 |
| `Button` / `Input` / `Select` / `Textarea` | 基础表单 | teacher-portal Shell 暴露 |
| `DataTable` | 表格(排序/分页/筛选) | teacher-portal Shell 暴露 |
| `Chart` | 图表封装recharts | teacher-portal Shell 暴露 |
| `Form` | react-hook-form + zodResolver 封装 | teacher-portal Shell 暴露 |
| `A11y` 工具集 | useA11yId / mergeA11yProps 等 | teacher-portal Shell 暴露 |
### 7.2 parent-portal 特有组件
| 组件 | 用途 | 来源 |
| --------------- | ---------------------------------------------------------- | ---- |
| `ChildSwitcher` | 多子女切换组件(顶部 Tab切换后 invalidate 子女相关查询 | 新建 |
> `ChildSwitcher` 通过 MF `exposes` 暴露给 Shell但实际只在 parent-portal 路由内使用。组件内部封装:子女列表查询 + 切换 mutation + Zustand slice 同步 + invalidate 逻辑。
## 8. 共享 Hooks复用 Shell 暴露 + parent 特有)
### 8.1 复用 Shell 暴露的 Hooks
| Hook | 职责 |
| --------------------- | --------------------------------------------------- |
| `useAuth()` | 会话状态user/token/refresh/login/logout |
| `usePermission()` | 权限查询hasPermission/hasAny/hasAll + dataScope |
| `useViewports(scope)` | 视口列表(按 scope 过滤) |
| `useApi()` | ApiClient 实例(注入 token + 401 处理) |
| `useA11yId()` | 唯一 ARIA ID 生成 |
| `useAriaLive()` | aria-live 区域管理 |
| `useToast()` | 全局 toastZustand ui-store |
### 8.2 parent-portal 特有 Hook
| Hook | 职责 |
| -------------------- | --------------------------------------------------------- |
| `useChildSwitcher()` | 多子女切换children/currentChildId/switchChild/refresh |
## 9. 设计令牌三层(复用 packages/ui-tokens
**与 teacher-portal 共享**,定义详见 [teacher-portal 阶段2 §9](../../teacher-portal/docs/02-architecture-design.md#9-设计令牌三层packagesui-tokens待建立ai07-维护)。parent-portal 通过 MF `shared` 单例复用 `packages/ui-tokens`,不在本应用内重复定义令牌。
**强制规则**project_rules §3.10
- 禁止 `#hex` 字面量ESLint `no-restricted-syntax`
- 禁止 `'Inter'`/`'Fraunces'`/`'JetBrains Mono'` 字面量ESLint `design-tokens/no-hardcoded-fonts`
- 禁止 `font-size: Npx`(用 `var(--font-size-1~9)`
- 禁止 Tailwind 任意值 `w-[Npx]`(用 `--space-*` 或默认阶梯)
## 10. 与其他模块的交互点(契约清单)
| 方向 | 对方服务 | 协议 | 接口/事件 | 用途 | 阶段 |
| ------ | ------------ | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- | ---- |
| 调用 | api-gateway | HTTP/REST | `/api/v1/*` 代理 | 全部业务请求 | P1+ |
| 调用 | push-gateway | WebSocket | `ws://push-gateway/ws` | 实时推送 | P5 |
| 被调用 | — | — | — | 前端不暴露接口给其他服务 | — |
| 消费 | parent-bff | HTTP经 Gateway | `GET /parent/viewports``GET /parent/children``POST /parent/switch-child``GET /parent/notifications``PUT /parent/notification-preferences` | 家长场景聚合 | P4+ |
| 消费 | iam | HTTP经 Gateway | `/iam/*` | 登录/权限/视口 | P2+ |
| 消费 | core-edu | HTTP经 Gateway | `/grades/*` `/homework/*` | 教学核心(子女视角) | 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/通用工具 | P4+ |
| 依赖 | ai07 维护 | — | `packages/ui-tokens`(待建) | 三层设计令牌 | P4+ |
| 依赖 | ai07 维护 | — | `packages/ui-components`(待建) | shadcn + 共享组件 | P4+ |
| 依赖 | ai07 维护 | — | `packages/hooks`(待建) | usePermission/useAuth 等 | P4+ |
| 依赖 | coord 维护 | — | `packages/contracts`(待建) | Permissions 常量 + 类型 | P4+ |
> **proto 不直接消费**:前端不调用 gRPCBFF 把 gRPC 聚合为 REST 暴露给前端。前端仅消费 `packages/contracts/src/permissions.ts` 中的权限点常量TS 文件,非 proto 生成)。
## 11. 风险与假设
### 11.1 假设
1. **假设 coord 建立 `packages/shared-ts`、`packages/contracts`**:包含 ApiClient、Logger、Permissions 常量、通用类型。若 coord 未建立ai07 自行在 `apps/parent-portal/src/shared/` 内实现,后续提取到 packages。
2. **假设 ai05 parent-bff 提供 `GET /parent/viewports`、`GET /parent/children`、`POST /parent/switch-child`、`GET /parent/notifications`、`PUT /parent/notification-preferences`**:当前 parent-bff 待 ai05 设计P4
3. **假设 teacher-portal Shell 已就绪**AppShell + 共享依赖暴露react/react-dom/@tanstack/react-query/zustand/nuqs/ui-components/ui-tokens/contracts/hooks/shared-ts+ MF 配置(`remotes.parent`)已配置完成。详见 [teacher-portal 阶段2](../../teacher-portal/docs/02-architecture-design.md)。
4. **假设 Next.js 14+ Module Federation 2.0 稳定**`@module-federation/nextjs-mf` 在 Next.js App Router 下可用。若不稳定,降级为 4 端独立部署 + 各自 Shell重复实现 AppShell
### 11.2 技术风险
| 风险 | 影响 | 缓解 |
| ----------------------- | ------------------------------------------------------------ | -------------------------------------------------------------------------------- |
| MF SSR 对齐复杂 | Remote 在 SSR 时需 Shell 提供上下文 | 优先 CSRSSR 仅用于首屏 dashboardMF 2.0 支持 SSR |
| 共享依赖版本漂移 | Remote 与 Shell 的 react/react-dom 版本不一致导致运行时错误 | MF `shared.singleton: true` + CI 检查版本对齐 |
| Token 刷新竞态 | 多请求同时 401 触发多次 refresh | ApiClient 全局单例Shell 共享)+ refresh promise 复用 |
| 权限缓存陈旧 | 角色变更后前端 5min 内仍用旧权限 | iam 角色变更发 Kafka 事件 → msg 推送 WebSocket → 前端 invalidate |
| 子女切换竞态 | 快速连续切换子女导致请求乱序,旧请求覆盖新数据 | TanStack Query `queryKey``currentChildId` + 切换时 invalidate + abort 旧请求 |
| parent-bff 契约未定 | ai05 parent-bff 接口契约尚未最终确认,可能与本文档假设不一致 | P4 启动前与 ai05 对齐契约,必要时调整 `useParentApi` 实现 |
| TanStack Query 缓存膨胀 | 长时间使用后缓存项过多(多个子女的历史查询) | `gcTime` 5min + `staleTime` 按数据类型分级 + 切换子女时清理非当前子女的缓存 |
### 11.3 未决设计决策(需 coord 仲裁)
> 以下 4 项与 teacher-portal 一致,详见 [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**004 §11.3 提到 BFF GraphQL Yoga + DataLoader但当前 parent-bff 实现为 REST。前端 API 请求层是否需要 GraphQL clienturql/apollo建议P4 用 REST后续若 BFF 切 GraphQL 再引入 urql。
3. **i18n key 命名**`iam.error.IAM_INVALID_CREDENTIALS` 还是 `error.iam.invalid_credentials`?建议:`error.{{service}}.{{code_snake_case}}`,与错误码前缀对齐。
4. **MF 暴露粒度**Shell 暴露整个 AppShell 还是暴露更细粒度的组件Sidebar、Header、Content建议暴露 AppShell 整体 + 各 Remote 自行决定内部布局。
## 12. coord 交叉审查所需信息
### 12.1 端口矩阵
| 端 | dev 端口 | 生产端口 | 备注 |
| ------------- | -------- | -------- | ------------- |
| parent-portal | 3002 | 3002 | Remote 子应用 |
> 与 [full-stack-runbook](../../../docs/standards/full-stack-runbook.md) 端口矩阵对齐。
### 12.2 依赖的共享包(需 coord 建立)
| 包 | 路径 | 维护方 | 内容 |
| --------------- | ------------------------- | ------------ | ------------------------------------------------------ |
| `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、useChildSwitcher |
### 12.3 依赖的后端契约(需对应 AI 确认)
| 契约 | 提供方 | 当前状态 |
| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------ | ------------------- |
| `POST /iam/login``GET /iam/effective-permissions``GET /iam/me` | iam | ✅ 已实现 |
| `GET /parent/viewports``GET /parent/children``POST /parent/switch-child``GET /parent/notifications``PUT /parent/notification-preferences` | parent-bff (ai05) | 📐 待 P4 设计 |
| `/grades/*` `/homework/*`(子女视角) | core-edu | ✅ 已实现P3 |
| `/analytics/*` | data-ana | ✅ 已实现P4 CDC |
| `/notifications/*` + WebSocket 推送 | msg + push-gateway | 📐 待 P5 |
### 12.4 错误码前缀(前端 i18n 路由依赖)
前端不产生错误码,仅消费。需各服务确认错误码前缀不重叠:
| 前缀 | 服务 | 状态 |
| ------------- | ----------- | --------------- |
| `IAM_` | iam | ✅ 已用 |
| `CORE_EDU_` | core-edu | ✅ 已用 |
| `GRADES_` | core-edu | ⚠️ 待确认 |
| `HOMEWORK_` | core-edu | ⚠️ 待确认 |
| `BFF_PARENT_` | parent-bff | ⚠️ 待 ai05 确认 |
| `GW_` | api-gateway | ✅ 已用 |
| `NETWORK_` | 前端 | ai07 自有 |
### 12.5 不产生 Kafka 事件
前端不发布/消费 Kafka 事件。WebSocket 推送由 push-gateway 消费 Kafka 转发。
## 13. 实施路线ai07 自用)
### P4parent-portal 启动)
1.`apps/parent-portal/`Remote 角色),配置 `next.config.js` MFRemote
2. 实现 Dashboard 页面(家长仪表盘,聚合子女学情概览)
3. 实现 ChildSwitcher 组件 + `useChildSwitcher` Hook + Zustand childSwitcherSlice
4. 实现子女列表页面(`/parent/children`
5. 实现子女成绩查看页面(`/parent/grades`,复用 Shell 的 DataTable + Chart
6. 实现子女作业查看页面(`/parent/homework`
7. 实现通知偏好设置页面(`/parent/preferences`react-hook-form + zodResolver
8. 配置 `/api/health` + `/api/ready` route
9. 补 Vitest 单测 + Playwright E2E覆盖率 ≥ 80%
10. 配置 Dockerfile 多阶段构建builder + runtime
### P5推送接入
1. parent-portal 接入 WebSocketpush-gateway
2. 实现 `NotificationRequested` / `GradeRecorded` / `SchoolAnnouncement` 事件处理
3. 实现通知中心页面(`/parent/notifications`
### P6硬化
1. Web Vitals + OTel browser SDK 接入
2. A11y WCAG 2.2 AA 审计
3. 性能优化MF shared 单例验证、bundle 分析)
---
**AI Agent**: ai07 (parent-portal remote)
**Branch**: docs/parent-portal-stage1-stage2-design-ai07
**Coordinator**: coord-ai

View File

@@ -0,0 +1,409 @@
# 模块理解确认书 — student-portal
> AIai07TS/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)
---
## 1. 我在架构中的位置
- **层级**L2 微前端层004 §3.1 六层架构中的前端层)
- **MF 角色****Remote 子应用**,挂载到 teacher-portal Shell
- **上游(谁调用我)**:浏览器(学生)
- **下游(同步)**api-gatewayREST经 Next.js `rewrites` 代理 `/api/v1/*`
- **下游推送P5**push-gatewayWebSocket
- **BFF 对接**student-bff待 ai04 设计)
- **通信方式**HTTP/REST前端→Gateway+ WebSocket前端→push-gatewayP5
- **不直连**:前端不直连任何业务服务或 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 提供
## 2. 我的限界上下文
### 2.1 我负责的聚合 / 实体(前端视图模型)
- 作答、作业提交、学情诊断、错题本(学习场景域前端视图)
- 会话状态Session、视口Viewport、权限Permission— 与 Shell 共享,引用 teacher-portal 文档
### 2.2 业务领域
- **D3 教学核心领域**(前端场景域:学习场景域,学生视角)
### 2.3 不负责
- 教师批改界面(归 teacher-portal
- AI 出题(归 teacher-portal
- 班级/考试/作业 CRUD 管理(归 teacher-portal
- 用户/角色/权限 CRUD归 admin-portal
- 家长多子女切换(归 parent-portal
### 2.4 数据范围
- DataScope **L0仅本人**:学生只能看到自己的作业、考试、成绩、学情、错题
## 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 |
> student-bff 由 ai04 设计,聚合 iam + core-edu + data-ana为学生场景提供聚合视图。student-portal 主要消费 student-bff少量直连 iam登录/权限/视口)。
### 3.2 统一响应契约
所有后端响应遵循 `ActionState` 结构(迁移指南 §7.5
```typescript
type ActionState<T> =
| { success: true; data: T }
| {
success: false;
error: { code: string; message: string; details?: unknown };
};
```
错误码前缀按服务名大写(如 `IAM_``CORE_EDU_``EXAMS_``HOMEWORK_``GRADES_``BFF_STUDENT_``GW_``NETWORK_`)。前端 API 请求层根据 `error.code` 前缀路由到对应的 i18n key。
### 3.3 推送契约P5
| 协议 | 场景 |
| ------------------------- | ------------------------------------ |
| WebSocketpush-gateway | 考试发布通知、成绩发布、作业截止提醒 |
### 3.4 proto 不直接消费
前端不调用 gRPCBFF 把 gRPC 聚合为 REST 暴露给前端。前端仅消费 `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-a11yerror 级) | WCAG 2.2 AA |
| 字体 | Intersans/ Frauncesserif/ JetBrains Monomono | 复用 Shell 的 next/font/google 加载 |
## 5. 我的阶段归属
- **阶段**P3
- **当前状态**:📐 待设计(待 core-edu + student-bff 就绪),依赖上游阶段 P3
- **依赖上游阶段**P1api-gateway + iam+ P2teacher-portal Shell 就绪)+ P3core-edu + student-bff
## 6. 我需要对齐的黄金模板项(对照 classes 服务)
> 前端无 `@RequirePermission` 装饰器(后端概念),对齐项改造为前端等价物。
| 对齐项 | classes后端黄金模板 | student-portal 前端等价 | 当前状态 |
| --------------------- | ------------------------------------- | ------------------------------------------------------------------------ | ----------------------------------- |
| 权限校验 | `@RequirePermission(Permissions.XXX)` | `usePermission().hasPermission("XXX")` Hook + `<RequirePermission>` 组件 | ❌ 待建(复用 Shell 暴露的 hooks |
| 错误码前缀统一 | `CLASSES_*``IAM_*` | API 请求层根据 `error.code` 前缀路由 i18n | ❌ 待建(复用 Shell ApiClient |
| logger | pino | 前端 console + SentryP6 | ❌ 待建(复用 shared-ts Logger |
| metrics | prom-client `/metrics` | 前端 Web Vitals → Gateway 上报 | ❌ 待建 |
| tracer | OTel SDK | 前端 OTel browser SDKP6 | ❌ 待建 |
| /healthz + /readyz | `GET /healthz` `GET /readyz` | Next.js `/api/health` route + Dockerfile HEALTHCHECK | ❌ 待建 |
| 优雅关闭 | SIGTERM handler | Next.js 无长连接,无需 | ✅ 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 |
| 设计令牌三层 | — | 复用 Shell 提供的 primitive/semantic-light/dark/tailwind-theme | ❌ 待建(依赖 ui-tokens 包) |
| A11y 工具集 | — | useA11yId / mergeA11yProps / describeInput / focus-trap | ❌ 待建(复用 Shell 暴露的 hooks |
---
## 附student-portal 现状审计(对齐黄金模板)
### 审计表
| 维度 | 状态 | 说明 |
| ------------------------------------ | ------ | ---------------------------------------------------- |
| 权限装饰器(前端等价 usePermission | ❌ | 待建,复用 Shell 暴露的 `usePermission` Hook |
| 错误码前缀 | ❌ | 待建,复用 Shell 暴露的 ApiClient |
| 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% |
| Dockerfile 多阶段 | ❌ | 待建builder + runtime |
| Zod 输入验证 | ❌ | 待建react-hook-form + zodResolver |
| GlobalErrorFilterErrorBoundary | ❌ | 待建,复用 Shell ErrorBoundary |
| 设计令牌三层 | ❌ | 待建,复用 ui-tokens 包 |
| A11y 工具集 | ❌ | 待建,复用 hooks 包 |
| Module Federation 配置 | ❌ | 待建Remote 角色 |
| 5 层状态管理 | ❌ | 待建,复用 Shell Provider |
| 共享组件库 | ❌ | 待建,复用 Shell 暴露的 ui-components |
| i18n | ❌ | 待建,复用 Shell Provider + scope=student 翻译 |
| API 请求层 | ❌ | 待建,复用 Shell ApiClient仅注入不同 baseUrl/token |
| ESLint flat config 自定义规则 | ❌ | 待建,与 Shell 共用配置 |
### 现有文件清单
```
apps/student-portal/ # 空目录,待建
```
> student-portal 当前为空目录,所有维度均为 ❌ 待建状态。无现有文件清单。本设计文档作为 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 特有
4. **作业提交表单**react-hook-form + zodResolver不用 Tiptap
5. **Dockerfile 多阶段构建**builder + runtime + HEALTHCHECK
6. **Vitest + Playwright 测试**:覆盖率 ≥ 80%
7. **`/api/health` + `/api/ready` route**:健康检查端点
---
## 7. L1 导航菜单(视口)
| 视口 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 |
> 来源:`GET /api/v1/student/viewports`student-bff 聚合 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 |
## 9. L3 组件级差异student-portal 特有)
### 9.1 复用 Shell 暴露的组件
- `AppShell`(左栏导航 + 主内容区)
- `RequirePermission`L3 组件级视口控制)
- `ErrorBoundary`React 渲染异常兜底)
- `Loading`(骨架屏)
- `Empty`(空态)
- `DataTable`(表格)
- `Form`react-hook-form + zodResolver 封装)
- `Chart`recharts 封装)
### 9.2 student-portal 特有组件
| 组件 | 用途 | 来源 |
| ----------------- | --------------------------------------------- | ---- |
| `ExamTaking` | 考试作答(倒计时 + 自动保存) | 新建 |
| `HomeworkSubmit` | 作业提交表单react-hook-form + zodResolver | 新建 |
| `DiagnosticChart` | 学情诊断图表recharts 多维雷达 + 趋势线) | 新建 |
| `WeaknessList` | 错题本列表(按知识点聚合 + 掌握度标签) | 新建 |
### 9.3 不使用的组件(与 teacher-portal 差异)
- **不使用 `RichTextEditor`Tiptap**:学生不作答富文本,作业提交用表单
- 不使用 `SSEViewer`:学生不参与 AI 出题
- 不使用 `ChildSwitcher`:学生无多子女切换(家长端特有)
- 不使用 `UserManagementTable`:学生不管理用户
## 10. L4 数据层差异
| 维度 | teacher-portal | student-portal |
| ---------- | ------------------------- | -------------------------------------------------- |
| 主要数据源 | teacher-bff聚合多服务 | student-bff聚合 iam + core-edu + data-ana |
| 缓存策略 | 5min 中等缓存 | 5-30s 短缓存,作业列表 30s |
| 数据范围 | L1-L5按角色 | L0仅本人 |
| 特殊状态 | — | 考试作答草稿Zustand L3断网恢复+ 倒计时L3 |
## 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+ |
## 12. 事件设计P5 WebSocket 推送)
| 事件 | 触发 | student-portal 前端动作 |
| ----------------------------- | -------------- | ------------------------------ |
| `NotificationRequested` | msg 服务投递 | toast 提示 + 通知中心未读数 +1 |
| `ExamPublished` | 教师发布考试 | toast + dashboard invalidate |
| `GradeRecorded` | 教师录入成绩 | toast + 成绩列表 invalidate |
| `HomeworkDeadlineApproaching` | 作业截止前提醒 | toast + 作业列表高亮 |
## 13. 横切关注点对齐清单
### 13.1 权限(前端等价)
见 §8 L2 路由表权限列。完整权限点常量集中在 `packages/contracts/src/permissions.ts`待建立coord 负责 contractsai07 负责调用。L3 组件级视口用 `<RequirePermission perm="HOMEWORK_SUBMIT"><Button>提交作业</Button></RequirePermission>`
### 13.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}}` |
### 13.3 Logger
复用 `packages/shared-ts/src/logger.ts`(同 teacher-portal开发环境 console + 结构化,生产环境 → SentryP6。必含字段trace_id、user_id、scope=student、path。
### 13.4 MetricsWeb 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 TracerOTel browser SDKP6
复用 `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 自用)
### P3student-portal 起步)
1.`apps/student-portal/`Remote 角色)
2. 配置 MF`exposes` pages`remotes: { teacher: ... }`
3. 实现 Dashboard + 我的作业 + 提交作业 + 我的考试 + 作答考试
4. 复用 Shell 的 AppShell + 共享组件
5. SSE 接入(考试作答自动保存)
### P5推送接入
1. student-portal 接入 WebSocketpush-gateway
2. 通知中心 + 作业截止提醒
### P6硬化
1. Web Vitals + OTel browser SDK 接入
2. A11y WCAG 2.2 AA 审计
3. 性能优化MF shared 单例验证、bundle 分析)
---
**AI Agent**: ai07 (student-portal remote)
**Branch**: docs/student-portal-stage1-stage2-design-ai07
**Coordinator**: coord-ai

View File

@@ -0,0 +1,597 @@
# 模块架构设计文档 — student-portal
> AIai07TS/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)
> 状态:待 coord 交叉审查
---
## 1. 模块内部分层图student-portal Remote 视角)
```mermaid
graph TB
subgraph Browser["浏览器(学生)"]
URL[URL 路由 /student/*]
end
subgraph Shell["teacher-portalShell 宿主)"]
AppShell[AppShell<br/>左栏导航 + 主内容区]
RootLayout[RootLayout<br/>字体/令牌/i18n/Query Provider]
SharedDeps["共享依赖暴露<br/>react/react-dom/@tanstack/react-query/zustand/nuqs<br/>ui-components/ui-tokens/contracts/hooks"]
end
subgraph RemoteStudent["student-portalRemote"]
StudentPages["学习场景页面<br/>dashboard/homework/submit/exams/take<br/>diagnostic(P4)/weakness(P4)/notifications(P5)"]
ExamTaking[ExamTaking 组件<br/>倒计时 + 自动保存]
StudentApiClient[ApiClient 实例<br/>注入 student scope token]
end
subgraph Shared["共享层packages/"]
UITokens[ui-tokens<br/>三层设计令牌]
UIComponents[ui-components<br/>shadcn + A11y + ErrorBoundary]
Contracts[contracts<br/>Permissions 常量 + 类型]
Hooks[hooks<br/>usePermission/useAuth/useA11y]
LibTS[shared-ts<br/>ApiClient/Logger/通用工具]
end
subgraph Gateway["api-gateway"]
GW[Gin 路由/鉴权/限流]
end
subgraph PushGW["push-gatewayP5"]
WS[WebSocket /ws]
end
Browser --> URL
URL --> RootLayout
RootLayout --> AppShell
AppShell -->|动态加载 Remote| RemoteStudent
RemoteStudent -->|复用| SharedDeps
RemoteStudent --> ExamTaking
RemoteStudent --> StudentApiClient
Shell --> UITokens
Shell --> UIComponents
Shell --> Contracts
Shell --> Hooks
Shell --> LibTS
RemoteStudent --> UITokens
RemoteStudent --> UIComponents
RemoteStudent --> Contracts
RemoteStudent --> Hooks
StudentApiClient -->|fetch /api/v1/student/*| GW
StudentApiClient -->|fetch /api/v1/iam/*| GW
StudentApiClient -->|fetch /api/v1/notifications/*| GW
RemoteStudent -.->|P5 WebSocket| WS
WS -.->|推送事件| RemoteStudent
```
### 1.1 Remote 角色定位
student-portal 作为 **Remote 子应用**,由 teacher-portal Shell 动态加载。与 Shell 的职责分工:
| 职责 | Shellteacher-portal | Remotestudent-portal |
| -------------------------------- | ----------------------- | ------------------------ |
| RootLayout字体/令牌/Provider | ✅ 提供 | ❌ 复用 |
| AppShell左栏 + 主内容区) | ✅ 提供 | ❌ 复用 |
| 共享依赖暴露singleton | ✅ 提供 | ❌ 消费 |
| 登录页 | ✅ 提供 | ❌ 复用 |
| 路由表 `/student/*` | ❌ 由 Remote 暴露 | ✅ 提供 |
| 学习场景页面 | ❌ | ✅ |
| ApiClient 实例 | ❌ 提供 ApiClient 类 | ✅ 注入 student scope |
| 业务组件ExamTaking 等) | ❌ | ✅ |
### 1.2 MF 配置student-portal/next.config.js
```javascript
// student-portal/next.config.jsRemote
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,
webpack(config, { isServer }) {
config.plugins.push(
new NextFederationPlugin({
name: "student_app",
filename: "static/chunks/remoteEntry.js",
remotes: remotes(isServer),
exposes: {
"./pages": "./src/pages",
"./ExamTaking": "./src/components/ExamTaking",
},
shared: {
react: { singleton: true, requiredVersion: "^18.3.0" },
"react-dom": { singleton: true, requiredVersion: "^18.3.0" },
"@tanstack/react-query": { singleton: true },
zustand: { singleton: true },
nuqs: { 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*`,
},
];
},
};
```
**关键点**
- `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
## 2. 领域模型(前端视角)
前端不持有业务聚合根,仅持有"视图模型"ViewModel和"会话状态"。Session/Viewport/Permission 三模型与 Shell 共享,详见 [teacher-portal 阶段 2 §2](../../teacher-portal/docs/02-architecture-design.md#2-领域模型前端视角)。
### 2.1 会话状态Session
复用 Shell 的 Session 模型student-portal 不重复定义。详见 teacher-portal 文档 §2.1。
### 2.2 视口模型Viewport
复用 Shell 的 ViewportItem 模型,但 `scope` 字段值为 `'student'`。来源:`GET /api/v1/student/viewports`student-bff 聚合 iam 视口配置。AppShell 按 `scope='student'` 过滤渲染学生端导航。
### 2.3 权限模型Permission
复用 Shell 的 PermissionState 模型。来源:`GET /api/v1/iam/effective-permissions``{ permissions, viewports, dataScope }`。学生 dataScope 固定为 L0仅本人
### 2.4 student-portal 特有视图模型
```typescript
// 考试作答草稿Zustand L3断网恢复用
interface ExamTakingDraft {
examId: string;
answers: Record<string, AnswerInput>; // questionId → answer
startedAt: number;
lastSavedAt: number | null;
durationSeconds: number; // 考试时长(秒)
}
// 作业提交表单react-hook-form L5
interface HomeworkSubmitForm {
homeworkId: string;
answers: AnswerInput[];
attachments?: File[]; // 附件(图片/PDF
note?: string; // 学生备注
}
```
## 3. 数据模型(前端缓存策略)
前端无数据库仅有缓存层。student-portal 缓存策略偏短(学生数据实时性要求高):
| 数据类型 | 存储 | TTL | 失效策略 |
| ------------------------- | ------------------------- | ---- | --------------------------------------------------------- |
| Sessiontoken + user | localStorage + Zustand | — | 复用 Shellaccess 15min / refresh 7day401 自动 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 30sExamPublished 事件 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 30sWebSocket 事件 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],
);
}
```
**职责**(与 Shell 一致,由 shared-ts ApiClient 承担):
- 自动注入 `Authorization: Bearer ${token}`
- 401 自动 refresh token 一次,失败调 `onUnauthorized`
- 解析 `ActionState`success=false 抛 `ApiError`
-`error.code` 前缀路由 i18n key
- 全局错误 toast除 401
- 请求/响应 trace_id 透传(从响应头 `X-Request-Id` 提取)
### 4.2 TanStack Query 约定
```typescript
// Query Key 命名:[scope, resource, ...args]
queryKey: ["student", "dashboard"];
queryKey: ["student", "homework", { status, page }];
queryKey: ["student", "exams", { status }];
queryKey: ["student", "exam-taking", examId];
queryKey: ["student", "diagnostic"];
queryKey: ["student", "weakness", { knowledgePointId }];
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
### 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 |
### 5.2 WebSocket 连接管理P5
```typescript
// apps/student-portal/src/lib/ws.tsP5 实现)
export function useStudentWebSocket() {
const { getToken } = useAuth();
const queryClient = useQueryClient();
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;
}
};
return () => ws.close();
}, [getToken, queryClient]);
}
```
### 5.3 考试作答自动保存SSE / HTTP 轮询)
> 考试作答的自动保存采用 HTTP POST每 30s + blur 时),不使用 SSE。SSE 仅 teacher-portal 用于 AI 流式出题student-portal 不涉及。
## 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` |
> 完整权限点常量集中在 `packages/contracts/src/permissions.ts`待建立coord 负责 contractsai07 负责调用。L3 组件级视口用 `<RequirePermission perm="HOMEWORK_SUBMIT"><Button>提交作业</Button></RequirePermission>`。权限点后缀 `_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}}` |
### 6.3 Logger
复用 `packages/shared-ts/src/logger.ts`(同 teacher-portal开发环境 console + 结构化,生产环境 → SentryP6。必含字段`trace_id``user_id``scope=student``path`
```typescript
// 使用示例student-portal 内)
import { createLogger } from "@edu/shared-ts";
const logger = createLogger({ scope: "student" });
logger.info("exam taking started", { examId, durationSeconds });
logger.error("homework submit failed", { homeworkId, error: err.code });
```
### 6.4 MetricsWeb 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 暂缓。
### 6.5 TracerOTel browser SDKP6
复用 `packages/shared-ts/src/tracer.ts`(同 teacher-portal。BatchSpanProcessor → OTLP exporter → collector → Tempo。自动埋点fetch、XMLHttpRequest、document load、user interaction。
### 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` 可达 + 内存 < 阈值 |
### 6.7 优雅关闭
Next.js 无长连接(除 WS无需特殊处理。WS 在 P5 由 push-gateway 管理,前端断线自动重连(指数退避,最多 5 次)。
## 7. 共享组件库(复用 Shell 暴露 + student 特有)
### 7.1 复用 Shell 暴露的组件packages/ui-components/
| 组件 | 用途 | 来源 |
| ------------------------------------------ | --------------------------------------------------------------------------------------------------- | ------------------------------ |
| `AppShell` | 左侧栏 + 主内容区布局 | teacher-portal Shell 暴露 |
| `RequirePermission` | L3 组件级视口控制(无权限不渲染 children | Shell 暴露 |
| `ErrorBoundary` | React 渲染异常兜底fallback UI | Shell 暴露 |
| `Loading` | 骨架屏Skeleton | Shell 暴露 |
| `Empty` | 空态(插画 + 文案 + CTA | Shell 暴露 |
| `Modal` / `Dialog` | 全局 ModalModalRoot + Zustand ui-store | Shell 暴露shadcn/ui |
| `Toast` | 全局 toast错误/成功/警告) | Shell 暴露shadcn/ui sonner |
| `Button` / `Input` / `Select` / `Textarea` | 基础表单 | Shell 暴露shadcn/ui |
| `DataTable` | 表格(排序/分页/筛选) | Shell 暴露 |
| `Chart` | 图表封装recharts | Shell 暴露 |
| `A11y` 工具集 | useA11yId / mergeA11yProps / describeInput / focus-trap / skip-link / visually-hidden / aria-status | Shell 暴露 |
| `Form` | react-hook-form + zodResolver 封装 | Shell 暴露 |
### 7.2 student-portal 特有组件(不暴露给 Shell
| 组件 | 用途 | 来源 | 是否暴露给 Shell |
| ----------------- | --------------------------------------------- | ---- | ------------------------------------------- |
| `ExamTaking` | 考试作答(倒计时 + 自动保存 + 断网恢复) | 新建 | ✅ 暴露 `./ExamTaking`(供 Shell 路由复用) |
| `HomeworkSubmit` | 作业提交表单react-hook-form + zodResolver | 新建 | ❌ 内部使用 |
| `DiagnosticChart` | 学情诊断图表recharts 多维雷达 + 趋势线) | 新建 | ❌ 内部使用 |
| `WeaknessList` | 错题本列表(按知识点聚合 + 掌握度标签) | 新建 | ❌ 内部使用 |
### 7.3 不使用的组件(与 teacher-portal 差异)
- **不使用 `RichTextEditor`Tiptap**:学生不作答富文本,作业提交用表单
- 不使用 `SSEViewer`:学生不参与 AI 出题
- 不使用 `ChildSwitcher`:学生无多子女切换(家长端特有)
- 不使用 `UserManagementTable`:学生不管理用户
## 8. 共享 Hooks复用 Shell 暴露)
| Hook | 职责 | 来源 |
| --------------------- | --------------------------------------------------- | ---------- |
| `useAuth()` | 会话状态user/token/refresh/login/logout | Shell 暴露 |
| `usePermission()` | 权限查询hasPermission/hasAny/hasAll + dataScope | Shell 暴露 |
| `useViewports(scope)` | 视口列表(按 scope 过滤) | Shell 暴露 |
| `useApi()` | ApiClient 实例(注入 token + 401 处理) | Shell 暴露 |
| `useA11yId()` | 唯一 ARIA ID 生成 | Shell 暴露 |
| `useAriaLive()` | aria-live 区域管理 | Shell 暴露 |
| `useToast()` | 全局 toastZustand ui-store | Shell 暴露 |
## 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-维护))。
**强制规则**project_rules §3.10,与 Shell 一致):
- 禁止 `#hex` 字面量ESLint `no-restricted-syntax`
- 禁止 `'Inter'`/`'Fraunces'`/`'JetBrains Mono'` 字面量ESLint `design-tokens/no-hardcoded-fonts`
- 禁止 `font-size: Npx`(用 `var(--font-size-1~9)`
- 禁止 Tailwind 任意值 `w-[Npx]`(用 `--space-*` 或默认阶梯)
student-portal 的 ESLint flat config 与 Shell 共用,确保规则一致。
## 10. 与其他模块的交互点(契约清单)
| 方向 | 对方服务 | 协议 | 接口/事件 | 用途 | 阶段 |
| ------ | ------------ | ------------------ | ------------------------------------ | ---------------------------- | ---- |
| 调用 | 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+ |
> **proto 不直接消费**:前端不调用 gRPCBFF 把 gRPC 聚合为 REST 暴露给前端。前端仅消费 `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
### 11.2 技术风险
| 风险 | 影响 | 缓解 |
| ----------------------- | ----------------------------------------------------------- | ---------------------------------------------------------------------- |
| MF Remote SSR 对齐复杂 | Remote 在 SSR 时需 Shell 提供上下文 | 优先 CSRSSR 仅用于首屏 dashboardMF 2.0 支持 SSR |
| 共享依赖版本漂移 | Remote 与 Shell 的 react/react-dom 版本不一致导致运行时错误 | MF `shared.singleton: true` + CI 检查版本对齐 |
| 考试作答断网丢失 | 学生作答过程中断网,草稿丢失 | Zustand L3 + localStorage 双写,每 30s + blur 时自动保存,重连后重试 |
| 考试倒计时不准 | 学生端时间与服务器时间偏差 | 倒计时基于服务器返回的 `expiresAt`,前端仅做展示,提交以服务器时间为准 |
| 缓存陈旧导致看到旧作业 | 学生看到已截止的作业 | staleTime 30s + 截止时间客户端校验 + 提交时服务端二次校验 |
| Token 刷新竞态 | 多请求同时 401 触发多次 refresh | ApiClient 全局单例 + refresh promise 复用(复用 Shell |
| 权限缓存陈旧 | 角色变更后前端 5min 内仍用旧权限 | iam 角色变更发 Kafka 事件 → msg 推送 WebSocket → 前端 invalidate |
| TanStack Query 缓存膨胀 | 长时间使用后缓存项过多 | `gcTime` 5min + `staleTime` 按数据类型分级 |
### 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 clienturql/apollo建议P3-P4 用 REST若 BFF 切 GraphQL 再引入 urql。
3. **i18n key 命名**`error.{{service}}.{{code_snake_case}}` 还是其他模式?建议:与 teacher-portal 对齐。
4. **MF 暴露粒度**Shell 暴露整个 AppShell 还是更细粒度的组件?建议:暴露 AppShell 整体 + 各 Remote 自行决定内部布局。
## 12. coord 交叉审查所需信息
### 12.1 端口矩阵
| 端 | dev 端口 | 生产端口 | 备注 |
| -------------- | -------- | -------- | ------------- |
| student-portal | 3001 | 3001 | Remote 子应用 |
> 与 [full-stack-runbook](../../../docs/standards/full-stack-runbook.md) 端口矩阵对齐。
### 12.2 依赖的共享包(需 coord 建立)
| 包 | 路径 | 维护方 | 内容 |
| --------------- | ------------------------- | ------------ | ------------------------------------------------- |
| `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 |
### 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 |
### 12.4 错误码前缀(前端 i18n 路由依赖)
前端不产生错误码,仅消费。需各服务确认错误码前缀不重叠:
| 前缀 | 服务 | 状态 |
| ------------------------------ | ----------- | --------------- |
| `IAM_` | iam | ✅ 已用 |
| `EXAMS_`/`HOMEWORK_`/`GRADES_` | core-edu | ⚠️ 待确认 |
| `BFF_STUDENT_` | student-bff | ⚠️ 待 ai04 确认 |
| `GW_` | api-gateway | ✅ 已用 |
| `NETWORK_` | 前端 | ai07 自有 |
### 12.5 不产生 Kafka 事件
前端不发布/消费 Kafka 事件。WebSocket 推送由 push-gateway 消费 Kafka 转发。
## 13. 实施路线ai07 自用)
### P3student-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 双写草稿)
6. 配置 Dockerfile 多阶段构建 + `/api/health` + `/api/ready` route
7. 补 Vitest 单测 + Playwright E2E覆盖率 ≥ 80%
### P4学情诊断 + 错题本)
1. 实现学情诊断页面DiagnosticChart 多维雷达 + 趋势线)
2. 实现错题本页面WeaknessList 按知识点聚合 + 掌握度标签)
### P5推送 + 通知中心)
1. student-portal 接入 WebSocketpush-gateway
2. 实现通知中心页面(通知列表 + 未读数 + 标记已读)
3. 处理 4 类推送事件NotificationRequested/ExamPublished/GradeRecorded/HomeworkDeadlineApproaching
### P6硬化
1. Web Vitals + OTel browser SDK 接入
2. A11y WCAG 2.2 AA 审计
3. 性能优化MF shared 单例验证、bundle 分析)
---
**AI Agent**: ai07 (student-portal remote)
**Branch**: docs/student-portal-stage1-stage2-design-ai07
**Coordinator**: coord-ai

View File

@@ -1,945 +0,0 @@
# teacher-portal / 4 端微前端架构设计
> 版本1.0
> 日期2026-07-09
> AI Agentai07前端 4 端teacher-portal / student-portal / parent-portal / admin-portal
> 阶段:阶段 1理解确认书+ 阶段 2模块架构设计文档
> 关联文档:
>
> - [004 架构影响地图](../../docs/architecture/004_architecture_impact_map.md) §1.1a/1.1b/§5.4
> - [AI 分配方案](../../docs/architecture/ai-allocation.md) §5 ai07
> - [项目规则](../../.trae/rules/project_rules.md) §3.8/§3.9/§3.10
> - [编码规范](../../docs/standards/coding-standards.md) §2.8-2.10/§7
> - [迁移指南](../../MIGRATION_GUIDE.md) §7.1-7.7
> - [known-issues](../../docs/troubleshooting/known-issues.md) §2.12
> 本文档合并 4 端的设计,因 ai07 单一负责全部 4 端Module Federation shell + remote 架构需统一设计4 端共享组件库和权限体系。当前仓库仅 `teacher-portal` 已实现P1 测试页 + P2 骨架student/parent/admin-portal 待建。
---
## 目录
1. [阶段 1模块理解确认书4 端)](#阶段-1模块理解确认书4-端)
2. [teacher-portal 现状审计(对齐黄金模板)](#teacher-portal-现状审计对齐黄金模板)
3. [阶段 2模块架构设计文档](#阶段-2模块架构设计文档)
4. [4 端差异化对比表](#4-端差异化对比表)
5. [与其他模块的交互点(契约清单)](#与其他模块的交互点契约清单)
6. [风险与假设](#风险与假设)
7. [coord 交叉审查所需信息](#coord-交叉审查所需信息)
---
# 阶段 1模块理解确认书4 端)
## 1.1 我在架构中的位置
| 维度 | teacher-portal | student-portal | parent-portal | admin-portal |
| ------------ | --------------------------------------------------------- | ---------------- | ---------------- | --------------------------- |
| 层级 | L2 微前端层 | L2 微前端层 | L2 微前端层 | L2 微前端层 |
| MF 角色 | **Shell 宿主**(主应用) | Remote子应用 | Remote子应用 | Remote子应用 |
| 上游 | 浏览器(教师 / 教导主任 / 教研组长) | 浏览器(学生) | 浏览器(家长) | 浏览器(系统/校管理员) |
| 下游(同步) | api-gatewayREST经 Next.js rewrites 代理) | api-gateway | api-gateway | api-gateway |
| 下游(推送) | push-gatewayWebSocket/SSEP5 | push-gateway | push-gateway | — |
| BFF 对接 | teacher-bffGraphQL Yoga + DataLoader | student-bff | parent-bff | teacher-bff 复用 + iam 直连 |
| 通信方式 | HTTP/REST前端→Gateway+ WebSocket前端→push-gateway | 同左 | 同左 | HTTP/REST |
**说明**
- 4 端均通过 `next.config.js``rewrites``/api/v1/*` 代理到 `api-gateway`,前端不直连任何业务服务或 BFF 后端实例
- MF 架构下4 端共享同一 Shellteacher-portal 作为 Shell 宿主),其余 3 端作为 Remote 子应用挂载Shell 提供 AppShell + 共享组件库 + 权限 Hook + API 请求层
- 场景域 BFF 复用策略004 §5.4):教导主任/教研组长复用 teacher-portal + 额外管理视口,不单独建 portal
## 1.2 我的限界上下文
| 项 | teacher-portal | student-portal | parent-portal | admin-portal |
| -------- | --------------------------------------------------------------------------------------------------- | -------------------------------- | ---------------------------------------- | ------------------------------------------------- |
| 业务领域 | 教学场景域 | 学习场景域 | 家长场景域 | 管理场景域 |
| 主要聚合 | 班级、考试、作业、成绩、备课、AI 出题 | 作答、作业提交、学情诊断、错题本 | 多子女切换、通知偏好、学情查看、成绩通知 | 用户/角色/权限/视口 CRUD、组织/班级管理、平台监控 |
| 不负责 | 学生作答界面、家长多子女切换 | 教师批改界面、AI 出题 | 教师沟通、学生作答 | 教学业务编排(归 teacher-portal |
| 数据范围 | DataScope L1-L5教师 L1 班级 / 教导主任 L2 年级 / 校管理员 L3 学校 / 区教研员 L4 / 系统管理员 L5 | DataScope L0仅本人 | DataScope L0仅子女 | DataScope L3-L5校管理员 L3 / 系统管理员 L5 |
## 1.3 我与外部的契约
### 1.3.1 消费的后端 API经 api-gateway 代理)
| 端 | 路径前缀 | 下游 BFF/服务 | 关键端点 |
| -------------- | ------------------------------------------------------------------------ | --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| teacher-portal | `/api/v1/iam/*` | iam | `POST /iam/login``POST /iam/register``POST /iam/refresh``GET /iam/me``GET /iam/rbac/...``GET /iam/effective-permissions` |
| teacher-portal | `/api/v1/teacher/*` | teacher-bff | `GET /teacher/viewports``GET /teacher/dashboard``GET /teacher/classes/:id/exams``GET /teacher/classes/:id/homework``GET /teacher/exams/:id/grades` |
| teacher-portal | `/api/v1/classes/*` | core-educlasses 模块) | CRUD黄金模板 |
| teacher-portal | `/api/v1/exams/*` `/api/v1/homework/*` `/api/v1/grades/*` | core-edu | P3 教学核心 |
| teacher-portal | `/api/v1/textbooks/*` `/api/v1/knowledge-points/*` `/api/v1/questions/*` | content | P4 内容 |
| teacher-portal | `/api/v1/ai/*` | aiSSE 流式) | P5 AI 辅助出题 |
| student-portal | `/api/v1/student/*` | student-bff | `GET /student/viewports``GET /student/dashboard``GET /student/homework``POST /student/homework/:id/submit``GET /student/diagnostic` |
| parent-portal | `/api/v1/parent/*` | parent-bff | `GET /parent/viewports``GET /parent/children``POST /parent/switch-child``GET /parent/notifications``PUT /parent/notification-preferences` |
| admin-portal | `/api/v1/iam/*`(管理用) | iam | 用户/角色/权限/视口 CRUD |
| admin-portal | `/api/v1/admin/*` | teacher-bff 复用 + iam 直连 | 平台监控、统计数据聚合 |
| 全部 | `/api/v1/notifications/*` | msg | 通知中心P5 |
### 1.3.2 统一响应契约
所有后端响应遵循 `ActionState` 结构(迁移指南 §7.5
```typescript
type ActionState<T> =
| { success: true; data: T }
| {
success: false;
error: { code: string; message: string; details?: unknown };
};
```
错误码前缀按服务名大写(如 `IAM_``CORE_EDU_``CONTENT_``MSG_``AI_``BFF_``GW_`)。前端 API 请求层根据 `error.code` 前缀路由到对应的 i18n key。
### 1.3.3 推送契约P5
| 端 | 协议 | 场景 |
| -------------- | ------------------------- | -------------------------------------------- |
| teacher-portal | WebSocketpush-gateway | 学生提交作业通知、考试成绩录入提醒、全校广播 |
| student-portal | WebSocket | 考试发布通知、成绩发布、作业截止提醒 |
| parent-portal | WebSocket | 子女成绩发布、教师沟通、学校通知 |
| admin-portal | — | 不消费推送(管理端用轮询) |
## 1.4 我的技术栈
| 维度 | 选型 | 说明 |
| --------------------------- | -------------------------------------------------------- | -------------------------------------------------------- |
| 框架 | Next.js 14+App Router | 4 端统一server components 默认client components 按需 |
| 语言 | TypeScript 5.5+strict | 沿用 tsconfig.base.json |
| 微前端 | Module Federation 2.0@module-federation/nextjs-mf | teacher-portal = Shell其余 = Remote |
| 样式 | Tailwind CSS 3.4+ | 配合设计令牌三层模型 |
| UI 组件库 | shadcn/ui迁移指南 §7.2 | 平移至 `packages/ui-components/`MF 共享 |
| 状态管理 L1 URL | nuqs | 可分享、可刷新状态 |
| 状态管理 L2 Server | TanStack Query v5 | 服务端数据缓存、重试、乐观更新 |
| 状态管理 L3 Client Business | Zustand slice | 客户端业务状态 |
| 状态管理 L4 Global UI | Zustand ui-store + ModalRoot | 全局 UI 状态 |
| 状态管理 L5 Form | react-hook-form + zodResolver | 表单状态 |
| 富文本 | Tiptap备课、出题、反馈 | SSR 安全 |
| 图表 | recharts | 学情、Dashboard |
| i18n | next-intl | BFF/服务返回 i18n key + 参数,前端翻译 |
| A11y | eslint-plugin-jsx-a11yerror 级) | WCAG 2.2 AA |
| 字体 | Intersans/ Frauncesserif/ JetBrains Monomono | next/font/google 加载CSS 变量暴露 |
## 1.5 我的阶段归属
| 端 | 阶段 | 当前状态 | 依赖上游阶段 |
| -------------- | ---- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------- |
| teacher-portal | P2 | ✅ 已实现 P1 测试页 + P2 骨架(登录/AppShell/Dashboard/classes CRUD 待审计对齐黄金模板 + 引入 MF + 共享组件库 | P1api-gateway + classes + iam |
| student-portal | P3 | 📐 需设计(待 core-edu + student-bff 就绪) | P3core-edu + student-bff |
| parent-portal | P4 | 📐 需设计(待 parent-bff + data-ana 就绪) | P4parent-bff + data-ana |
| admin-portal | P6 | 📐 需设计(待全部业务服务稳定) | P6硬化阶段 |
## 1.6 黄金模板对齐清单(对照 classes 服务)
> 前端无 `@RequirePermission` 装饰器(后端概念),对齐项改造为前端等价物。
| 对齐项 | classes后端黄金模板 | teacher-portal 前端等价 | 当前状态 |
| --------------------- | ------------------------------------- | ------------------------------------------------------------------------ | -------------------------------------------- |
| 权限校验 | `@RequirePermission(Permissions.XXX)` | `usePermission().hasPermission("XXX")` Hook + `<RequirePermission>` 组件 | ❌ 缺失,直接硬编码 `user.roles.join(", ")` |
| 错误码前缀统一 | `CLASSES_*``IAM_*` | API 请求层根据 `error.code` 前缀路由 i18n | ❌ 缺失统一请求层 |
| logger | pino | 前端 console + SentryP6 | ⚠️ 仅 console.error |
| metrics | prom-client `/metrics` | 前端 Web Vitals → Gateway 上报 | ❌ 缺失 |
| tracer | OTel SDK | 前端 OTel browser SDKP6 | ❌ 缺失 |
| /healthz + /readyz | `GET /healthz` `GET /readyz` | Next.js `/api/health` route + Dockerfile HEALTHCHECK | ⚠️ Dockerfile 有 HEALTHCHECK无 /api/health |
| 优雅关闭 | SIGTERM handler | Next.js 无长连接,无需 | ✅ N/A |
| 测试覆盖率 ≥ 80% | Vitest | Vitest + @testing-library/react + Playwright E2E | ❌ 0% |
| Dockerfile 多阶段构建 | builder + runtime | 已有多阶段 | ✅ 已对齐 |
| Zod 输入验证 | class-validator + Zod schema | react-hook-form + zodResolver | ❌ 缺失 |
| GlobalErrorFilter | NestJS 全局异常过滤器 | React ErrorBoundary + API 请求层统一错误处理 | ❌ 缺失 |
| 设计令牌三层 | — | primitive.css / semantic-light/dark.css / tailwind-theme.css | ❌ 硬编码在 globals.css + tailwind.config.js |
| A11y 工具集 | — | useA11yId / mergeA11yProps / describeInput / focus-trap | ❌ 缺失 |
---
# teacher-portal 现状审计(对齐黄金模板)
## 2.1 审计表
| 维度 | 状态 | 说明 |
| ------------------------------------ | ------ | ---------------------------------------------------------------------- |
| 权限装饰器(前端等价 usePermission | ❌ | AppShell.tsx 直接 `user.roles.join(", ")`,违反 project_rules §3.8 |
| 错误码前缀 | ❌ | 无统一 API 请求层,错误处理散落在每个 page.tsx |
| logger | ⚠️ | 仅 `console.error`,无结构化、无 trace_id |
| metrics | ❌ | 无 Web Vitals 采集 |
| tracer | ❌ | 无 OTel browser SDK |
| /healthz | ⚠️ | Dockerfile 有 `HEALTHCHECK wget /`,但无 `/api/health` route |
| /readyz | ❌ | 无 |
| 优雅关闭 | ✅ N/A | Next.js 无长连接 |
| 测试覆盖率 | ❌ | 0%,无测试文件 |
| Dockerfile 多阶段 | ✅ | builder + runtime非 root 用户HEALTHCHECK |
| Zod 输入验证 | ❌ | 表单直接 useState无 zodResolver |
| GlobalErrorFilterErrorBoundary | ❌ | 无 React ErrorBoundary |
| 设计令牌三层 | ❌ | 硬编码在 globals.css`:root` 变量)+ tailwind.config.jshex 字面量) |
| A11y 工具集 | ❌ | 无 useA11yId、focus-trap 等 |
| Module Federation 配置 | ❌ | next.config.js 仅有 rewrites无 MF |
| 5 层状态管理 | ❌ | 仅 useState + localStorage无 nuqs/TanStack Query/Zustand |
| 共享组件库 | ❌ | 仅 AppShell无 ErrorBoundary/Loading/Empty/RequirePermission |
| i18n | ❌ | 中文硬编码在 JSX |
| API 请求层 | ❌ | 每页重复 fetch + authHeaders + try/catch |
| ESLint flat config 自定义规则 | ❌ | 未配置 no-hardcoded-fonts / design-tokens 规则 |
## 2.2 现有文件清单
```
apps/teacher-portal/
├─ src/
│ ├─ app/
│ │ ├─ (app)/ # 受保护路由组(套 AppShell
│ │ │ ├─ classes/page.tsx # 班级 CRUDP1 测试页)
│ │ │ ├─ dashboard/page.tsx # 教师仪表盘
│ │ │ ├─ exams/page.tsx # 考试列表
│ │ │ ├─ grades/page.tsx # 成绩查询
│ │ │ ├─ homework/page.tsx # 作业列表
│ │ │ └─ layout.tsx # 套 AppShell
│ │ ├─ login/page.tsx # 登录页(不套壳)
│ │ ├─ globals.css # 全局样式 + 设计令牌(硬编码)
│ │ ├─ layout.tsx # 根布局(字体加载)
│ │ └─ page.tsx # 根路径重定向
│ ├─ components/
│ │ └─ AppShell.tsx # 左侧栏 + 主内容区
│ └─ lib/
│ └─ auth.ts # token + userInfo localStorage 管理
├─ Dockerfile # 多阶段构建 ✅
├─ next.config.js # 仅 rewrites无 MF ❌
├─ package.json # 仅 next/react/react-dom无 MF/Query/Zustand ❌
├─ tailwind.config.js # 硬编码 hex ❌
├─ postcss.config.js
└─ tsconfig.json
```
## 2.3 主要违规点(必须在 P2 收尾或 P3 起步时修复)
1. **权限硬编码**[AppShell.tsx:143](src/components/AppShell.tsx) `user.roles.join(", ")` 违反 project_rules §3.8,必须改为 `usePermission().hasPermission()`
2. **设计令牌硬编码**[globals.css:6-13](src/app/globals.css) 与 [tailwind.config.js:7-19](tailwind.config.js) 出现 `hsl(...)` 字面量与 `'Fraunces'`/`'Inter'` 字面量,违反 project_rules §3.10
3. **无统一 API 请求层**4 个 page.tsx 重复 `authHeaders()` + `fetch` + `try/catch` + `setError`,必须抽取到 `lib/api.ts`
4. **无权限 Hook**:缺少 `usePermission().hasPermission()`,无法做 L3 组件级视口控制
5. **无 ErrorBoundary**React 渲染异常会白屏
6. **无 5 层状态管理**:登录态用 localStorageL3但无 TanStack QueryL2导致每页重复 fetch
7. **字体名硬编码**[layout.tsx:3-7](src/app/layout.tsx) 直接 import `Inter/Fraunces/JetBrains_Mono`,应改为 `var(--font-family-sans/serif/mono)`
---
# 阶段 2模块架构设计文档
## 3.1 模块内部分层图4 端统一 MF 架构)
```mermaid
graph TB
subgraph Browser["浏览器"]
URL[URL 路由]
end
subgraph Shell["teacher-portalShell 宿主)"]
AppShell[AppShell<br/>左栏导航 + 主内容区]
RootLayout[RootLayout<br/>字体/令牌/i18n Provider]
Router[Next.js App Router]
SharedDeps["共享依赖暴露<br/>react/react-dom/@tanstack/react-query/zustand/nuqs"]
end
subgraph RemoteTeacher["teacher-portal Remote 模块"]
TeacherPages[教学场景页面<br/>dashboard/classes/exams/homework/grades/ai-assist]
end
subgraph RemoteStudent["student-portalRemote"]
StudentPages[学习场景页面<br/>dashboard/homework/submit/diagnostic/exam-taking]
end
subgraph RemoteParent["parent-portalRemote"]
ParentPages[家长场景页面<br/>dashboard/children-switch/grades/notifications]
end
subgraph RemoteAdmin["admin-portalRemote"]
AdminPages[管理场景页面<br/>users/roles/permissions/viewports/monitoring]
end
subgraph Shared["共享层packages/"]
UITokens[ui-tokens<br/>三层设计令牌]
UIComponents[ui-components<br/>shadcn + A11y + ErrorBoundary]
Contracts[contracts<br/>Permissions 常量 + 类型]
Hooks[hooks<br/>usePermission/useAuth/useA11y]
LibTS[shared-ts<br/>通用工具]
end
subgraph Gateway["api-gateway"]
GW[Gin 路由/鉴权/限流]
end
Browser --> URL
URL --> RootLayout
RootLayout --> AppShell
AppShell --> Router
Router -->|动态加载| RemoteTeacher
Router -->|动态加载| RemoteStudent
Router -->|动态加载| RemoteParent
Router -->|动态加载| RemoteAdmin
RemoteTeacher --> SharedDeps
RemoteStudent --> SharedDeps
RemoteParent --> SharedDeps
RemoteAdmin --> SharedDeps
Shell --> UITokens
Shell --> UIComponents
Shell --> Contracts
Shell --> Hooks
RemoteTeacher --> UITokens
RemoteStudent --> UITokens
RemoteParent --> UITokens
RemoteAdmin --> UITokens
AppShell -->|fetch /api/v1/iam/effective-permissions| Hooks
Hooks -->|透传 token| GW
RemoteTeacher -->|fetch /api/v1/teacher/*| GW
RemoteStudent -->|fetch /api/v1/student/*| GW
RemoteParent -->|fetch /api/v1/parent/*| GW
RemoteAdmin -->|fetch /api/v1/iam/* + /api/v1/admin/*| GW
```
### 3.1.1 MF 拓扑选型
| 方案 | 选否 | 理由 |
| ------------------------------------ | ---- | --------------------------------------------------------------------------------------- |
| 4 端独立部署 + 独立域名 + 各自 Shell | ❌ | 4 套 Shell 重复,登录态/权限/组件库要重复实现 |
| 单 Shell + 4 Remote**采用** | ✅ | teacher-portal 作为 Shell 宿主,提供 AppShell + 共享依赖;其余 3 端作为 Remote 动态加载 |
| 单一 Next.js 应用 + 4 路由组 | ❌ | 违反"微前端独立部署"目标ADR-012 |
**Shell 职责**
- RootLayout字体、设计令牌、i18n Provider、TanStack QueryClientProvider、Zustand StoreProvider
- AppShell左侧导航 + 主内容区 + 用户信息 + 登出)
- 共享依赖暴露react、react-dom、@tanstack/react-query、zustand、nuqs、ui-components、ui-tokens、contracts、hooks
- 路由表4 端路由前缀:`/teacher/*``/student/*``/parent/*``/admin/*`
- 登录页(统一登录入口,按角色重定向到对应 portal
**Remote 职责**
- 各场景域页面page.tsx
- 各场景域专属组件
- 各场景域专属 Zustand slice
- 通过 MF 共享 Shell 暴露的依赖,避免重复加载
### 3.1.2 MF 配置next.config.js
```javascript
// teacher-portal/next.config.jsShell
const NextFederationPlugin = require("@module-federation/nextjs-mf");
const remotes = (isServer) => ({
student: `student_app@http://localhost:3001/_next/static/${isServer ? "ssr" : "chunks"}/remoteEntry.js`,
parent: `parent_app@http://localhost:3002/_next/static/${isServer ? "ssr" : "chunks"}/remoteEntry.js`,
admin: `admin_app@http://localhost:3003/_next/static/${isServer ? "ssr" : "chunks"}/remoteEntry.js`,
});
module.exports = {
reactStrictMode: true,
webpack(config, { isServer }) {
config.plugins.push(
new NextFederationPlugin({
name: "teacher_app",
filename: "static/chunks/remoteEntry.js",
remotes: remotes(isServer),
exposes: {
"./AppShell": "./src/components/AppShell",
"./shared-deps": "./src/shared/deps",
},
shared: {
react: { singleton: true, requiredVersion: "^18.3.0" },
"react-dom": { singleton: true, requiredVersion: "^18.3.0" },
"@tanstack/react-query": { singleton: true },
zustand: { singleton: true },
nuqs: { 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*`,
},
];
},
};
```
> Remote 端配置对称:`name: 'student_app'``exposes: { './pages': './src/pages' }``remotes: { teacher: 'teacher_app@...' }`。
## 3.2 领域模型(前端视角)
前端不持有业务聚合根,仅持有"视图模型"ViewModel和"会话状态"。
### 3.2.1 会话状态Session
```typescript
interface Session {
user: UserInfo; // { id, email, name, roles, permissions, dataScope }
tokens: { accessToken: string; refreshToken: string };
viewports: ViewportItem[]; // L1 导航视口
expiresAt: number; // access token 过期时间戳
}
```
存储Zustand sessionSliceL3+ localStorage 持久化(刷新恢复)+ TanStack Query 缓存 `['session']`L2
### 3.2.2 视口模型Viewport
```typescript
interface ViewportItem {
key: string; // 'dashboard' | 'classes' | ...
label: string; // i18n key 或显式文案
route: string; // '/teacher/dashboard'
icon: string | null; // 图标 key按需
sortOrder: number; // 排序
requiredPermission: string | null; // 'CLASSES_READ' 等
scope: "teacher" | "student" | "parent" | "admin"; // 标记归属哪个 portal
}
```
来源:`GET /api/v1/{scope}/viewports`BFF 聚合 iam 视口配置。AppShell 按 `scope` 过滤渲染对应 portal 的导航。
### 3.2.3 权限模型Permission
```typescript
interface PermissionState {
permissions: string[]; // ['CLASSES_READ', 'EXAMS_CREATE', ...]
dataScope: DataScope; // L0-L5
hasPermission: (perm: string) => boolean;
hasAnyPermission: (perms: string[]) => boolean;
hasAllPermissions: (perms: string[]) => boolean;
}
```
来源:`GET /api/v1/iam/effective-permissions``{ permissions, viewports, dataScope }`。Redis 缓存 5miniam 侧),前端 TanStack Query 缓存 5min角色变更主动 invalidate。
## 3.3 数据模型(前端)
前端无数据库,仅有缓存层:
| 数据类型 | 存储 | TTL | 失效策略 |
| ----------------------- | ---------------------- | --------------------------- | -------------------------------------- |
| Sessiontoken + user | localStorage + Zustand | access 15min / refresh 7day | 401 自动 refreshrefresh 失败跳登录 |
| 权限列表 | TanStack Query cache | 5min | 角色变更事件 invalidate |
| 视口列表 | TanStack Query cache | 5min | 同上 |
| 班级/年级列表 | TanStack Query cache | 5min | staleTime 5minmutation 后 invalidate |
| 教学资源详情 | TanStack Query cache | 30s | staleTime 30s |
| 学情宽表 | TanStack Query cache | 30s | staleTime 30s实时性由 BFF 决定) |
| URL 状态(分页/筛选) | nuqs | — | 永久(可分享) |
| 表单临时态 | react-hook-form | — | 卸载即销毁 |
## 3.4 API 设计(前端 → 后端)
前端不设计后端 API仅声明消费的端点。详见 §1.3.1。
### 3.4.1 统一 API 请求层lib/api.ts
```typescript
// packages/shared-ts/src/api-client.ts共享
interface ApiClientOptions {
baseUrl?: string; // 默认 ''(走 Next.js rewrites
getToken?: () => string | null;
onUnauthorized?: () => void; // 401 → refresh → 重试 / 跳登录
onError?: (error: ApiError) => void; // 全局 toast
}
class ApiClient {
async get<T>(path: string, query?: Record<string, string>): Promise<T>;
async post<T>(path: string, body: unknown): Promise<T>;
async put<T>(path: string, body: unknown): Promise<T>;
async delete<T>(path: string): Promise<T>;
async sse<T>(path: string, body: unknown): AsyncIterable<T>; // AI 流式
}
// 错误结构
interface ApiError {
code: string; // 'IAM_INVALID_CREDENTIALS'
message: string; // 已 i18n 翻译或后端原文
details?: unknown;
httpStatus: number;
}
```
**职责**
- 自动注入 `Authorization: Bearer ${token}`
- 401 自动 refresh token 一次,失败调 `onUnauthorized`
- 解析 `ActionState`success=false 抛 `ApiError`
-`error.code` 前缀路由 i18n key
- 全局错误 toast除 401
- 请求/响应 trace_id 透传(从响应头 `X-Request-Id` 提取)
### 3.4.2 TanStack Query 约定
```typescript
// Query Key 命名:[scope, resource, ...args]
queryKey: ["teacher", "classes", { gradeId }];
queryKey: ["teacher", "exams", classId];
queryKey: ["session", "effective-permissions"];
queryKey: ["session", "viewports", "teacher"];
// Mutation 约定
const mutation = useMutation({
mutationFn: (input) => api.post("/api/v1/classes", input),
onSuccess: () =>
queryClient.invalidateQueries({ queryKey: ["teacher", "classes"] }),
onError: (e: ApiError) => toast.error(e.message),
});
```
## 3.5 事件设计
前端不发布 Kafka 事件,仅消费 WebSocket 推送P5和 Server-Sent EventsAI 流式)。
### 3.5.1 WebSocket 推送P5
| 事件 | 触发 | 前端动作 |
| ----------------------- | ------------ | --------------------------------------- |
| `NotificationRequested` | msg 服务投递 | toast 提示 + 通知中心未读数 +1 |
| `ExamPublished` | 教师发布考试 | 学生端 toast + dashboard invalidate |
| `GradeRecorded` | 教师录入成绩 | 学生/家长端 toast + 成绩列表 invalidate |
| `HomeworkSubmitted` | 学生提交作业 | 教师端 toast + 作业批改列表 invalidate |
### 3.5.2 SSE 流式P5 AI 辅助出题)
```
GET /api/v1/ai/generate-questions (SSE)
data: {"delta": "题目"}\n\n
data: {"delta": "A. option1"}\n\n
data: {"done": true}\n\n
```
前端用 `AsyncIterable<T>` 消费Tiptap 逐字插入。
## 3.6 横切关注点对齐清单
### 3.6.1 权限(前端等价)
| 端 | 路由 | requiredPermission |
| -------------- | ------------------------------ | ------------------------ |
| teacher-portal | `/teacher/dashboard` | `TEACHER_DASHBOARD_VIEW` |
| teacher-portal | `/teacher/classes` | `CLASSES_READ` |
| teacher-portal | `/teacher/classes/new` | `CLASSES_CREATE` |
| teacher-portal | `/teacher/exams` | `EXAMS_READ` |
| teacher-portal | `/teacher/exams/new` | `EXAMS_CREATE` |
| teacher-portal | `/teacher/homework` | `HOMEWORK_READ` |
| teacher-portal | `/teacher/homework/:id/grade` | `HOMEWORK_GRADE` |
| teacher-portal | `/teacher/grades` | `GRADES_READ` |
| teacher-portal | `/teacher/ai-assist` | `AI_GENERATE` |
| student-portal | `/student/dashboard` | `STUDENT_DASHBOARD_VIEW` |
| student-portal | `/student/homework` | `HOMEWORK_READ_OWN` |
| student-portal | `/student/homework/:id/submit` | `HOMEWORK_SUBMIT` |
| student-portal | `/student/diagnostic` | `DIAGNOSTIC_READ_OWN` |
| parent-portal | `/parent/dashboard` | `PARENT_DASHBOARD_VIEW` |
| parent-portal | `/parent/children` | `PARENT_CHILDREN_VIEW` |
| parent-portal | `/parent/grades` | `GRADES_READ_CHILD` |
| admin-portal | `/admin/users` | `IAM_USER_READ` |
| admin-portal | `/admin/users/new` | `IAM_USER_CREATE` |
| admin-portal | `/admin/roles` | `IAM_ROLE_READ` |
| admin-portal | `/admin/permissions` | `IAM_PERMISSION_READ` |
| admin-portal | `/admin/viewports` | `IAM_VIEWPORT_READ` |
| admin-portal | `/admin/monitoring` | `ADMIN_MONITORING_VIEW` |
> 完整权限点常量集中在 `packages/contracts/src/permissions.ts`待建立coord 负责 shared-tsai07 负责调用。L3 组件级视口用 `<RequirePermission perm="EXAMS_CREATE"><Button>新建考试</Button></RequirePermission>`。
### 3.6.2 错误码清单(前端 i18n 路由)
| 前缀 | 来源服务 | i18n key 模式 |
| ------------ | -------------------------- | ------------------------ |
| `IAM_*` | iam | `iam.error.{{code}}` |
| `CORE_EDU_*` | core-edu | `coreEdu.error.{{code}}` |
| `CLASSES_*` | core-edu/classes | `classes.error.{{code}}` |
| `CONTENT_*` | content | `content.error.{{code}}` |
| `MSG_*` | msg | `msg.error.{{code}}` |
| `AI_*` | ai | `ai.error.{{code}}` |
| `BFF_*` | teacher/student/parent-bff | `bff.error.{{code}}` |
| `GW_*` | api-gateway | `gateway.error.{{code}}` |
| `NETWORK_*` | 前端网络层 | `network.error.{{code}}` |
### 3.6.3 Logger
```typescript
// packages/shared-ts/src/logger.ts
interface Logger {
info(msg: string, meta?: Record<string, unknown>): void;
warn(msg: string, meta?: Record<string, unknown>): void;
error(msg: string, meta?: Record<string, unknown>): void;
}
// 实现:开发环境 console + 结构化;生产环境 → SentryP6
// 必含字段trace_id从响应头提取、user_id、scope、path
```
### 3.6.4 MetricsWeb Vitals
| 指标 | 类型 | 上报 |
| ----------------------------- | ---- | --------------------------------------------------- |
| `teacher_portal_lcp_seconds` | LCP | `next/web-vitals``POST /api/v1/admin/web-vitals` |
| `teacher_portal_cls` | CLS | 同上 |
| `teacher_portal_fid_seconds` | FID | 同上 |
| `teacher_portal_ttfb_seconds` | TTFB | 同上 |
P6 接入P2-P5 暂缓。
### 3.6.5 TracerOTel browser SDKP6
```typescript
// packages/shared-ts/src/tracer.ts
import { WebTracerProvider } from "@opentelemetry/sdk-trace-web";
// BatchSpanProcessor → OTLP exporter → collector → Tempo
// 自动埋点fetch、XMLHttpRequest、document load、user interaction
```
### 3.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` 可达 + 内存 < 阈值 |
### 3.6.7 优雅关闭
Next.js 无长连接(除 SSE/WS无需特殊处理。SSE/WS 在 P5 由 push-gateway 管理,前端断线自动重连。
## 3.7 共享组件库packages/ui-components/,待建立)
| 组件 | 用途 | 来源 |
| ------------------------------------------ | --------------------------------------------------------------------------------------------------- | ------------------------------ |
| `AppShell` | 左侧栏 + 主内容区布局 | teacher-portal 现有 → 抽取共享 |
| `RequirePermission` | L3 组件级视口控制(无权限不渲染 children | 新建 |
| `ErrorBoundary` | React 渲染异常兜底fallback UI | 新建 |
| `Loading` | 骨架屏Skeleton | 新建 |
| `Empty` | 空态(插画 + 文案 + CTA | 新建 |
| `Modal` / `Dialog` | 全局 ModalModalRoot + Zustand ui-store | shadcn/ui |
| `Toast` | 全局 toast错误/成功/警告) | shadcn/ui sonner |
| `Button` / `Input` / `Select` / `Textarea` | 基础表单 | shadcn/ui |
| `DataTable` | 表格(排序/分页/筛选) | shadcn/ui + TanStack Table |
| `Chart` | 图表封装recharts | 新建 |
| `A11y` 工具集 | useA11yId / mergeA11yProps / describeInput / focus-trap / skip-link / visually-hidden / aria-status | 迁移指南 §7.7 |
| `Form` | react-hook-form + zodResolver 封装 | 新建 |
## 3.8 共享 Hookspackages/hooks/,待建立)
| Hook | 职责 |
| --------------------- | --------------------------------------------------- |
| `useAuth()` | 会话状态user/token/refresh/login/logout |
| `usePermission()` | 权限查询hasPermission/hasAny/hasAll + dataScope |
| `useViewports(scope)` | 视口列表(按 scope 过滤) |
| `useApi()` | ApiClient 实例(注入 token + 401 处理) |
| `useA11yId()` | 唯一 ARIA ID 生成 |
| `useAriaLive()` | aria-live 区域管理 |
| `useToast()` | 全局 toastZustand ui-store |
## 3.9 设计令牌三层packages/ui-tokens/,待建立)
```
packages/ui-tokens/
├─ primitive.css # Layer 1 原始色板/字号/间距/阴影
├─ semantic-light.css # Layer 2 语义令牌(亮色)
├─ semantic-dark.css # Layer 2 语义令牌(暗色)
├─ tailwind-theme.css # Layer 3 @theme inline 暴露 bg-*/text-*/font-*
└─ package.json
```
**强制规则**project_rules §3.10
- 禁止 `#hex` 字面量ESLint `no-restricted-syntax`
- 禁止 `'Inter'`/`'Fraunces'`/`'JetBrains Mono'` 字面量ESLint `design-tokens/no-hardcoded-fonts`
- 禁止 `font-size: Npx`(用 `var(--font-size-1~9)`
- 禁止 Tailwind 任意值 `w-[Npx]`(用 `--space-*` 或默认阶梯)
**令牌命名**(迁移指南 §7.1
| Layer 1 Primitive | Layer 2 Semantic | Layer 3 Tailwind |
| ------------------ | ------------------ | ---------------- |
| `--color-blue-500` | `--color-accent` | `bg-accent` |
| `--font-size-3` | `--font-size-body` | `text-body` |
| `--space-4` | `--space-md` | `p-md` |
---
# 4 端差异化对比表
## 4.1 整体差异
| 维度 | teacher-portal | student-portal | parent-portal | admin-portal |
| -------------- | -------------------------------------------------------- | -------------- | ------------- | --------------------------- |
| MF 角色 | Shell + Remote | Remote | Remote | Remote |
| 路由前缀 | `/teacher/*` | `/student/*` | `/parent/*` | `/admin/*` |
| 端口dev | 3000 | 3001 | 3002 | 3003 |
| 对接 BFF | teacher-bff | student-bff | parent-bff | teacher-bff 复用 + iam 直连 |
| 默认角色 | teacher / head_teacher / grade_director / subject_leader | student | parent | school_admin / system_admin |
| DataScope 默认 | L1-L5按角色 | L0 | L0 | L3-L5 |
| 推送消费 | ✅ WebSocket | ✅ WebSocket | ✅ WebSocket | ❌ 轮询 |
| AI 辅助 | ✅ 出题/备课/分析 | ❌ | ❌ | ❌ |
| 富文本编辑 | ✅ Tiptap备课/出题/反馈) | ❌ | ❌ | ❌ |
| 多子女切换 | ❌ | ❌ | ✅ | ❌ |
| 用户管理 | ❌ | ❌ | ❌ | ✅ |
| 角色权限配置 | ❌ | ❌ | ❌ | ✅ |
| 平台监控 | ❌ | ❌ | ❌ | ✅ |
## 4.2 L1 导航菜单差异
| 端 | 菜单项(视口) |
| -------------- | -------------------------------------------------------------------------------------------- |
| teacher-portal | Dashboard、班级管理、考试管理、作业管理、成绩查询、备课P5、AI 辅助P5、知识图谱P4 |
| student-portal | Dashboard、我的作业、我的考试、学情诊断P4、错题本P4、通知中心P5 |
| parent-portal | Dashboard、子女切换、成绩查看、作业查看、通知中心P5、通知偏好设置 |
| admin-portal | Dashboard、用户管理、角色管理、权限管理、视口配置、组织管理、平台监控 |
## 4.3 L2 路由表差异
### teacher-portal
| 路由 | 页面 | 权限 |
| ----------------------------- | -------------- | ------------------------ |
| `/teacher/dashboard` | 教师仪表盘 | `TEACHER_DASHBOARD_VIEW` |
| `/teacher/classes` | 班级列表 | `CLASSES_READ` |
| `/teacher/classes/:id` | 班级详情 | `CLASSES_READ` |
| `/teacher/classes/new` | 新建班级 | `CLASSES_CREATE` |
| `/teacher/exams` | 考试列表 | `EXAMS_READ` |
| `/teacher/exams/:id` | 考试详情 | `EXAMS_READ` |
| `/teacher/exams/new` | 新建考试 | `EXAMS_CREATE` |
| `/teacher/homework` | 作业列表 | `HOMEWORK_READ` |
| `/teacher/homework/:id/grade` | 批改作业 | `HOMEWORK_GRADE` |
| `/teacher/grades` | 成绩查询 | `GRADES_READ` |
| `/teacher/lesson-prep` | 备课P5 | `LESSON_PREP_VIEW` |
| `/teacher/ai-assist` | AI 辅助P5 | `AI_GENERATE` |
| `/teacher/knowledge-graph` | 知识图谱P4 | `CONTENT_READ` |
### student-portal
| 路由 | 页面 | 权限 |
| ------------------------------ | -------------- | ------------------------ |
| `/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` | 学情诊断P4 | `DIAGNOSTIC_READ_OWN` |
| `/student/weakness` | 错题本P4 | `WEAKNESS_READ_OWN` |
| `/student/notifications` | 通知中心P5 | `NOTIFICATION_READ_OWN` |
### parent-portal
| 路由 | 页面 | 权限 |
| ----------------------- | -------------- | --------------------------- |
| `/parent/dashboard` | 家长仪表盘 | `PARENT_DASHBOARD_VIEW` |
| `/parent/children` | 子女列表 | `PARENT_CHILDREN_VIEW` |
| `/parent/grades` | 子女成绩 | `GRADES_READ_CHILD` |
| `/parent/homework` | 子女作业 | `HOMEWORK_READ_CHILD` |
| `/parent/notifications` | 通知中心P5 | `NOTIFICATION_READ_OWN` |
| `/parent/preferences` | 通知偏好 | `PARENT_PREFERENCES_UPDATE` |
### admin-portal
| 路由 | 页面 | 权限 |
| --------------------- | ---------- | ----------------------- |
| `/admin/dashboard` | 管理仪表盘 | `ADMIN_DASHBOARD_VIEW` |
| `/admin/users` | 用户管理 | `IAM_USER_READ` |
| `/admin/users/new` | 新建用户 | `IAM_USER_CREATE` |
| `/admin/users/:id` | 用户编辑 | `IAM_USER_UPDATE` |
| `/admin/roles` | 角色管理 | `IAM_ROLE_READ` |
| `/admin/permissions` | 权限管理 | `IAM_PERMISSION_READ` |
| `/admin/viewports` | 视口配置 | `IAM_VIEWPORT_READ` |
| `/admin/organization` | 组织管理 | `ORG_MANAGE` |
| `/admin/monitoring` | 平台监控 | `ADMIN_MONITORING_VIEW` |
## 4.4 L3 组件级差异
| 组件 | teacher | student | parent | admin |
| ---------------------------------- | -------------------- | ------------------ | ------------------ | -------------------- |
| `AppShell`(左栏+主区) | ✅ | ✅(复用 Shell | ✅(复用 Shell | ✅(复用 Shell |
| `RequirePermission` | ✅ | ✅ | ✅ | ✅ |
| `ErrorBoundary` | ✅ | ✅ | ✅ | ✅ |
| `Loading` / `Empty` | ✅ | ✅ | ✅ | ✅ |
| `DataTable` | ✅(班级/考试列表) | ✅(作业列表) | ✅(成绩列表) | ✅(用户列表) |
| `Form` | ✅(创建班级/考试) | ✅(提交作业) | ✅(通知偏好) | ✅(用户/角色 CRUD |
| `Chart` | ✅(班级成绩分布) | ✅(个人学情趋势) | ✅(子女成绩趋势) | ✅(平台监控) |
| `RichTextEditor`Tiptap | ✅(备课/出题/反馈) | ❌ | ❌ | ❌ |
| `ChildSwitcher` | ❌ | ❌ | ✅ | ❌ |
| `ExamTaking`(倒计时+自动保存) | ❌ | ✅ | ❌ | ❌ |
| `SSEViewer`AI 流式) | ✅ | ❌ | ❌ | ❌ |
| `UserManagementTable` | ❌ | ❌ | ❌ | ✅ |
| `RolePermissionMatrix` | ❌ | ❌ | ❌ | ✅ |
| `ViewportConfigEditor` | ❌ | ❌ | ❌ | ✅ |
| `PlatformMonitor`Grafana embed | ❌ | ❌ | ❌ | ✅ |
## 4.5 L4 数据层差异
| 端 | 主要数据来源 | 缓存策略 |
| -------------- | -------------------------------------------------------- | --------------------------------- |
| teacher-portal | teacher-bff聚合 iam + core-edu + content + data-ana | 5-30s 短缓存 |
| student-portal | student-bff聚合 iam + core-edu + data-ana | 5-30s 短缓存,作业列表 30s |
| parent-portal | parent-bff聚合 iam + core-edu + data-ana含子女关联 | 5-30s 短缓存,子女切换 invalidate |
| admin-portal | iam 直连 + teacher-bff 复用 | 5min 长缓存(管理数据低频变) |
---
# 与其他模块的交互点(契约清单)
| 方向 | 对方服务 | 协议 | 接口/事件 | 用途 | 阶段 |
| ------ | ------------ | ------------------ | --------------------------------------------------- | ---------------------------- | ---- |
| 调用 | api-gateway | HTTP/REST | `/api/v1/*` 代理 | 全部业务请求 | P1+ |
| 调用 | push-gateway | WebSocket | `ws://push-gateway/ws` | 实时推送 | P5 |
| 调用 | ai | SSE | `GET /api/v1/ai/generate-questions` | AI 流式出题 | P5 |
| 被调用 | — | — | — | 前端不暴露接口给其他服务 | — |
| 消费 | teacher-bff | HTTP经 Gateway | `GET /teacher/viewports` 等 | 教师场景聚合 | P2+ |
| 消费 | student-bff | HTTP经 Gateway | `GET /student/viewports` 等 | 学生场景聚合 | P3+ |
| 消费 | parent-bff | HTTP经 Gateway | `GET /parent/viewports` 等 | 家长场景聚合 | P4+ |
| 消费 | iam | HTTP经 Gateway | `/iam/*` | 登录/权限/视口/用户管理 | P2+ |
| 消费 | core-edu | HTTP经 Gateway | `/classes/*` `/exams/*` `/homework/*` `/grades/*` | 教学核心 | P2+ |
| 消费 | content | HTTP经 Gateway | `/textbooks/*` `/knowledge-points/*` `/questions/*` | 内容资源 | P4+ |
| 消费 | data-ana | HTTP经 Gateway | `/analytics/*` | 学情分析 | P4+ |
| 消费 | msg | HTTP经 Gateway | `/notifications/*` | 通知中心 | P5+ |
| 依赖 | coord 维护 | — | `packages/shared-proto` | TS 类型(仅 contracts 部分) | P1+ |
| 依赖 | coord 维护 | — | `packages/shared-ts`(待建) | ApiClient/Logger/通用工具 | P2+ |
| 依赖 | ai07 维护 | — | `packages/ui-tokens`(待建) | 三层设计令牌 | P2+ |
| 依赖 | ai07 维护 | — | `packages/ui-components`(待建) | shadcn + 共享组件 | P2+ |
| 依赖 | ai07 维护 | — | `packages/hooks`(待建) | usePermission/useAuth 等 | P2+ |
| 依赖 | coord 维护 | — | `packages/contracts`(待建) | Permissions 常量 + 类型 | P2+ |
> **proto 不直接消费**:前端不调用 gRPCBFF 把 gRPC 聚合为 REST/GraphQL 暴露给前端。前端仅消费 `packages/contracts/src/permissions.ts` 中的权限点常量TS 文件,非 proto 生成)。
---
# 风险与假设
## 8.1 假设
1. **假设 coord 建立 `packages/shared-ts`、`packages/contracts`**:包含 ApiClient、Logger、Permissions 常量、通用类型。若 coord 未建立ai07 自行在 `apps/teacher-portal/src/shared/` 内实现,后续提取到 packages。
2. **假设 ai02 iam 提供 `GET /iam/effective-permissions`**:返回 `{ permissions, viewports, dataScope }`。当前已实现known-issues §2.3 iam
3. **假设 ai03 teacher-bff 提供 `GET /teacher/viewports`**:返回 L1 导航视口。当前已实现。
4. **假设 ai03 core-edu classes 模块维持 `ActionState` 响应结构**:前端 API 请求层依赖此契约。
5. **假设 Next.js 14+ Module Federation 2.0 稳定**`@module-federation/nextjs-mf` 在 Next.js App Router 下可用。若不稳定,降级为 4 端独立部署 + 各自 Shell重复实现 AppShell
## 8.2 技术风险
| 风险 | 影响 | 缓解 |
| ------------------------ | ----------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| MF SSR 对齐复杂 | Remote 在 SSR 时需 Shell 提供上下文 | 优先 CSRSSR 仅用于首屏 dashboardMF 2.0 支持 SSR |
| 共享依赖版本漂移 | Remote 与 Shell 的 react/react-dom 版本不一致导致运行时错误 | MF `shared.singleton: true` + CI 检查版本对齐 |
| Token 刷新竞态 | 多请求同时 401 触发多次 refresh | ApiClient 全局单例 + refresh promise 复用 |
| 权限缓存陈旧 | 角色变更后前端 5min 内仍用旧权限 | iam 角色变更发 Kafka 事件 → msg 推送 WebSocket → 前端 invalidate |
| 设计令牌迁移破坏现有样式 | teacher-portal 现有硬编码令牌迁移到三层模型后样式漂移 | 灰度迁移:先建 ui-tokens 包teacher-portal 引入但不删除旧 globals.css验证后切换 |
| 4 端独立部署运维成本 | 4 个 Next.js 实例 = 4 倍内存 | Shell + 3 Remote 共享 node_modulesMF 运行时共享),实际内存增量 < 2x |
| TanStack Query 缓存膨胀 | 长时间使用后缓存项过多 | `gcTime` 5min + `staleTime` 按数据类型分级 |
## 8.3 未决设计决策(需 coord 仲裁)
1. **packages 归属**`ui-tokens` / `ui-components` / `hooks` 是 ai07 维护还是 coord 维护建议ai07 维护前端专属coord 仅维护 `shared-ts` / `contracts`(跨语言/跨服务)。
2. **GraphQL vs REST**004 §11.3 提到 BFF GraphQL Yoga + DataLoader但当前 teacher-bff 实现为 REST。前端 API 请求层是否需要 GraphQL clienturql/apollo建议P2-P3 用 RESTP4 起若 BFF 切 GraphQL 再引入 urql。
3. **i18n key 命名**`iam.error.IAM_INVALID_CREDENTIALS` 还是 `error.iam.invalid_credentials`?建议:`error.{{service}}.{{code_snake_case}}`,与错误码前缀对齐。
4. **MF 暴露粒度**Shell 暴露整个 AppShell 还是暴露更细粒度的组件Sidebar、Header、Content建议暴露 AppShell 整体 + 各 Remote 自行决定内部布局。
---
# coord 交叉审查所需信息
## 9.1 端口矩阵4 端)
| 端 | dev 端口 | 生产端口 | 备注 |
| -------------- | -------- | -------- | ---------- |
| teacher-portal | 3000 | 3000 | Shell 宿主 |
| student-portal | 3001 | 3001 | Remote |
| parent-portal | 3002 | 3002 | Remote |
| admin-portal | 3003 | 3003 | Remote |
> 与 [full-stack-runbook](../standards/full-stack-runbook.md) 端口矩阵对齐3000-3003 前端3001-3003 已被 Grafana3030/其他服务避让。
## 9.2 依赖的共享包(需 coord 建立)
| 包 | 路径 | 维护方 | 内容 |
| --------------- | ------------------------- | ------------ | ------------------------------------------------- |
| `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 |
## 9.3 依赖的后端契约(需对应 AI 确认)
| 契约 | 提供方 | 当前状态 |
| ------------------------------------------------------------------ | ---------------------------- | ------------------- |
| `POST /iam/login``GET /iam/effective-permissions``GET /iam/me` | ai02 iam | ✅ 已实现 |
| `GET /teacher/viewports``GET /teacher/dashboard` | ai03 teacher-bff | ✅ 已实现 |
| `/classes/*` CRUD | ai03 core-edu | ✅ 已实现 |
| `/exams/*` `/homework/*` `/grades/*` | ai03 core-edu | ✅ 已实现P3 |
| `/textbooks/*` `/knowledge-points/*` `/questions/*` | ai05 content | ✅ 已实现P4 |
| `/analytics/*` | ai06 data-ana | ✅ 已实现P4 CDC |
| `GET /student/viewports` 等 | ai04 student-bff | 📐 待 ai04 设计 |
| `GET /parent/viewports` 等 | ai04 parent-bff | 📐 待 ai04 设计 |
| `/notifications/*` + WebSocket 推送 | ai05 msg + ai01 push-gateway | 📐 待 P5 |
| `GET /ai/generate-questions`SSE | ai06 ai | 📐 待 P5 |
## 9.4 错误码前缀(前端 i18n 路由依赖)
前端不产生错误码,仅消费。需各服务确认错误码前缀不重叠:
| 前缀 | 服务 | 状态 |
| ----------------------------------------------- | ---------------- | -------------------- |
| `IAM_` | iam | ✅ ai02 已用 |
| `CLASSES_` | core-edu/classes | ✅ 已用 |
| `EXAMS_` / `HOMEWORK_` / `GRADES_` | core-edu | ⚠️ 待 ai03 确认 |
| `CONTENT_` | content | ⚠️ 待 ai05 确认 |
| `MSG_` | msg | ⚠️ 待 ai05 确认 |
| `AI_` | ai | ⚠️ 待 ai06 确认 |
| `BFF_TEACHER_` / `BFF_STUDENT_` / `BFF_PARENT_` | 3 BFF | ⚠️ 待 ai03/ai04 确认 |
| `GW_` | api-gateway | ✅ ai01 已用 |
| `NETWORK_` | 前端 | ai07 自有 |
## 9.5 不产生 Kafka 事件
前端不发布/消费 Kafka 事件。WebSocket 推送由 push-gateway 消费 Kafka 转发。
---
# 实施路线ai07 自用)
## P2 收尾teacher-portal 审计对齐)
1.`packages/ui-tokens/`(三层设计令牌)+ `packages/ui-components/`ErrorBoundary/RequirePermission/Loading/Empty+ `packages/hooks/`usePermission/useAuth
2. teacher-portal 引入 TanStack Query + Zustand + nuqs + react-hook-form
3. 抽取 `lib/api.ts` 统一 API 请求层
4. AppShell 改用 `usePermission()`,删除 `user.roles.join(", ")` 硬编码
5. globals.css / tailwind.config.js 迁移到 ui-tokens 三层令牌
6. 引入 next-intl + i18n key 路由
7. 引入 ESLint flat config 自定义规则no-hardcoded-fonts / design-tokens
8. 补 ErrorBoundary + /api/health route
9. 配置 next.config.js Module FederationShell 角色)
10. 补 Vitest 单测 + Playwright E2E覆盖率 ≥ 80%
## P3student-portal
1.`apps/student-portal/`Remote 角色)
2. 配置 MFexposes pagesremotes teacher
3. 实现 Dashboard + 我的作业 + 提交作业 + 我的考试 + 作答考试
4. 复用 Shell 的 AppShell + 共享组件
5. SSE 接入(考试作答自动保存)
## P4parent-portal
1.`apps/parent-portal/`Remote 角色)
2. 实现 Dashboard + 子女切换 + 成绩查看 + 通知偏好
3. 多子女状态管理Zustand slice
## P5推送 + AI 接入)
1. teacher-portal 接入 WebSocketpush-gateway
2. teacher-portal AI 辅助出题SSE + Tiptap
3. student/parent-portal 接入通知推送
## P6admin-portal + 硬化)
1.`apps/admin-portal/`Remote 角色)
2. 实现用户/角色/权限/视口/组织/监控管理
3. Web Vitals + OTel browser SDK 接入
4. A11y WCAG 2.2 AA 审计
5. 性能优化MF shared 单例验证、bundle 分析)
---
**AI Agent**: ai07 (teacher-portal / student-portal / parent-portal / admin-portal)
**Branch**: docs/teacher-portal-stage1-stage2-design-ai07
**Coordinator**: coord-ai

View File

@@ -0,0 +1,205 @@
# 模块理解确认书 — teacher-portal
> AIai07TS/React · 教学场景域前端 shell
> 阶段:阶段 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 ai13/ai07、[pending-features P2](../../../docs/architecture/roadmap/pending-features.md)、[known-issues §2.12](../../../docs/troubleshooting/known-issues.md)
---
## 1. 我在架构中的位置
- **层级**L2 微前端层004 §3.1 六层架构中的前端层)
- **MF 角色****Shell 宿主**(主应用),其余 3 端student/parent/admin-portal作为 Remote 子应用挂载
- **上游(谁调用我)**:浏览器(教师 / 教导主任 / 教研组长)
- **下游(同步)**api-gatewayREST经 Next.js `rewrites` 代理 `/api/v1/*`
- **下游推送P5**push-gatewayWebSocket/SSE
- **BFF 对接**teacher-bffGraphQL Yoga + DataLoaderP2-P3 用 REST 过渡)
- **通信方式**HTTP/REST前端→Gateway+ WebSocket前端→push-gatewayP5
- **不直连**:前端不直连任何业务服务或 BFF 后端实例,全部经 api-gateway 代理
**说明**
- 通过 `next.config.js``rewrites``/api/v1/*` 代理到 `api-gateway`
- MF 架构下teacher-portal 作为 Shell 宿主提供 AppShell + 共享组件库 + 权限 Hook + API 请求层
- 场景域 BFF 复用策略004 §5.4):教导主任/教研组长复用 teacher-portal + 额外管理视口,不单独建 portal
## 2. 我的限界上下文
### 2.1 我负责的聚合 / 实体(前端视图模型)
- 班级、考试、作业、成绩、备课、AI 出题(教学场景域前端视图)
- 会话状态Session、视口Viewport、权限Permission
### 2.2 业务领域
- **D3 教学核心领域**(前端场景域:教学场景域)
### 2.3 不负责
- 学生作答界面(归 student-portal
- 家长多子女切换(归 parent-portal
- 用户/角色/权限 CRUD归 admin-portal
### 2.4 数据范围
- DataScope L1-L5教师 L1 班级 / 教导主任 L2 年级 / 校管理员 L3 学校 / 区教研员 L4 / 系统管理员 L5
## 3. 我与外部的契约
### 3.1 消费的后端 API经 api-gateway 代理)
| 路径前缀 | 下游 BFF/服务 | 关键端点 |
| ------------------------------------------------------------------------ | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/api/v1/iam/*` | iam | `POST /iam/login``POST /iam/register``POST /iam/refresh``GET /iam/me``GET /iam/rbac/...``GET /iam/effective-permissions` |
| `/api/v1/teacher/*` | teacher-bff | `GET /teacher/viewports``GET /teacher/dashboard``GET /teacher/classes/:id/exams``GET /teacher/classes/:id/homework``GET /teacher/exams/:id/grades` |
| `/api/v1/classes/*` | core-educlasses 模块) | CRUD黄金模板 |
| `/api/v1/exams/*` `/api/v1/homework/*` `/api/v1/grades/*` | core-edu | P3 教学核心 |
| `/api/v1/textbooks/*` `/api/v1/knowledge-points/*` `/api/v1/questions/*` | content | P4 内容 |
| `/api/v1/ai/*` | aiSSE 流式) | P5 AI 辅助出题 |
| `/api/v1/notifications/*` | msg | 通知中心P5 |
### 3.2 统一响应契约
所有后端响应遵循 `ActionState` 结构(迁移指南 §7.5
```typescript
type ActionState<T> =
| { success: true; data: T }
| {
success: false;
error: { code: string; message: string; details?: unknown };
};
```
错误码前缀按服务名大写(如 `IAM_``CORE_EDU_``CONTENT_``MSG_``AI_``BFF_TEACHER_``GW_`)。前端 API 请求层根据 `error.code` 前缀路由到对应的 i18n key。
### 3.3 推送契约P5
| 协议 | 场景 |
| ------------------------- | -------------------------------------------- |
| WebSocketpush-gateway | 学生提交作业通知、考试成绩录入提醒、全校广播 |
| SSEai 服务) | AI 辅助出题流式响应 |
### 3.4 proto 不直接消费
前端不调用 gRPCBFF 把 gRPC 聚合为 REST/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 | teacher-portal = Shell |
| 样式 | Tailwind CSS 3.4+ | 配合设计令牌三层模型 |
| UI 组件库 | shadcn/ui迁移指南 §7.2 | 平移至 `packages/ui-components/`MF 共享 |
| 状态管理 L1 URL | nuqs | 可分享、可刷新状态 |
| 状态管理 L2 Server | TanStack Query v5 | 服务端数据缓存、重试、乐观更新 |
| 状态管理 L3 Client Business | Zustand slice | 客户端业务状态 |
| 状态管理 L4 Global UI | Zustand ui-store + ModalRoot | 全局 UI 状态 |
| 状态管理 L5 Form | react-hook-form + zodResolver | 表单状态 |
| 富文本 | Tiptap备课、出题、反馈 | SSR 安全 |
| 图表 | recharts | 学情、Dashboard |
| i18n | next-intl | BFF/服务返回 i18n key + 参数,前端翻译 |
| A11y | eslint-plugin-jsx-a11yerror 级) | WCAG 2.2 AA |
| 字体 | Intersans/ Frauncesserif/ JetBrains Monomono | next/font/google 加载CSS 变量暴露 |
## 5. 我的阶段归属
- **阶段**P2
- **当前状态**:✅ 已实现 P1 测试页 + P2 骨架(登录/AppShell/Dashboard/classes CRUD 待审计对齐黄金模板 + 引入 MF + 共享组件库
- **依赖上游阶段**P1api-gateway + classes + iam
## 6. 我需要对齐的黄金模板项(对照 classes 服务)
> 前端无 `@RequirePermission` 装饰器(后端概念),对齐项改造为前端等价物。
| 对齐项 | classes后端黄金模板 | teacher-portal 前端等价 | 当前状态 |
| --------------------- | ------------------------------------- | ------------------------------------------------------------------------ | -------------------------------------------- |
| 权限校验 | `@RequirePermission(Permissions.XXX)` | `usePermission().hasPermission("XXX")` Hook + `<RequirePermission>` 组件 | ❌ 缺失,直接硬编码 `user.roles.join(", ")` |
| 错误码前缀统一 | `CLASSES_*``IAM_*` | API 请求层根据 `error.code` 前缀路由 i18n | ❌ 缺失统一请求层 |
| logger | pino | 前端 console + SentryP6 | ⚠️ 仅 console.error |
| metrics | prom-client `/metrics` | 前端 Web Vitals → Gateway 上报 | ❌ 缺失 |
| tracer | OTel SDK | 前端 OTel browser SDKP6 | ❌ 缺失 |
| /healthz + /readyz | `GET /healthz` `GET /readyz` | Next.js `/api/health` route + Dockerfile HEALTHCHECK | ⚠️ Dockerfile 有 HEALTHCHECK无 /api/health |
| 优雅关闭 | SIGTERM handler | Next.js 无长连接,无需 | ✅ N/A |
| 测试覆盖率 ≥ 80% | Vitest | Vitest + @testing-library/react + Playwright E2E | ❌ 0% |
| Dockerfile 多阶段构建 | builder + runtime | 已有多阶段 | ✅ 已对齐 |
| Zod 输入验证 | class-validator + Zod schema | react-hook-form + zodResolver | ❌ 缺失 |
| GlobalErrorFilter | NestJS 全局异常过滤器 | React ErrorBoundary + API 请求层统一错误处理 | ❌ 缺失 |
| 设计令牌三层 | — | primitive.css / semantic-light/dark.css / tailwind-theme.css | ❌ 硬编码在 globals.css + tailwind.config.js |
| A11y 工具集 | — | useA11yId / mergeA11yProps / describeInput / focus-trap | ❌ 缺失 |
---
## 附teacher-portal 现状审计(对齐黄金模板)
### 审计表
| 维度 | 状态 | 说明 |
| ------------------------------------ | ------ | ---------------------------------------------------------------------- |
| 权限装饰器(前端等价 usePermission | ❌ | AppShell.tsx 直接 `user.roles.join(", ")`,违反 project_rules §3.8 |
| 错误码前缀 | ❌ | 无统一 API 请求层,错误处理散落在每个 page.tsx |
| logger | ⚠️ | 仅 `console.error`,无结构化、无 trace_id |
| metrics | ❌ | 无 Web Vitals 采集 |
| tracer | ❌ | 无 OTel browser SDK |
| /healthz | ⚠️ | Dockerfile 有 `HEALTHCHECK wget /`,但无 `/api/health` route |
| /readyz | ❌ | 无 |
| 优雅关闭 | ✅ N/A | Next.js 无长连接 |
| 测试覆盖率 | ❌ | 0%,无测试文件 |
| Dockerfile 多阶段 | ✅ | builder + runtime非 root 用户HEALTHCHECK |
| Zod 输入验证 | ❌ | 表单直接 useState无 zodResolver |
| GlobalErrorFilterErrorBoundary | ❌ | 无 React ErrorBoundary |
| 设计令牌三层 | ❌ | 硬编码在 globals.css`:root` 变量)+ tailwind.config.jshex 字面量) |
| A11y 工具集 | ❌ | 无 useA11yId、focus-trap 等 |
| Module Federation 配置 | ❌ | next.config.js 仅有 rewrites无 MF |
| 5 层状态管理 | ❌ | 仅 useState + localStorage无 nuqs/TanStack Query/Zustand |
| 共享组件库 | ❌ | 仅 AppShell无 ErrorBoundary/Loading/Empty/RequirePermission |
| i18n | ❌ | 中文硬编码在 JSX |
| API 请求层 | ❌ | 每页重复 fetch + authHeaders + try/catch |
| ESLint flat config 自定义规则 | ❌ | 未配置 no-hardcoded-fonts / design-tokens 规则 |
### 现有文件清单
```
apps/teacher-portal/
├─ src/
│ ├─ app/
│ │ ├─ (app)/ # 受保护路由组(套 AppShell
│ │ │ ├─ classes/page.tsx # 班级 CRUDP1 测试页)
│ │ │ ├─ dashboard/page.tsx # 教师仪表盘
│ │ │ ├─ exams/page.tsx # 考试列表
│ │ │ ├─ grades/page.tsx # 成绩查询
│ │ │ ├─ homework/page.tsx # 作业列表
│ │ │ └─ layout.tsx # 套 AppShell
│ │ ├─ login/page.tsx # 登录页(不套壳)
│ │ ├─ globals.css # 全局样式 + 设计令牌(硬编码)
│ │ ├─ layout.tsx # 根布局(字体加载)
│ │ └─ page.tsx # 根路径重定向
│ ├─ components/
│ │ └─ AppShell.tsx # 左侧栏 + 主内容区
│ └─ lib/
│ └─ auth.ts # token + userInfo localStorage 管理
├─ Dockerfile # 多阶段构建 ✅
├─ next.config.js # 仅 rewrites无 MF ❌
├─ package.json # 仅 next/react/react-dom无 MF/Query/Zustand ❌
├─ tailwind.config.js # 硬编码 hex ❌
├─ postcss.config.js
└─ tsconfig.json
```
### 主要违规点(必须在 P2 收尾或 P3 起步时修复)
1. **权限硬编码**[AppShell.tsx:143](../src/components/AppShell.tsx) `user.roles.join(", ")` 违反 project_rules §3.8,必须改为 `usePermission().hasPermission()`
2. **设计令牌硬编码**[globals.css:6-13](../src/app/globals.css) 与 [tailwind.config.js:7-19](../tailwind.config.js) 出现 `hsl(...)` 字面量与 `'Fraunces'`/`'Inter'` 字面量,违反 project_rules §3.10
3. **无统一 API 请求层**4 个 page.tsx 重复 `authHeaders()` + `fetch` + `try/catch` + `setError`,必须抽取到 `lib/api.ts`
4. **无权限 Hook**:缺少 `usePermission().hasPermission()`,无法做 L3 组件级视口控制
5. **无 ErrorBoundary**React 渲染异常会白屏
6. **无 5 层状态管理**:登录态用 localStorageL3但无 TanStack QueryL2导致每页重复 fetch
7. **字体名硬编码**[layout.tsx:3-7](../src/app/layout.tsx) 直接 import `Inter/Fraunces/JetBrains_Mono`,应改为 `var(--font-family-sans/serif/mono)`
---
**AI Agent**: ai07 (teacher-portal shell)
**Branch**: docs/teacher-portal-stage1-stage2-design-ai07

View File

@@ -0,0 +1,562 @@
# 模块架构设计文档 — teacher-portal
> AIai07TS/React · 教学场景域前端 shell
> 阶段:阶段 2 交付物
> 日期2026-07-09
> 关联:[阶段 1 理解确认书](./01-understanding.md)、[004 架构影响地图](../../../docs/architecture/004_architecture_impact_map.md) §5.4、[pending-features P2](../../../docs/architecture/roadmap/pending-features.md)
> 状态:待 coord 交叉审查
---
## 1. 模块内部分层图4 端统一 MF 架构)
```mermaid
graph TB
subgraph Browser["浏览器"]
URL[URL 路由]
end
subgraph Shell["teacher-portalShell 宿主)"]
AppShell[AppShell<br/>左栏导航 + 主内容区]
RootLayout[RootLayout<br/>字体/令牌/i18n Provider]
Router[Next.js App Router]
SharedDeps["共享依赖暴露<br/>react/react-dom/@tanstack/react-query/zustand/nuqs"]
end
subgraph RemoteTeacher["teacher-portal Remote 模块"]
TeacherPages[教学场景页面<br/>dashboard/classes/exams/homework/grades/ai-assist]
end
subgraph RemoteStudent["student-portalRemote"]
StudentPages[学习场景页面<br/>dashboard/homework/submit/diagnostic/exam-taking]
end
subgraph RemoteParent["parent-portalRemote"]
ParentPages[家长场景页面<br/>dashboard/children-switch/grades/notifications]
end
subgraph RemoteAdmin["admin-portalRemote"]
AdminPages[管理场景页面<br/>users/roles/permissions/viewports/monitoring]
end
subgraph Shared["共享层packages/"]
UITokens[ui-tokens<br/>三层设计令牌]
UIComponents[ui-components<br/>shadcn + A11y + ErrorBoundary]
Contracts[contracts<br/>Permissions 常量 + 类型]
Hooks[hooks<br/>usePermission/useAuth/useA11y]
LibTS[shared-ts<br/>通用工具]
end
subgraph Gateway["api-gateway"]
GW[Gin 路由/鉴权/限流]
end
Browser --> URL
URL --> RootLayout
RootLayout --> AppShell
AppShell --> Router
Router -->|动态加载| RemoteTeacher
Router -->|动态加载| RemoteStudent
Router -->|动态加载| RemoteParent
Router -->|动态加载| RemoteAdmin
RemoteTeacher --> SharedDeps
RemoteStudent --> SharedDeps
RemoteParent --> SharedDeps
RemoteAdmin --> SharedDeps
Shell --> UITokens
Shell --> UIComponents
Shell --> Contracts
Shell --> Hooks
RemoteTeacher --> UITokens
RemoteStudent --> UITokens
RemoteParent --> UITokens
RemoteAdmin --> UITokens
AppShell -->|fetch /api/v1/iam/effective-permissions| Hooks
Hooks -->|透传 token| GW
RemoteTeacher -->|fetch /api/v1/teacher/*| GW
RemoteStudent -->|fetch /api/v1/student/*| GW
RemoteParent -->|fetch /api/v1/parent/*| GW
RemoteAdmin -->|fetch /api/v1/iam/* + /api/v1/admin/*| GW
```
### 1.1 MF 拓扑选型
| 方案 | 选否 | 理由 |
| ------------------------------------ | ---- | --------------------------------------------------------------------------------------- |
| 4 端独立部署 + 独立域名 + 各自 Shell | ❌ | 4 套 Shell 重复,登录态/权限/组件库要重复实现 |
| 单 Shell + 4 Remote**采用** | ✅ | teacher-portal 作为 Shell 宿主,提供 AppShell + 共享依赖;其余 3 端作为 Remote 动态加载 |
| 单一 Next.js 应用 + 4 路由组 | ❌ | 违反"微前端独立部署"目标ADR-012 |
**Shell 职责**teacher-portal
- RootLayout字体、设计令牌、i18n Provider、TanStack QueryClientProvider、Zustand StoreProvider
- AppShell左侧导航 + 主内容区 + 用户信息 + 登出)
- 共享依赖暴露react、react-dom、@tanstack/react-query、zustand、nuqs、ui-components、ui-tokens、contracts、hooks
- 路由表4 端路由前缀:`/teacher/*``/student/*``/parent/*``/admin/*`
- 登录页(统一登录入口,按角色重定向到对应 portal
### 1.2 MF 配置teacher-portal/next.config.js
```javascript
// teacher-portal/next.config.jsShell
const NextFederationPlugin = require("@module-federation/nextjs-mf");
const remotes = (isServer) => ({
student: `student_app@http://localhost:3001/_next/static/${isServer ? "ssr" : "chunks"}/remoteEntry.js`,
parent: `parent_app@http://localhost:3002/_next/static/${isServer ? "ssr" : "chunks"}/remoteEntry.js`,
admin: `admin_app@http://localhost:3003/_next/static/${isServer ? "ssr" : "chunks"}/remoteEntry.js`,
});
module.exports = {
reactStrictMode: true,
webpack(config, { isServer }) {
config.plugins.push(
new NextFederationPlugin({
name: "teacher_app",
filename: "static/chunks/remoteEntry.js",
remotes: remotes(isServer),
exposes: {
"./AppShell": "./src/components/AppShell",
"./shared-deps": "./src/shared/deps",
},
shared: {
react: { singleton: true, requiredVersion: "^18.3.0" },
"react-dom": { singleton: true, requiredVersion: "^18.3.0" },
"@tanstack/react-query": { singleton: true },
zustand: { singleton: true },
nuqs: { 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*`,
},
];
},
};
```
> Remote 端配置对称:`name: 'student_app'``exposes: { './pages': './src/pages' }``remotes: { teacher: 'teacher_app@...' }`。
## 2. 领域模型(前端视角)
前端不持有业务聚合根,仅持有"视图模型"ViewModel和"会话状态"。
### 2.1 会话状态Session
```typescript
interface Session {
user: UserInfo; // { id, email, name, roles, permissions, dataScope }
tokens: { accessToken: string; refreshToken: string };
viewports: ViewportItem[]; // L1 导航视口
expiresAt: number; // access token 过期时间戳
}
```
存储Zustand sessionSliceL3+ localStorage 持久化(刷新恢复)+ TanStack Query 缓存 `['session']`L2
### 2.2 视口模型Viewport
```typescript
interface ViewportItem {
key: string; // 'dashboard' | 'classes' | ...
label: string; // i18n key 或显式文案
route: string; // '/teacher/dashboard'
icon: string | null; // 图标 key按需
sortOrder: number; // 排序
requiredPermission: string | null; // 'CLASSES_READ' 等
scope: "teacher" | "student" | "parent" | "admin"; // 标记归属哪个 portal
}
```
来源:`GET /api/v1/{scope}/viewports`BFF 聚合 iam 视口配置。AppShell 按 `scope` 过滤渲染对应 portal 的导航。
### 2.3 权限模型Permission
```typescript
interface PermissionState {
permissions: string[]; // ['CLASSES_READ', 'EXAMS_CREATE', ...]
dataScope: DataScope; // L0-L5
hasPermission: (perm: string) => boolean;
hasAnyPermission: (perms: string[]) => boolean;
hasAllPermissions: (perms: string[]) => boolean;
}
```
来源:`GET /api/v1/iam/effective-permissions``{ permissions, viewports, dataScope }`。Redis 缓存 5miniam 侧),前端 TanStack Query 缓存 5min角色变更主动 invalidate。
## 3. 数据模型(前端)
前端无数据库,仅有缓存层:
| 数据类型 | 存储 | TTL | 失效策略 |
| ----------------------- | ---------------------- | --------------------------- | -------------------------------------- |
| Sessiontoken + user | localStorage + Zustand | access 15min / refresh 7day | 401 自动 refreshrefresh 失败跳登录 |
| 权限列表 | TanStack Query cache | 5min | 角色变更事件 invalidate |
| 视口列表 | TanStack Query cache | 5min | 同上 |
| 班级/年级列表 | TanStack Query cache | 5min | staleTime 5minmutation 后 invalidate |
| 教学资源详情 | TanStack Query cache | 30s | staleTime 30s |
| 学情宽表 | TanStack Query cache | 30s | staleTime 30s实时性由 BFF 决定) |
| URL 状态(分页/筛选) | nuqs | — | 永久(可分享) |
| 表单临时态 | react-hook-form | — | 卸载即销毁 |
## 4. API 设计(前端 → 后端)
前端不设计后端 API仅声明消费的端点。详见 [01-understanding.md §3.1](./01-understanding.md)。
### 4.1 统一 API 请求层lib/api.ts
```typescript
// packages/shared-ts/src/api-client.ts共享
interface ApiClientOptions {
baseUrl?: string; // 默认 ''(走 Next.js rewrites
getToken?: () => string | null;
onUnauthorized?: () => void; // 401 → refresh → 重试 / 跳登录
onError?: (error: ApiError) => void; // 全局 toast
}
class ApiClient {
async get<T>(path: string, query?: Record<string, string>): Promise<T>;
async post<T>(path: string, body: unknown): Promise<T>;
async put<T>(path: string, body: unknown): Promise<T>;
async delete<T>(path: string): Promise<T>;
async sse<T>(path: string, body: unknown): AsyncIterable<T>; // AI 流式
}
// 错误结构
interface ApiError {
code: string; // 'IAM_INVALID_CREDENTIALS'
message: string; // 已 i18n 翻译或后端原文
details?: unknown;
httpStatus: number;
}
```
**职责**
- 自动注入 `Authorization: Bearer ${token}`
- 401 自动 refresh token 一次,失败调 `onUnauthorized`
- 解析 `ActionState`success=false 抛 `ApiError`
-`error.code` 前缀路由 i18n key
- 全局错误 toast除 401
- 请求/响应 trace_id 透传(从响应头 `X-Request-Id` 提取)
### 4.2 TanStack Query 约定
```typescript
// Query Key 命名:[scope, resource, ...args]
queryKey: ["teacher", "classes", { gradeId }];
queryKey: ["teacher", "exams", classId];
queryKey: ["session", "effective-permissions"];
queryKey: ["session", "viewports", "teacher"];
// Mutation 约定
const mutation = useMutation({
mutationFn: (input) => api.post("/api/v1/classes", input),
onSuccess: () =>
queryClient.invalidateQueries({ queryKey: ["teacher", "classes"] }),
onError: (e: ApiError) => toast.error(e.message),
});
```
## 5. 事件设计
前端不发布 Kafka 事件,仅消费 WebSocket 推送P5和 Server-Sent EventsAI 流式)。
### 5.1 WebSocket 推送P5
| 事件 | 触发 | teacher-portal 前端动作 |
| ----------------------- | ------------ | ------------------------------- |
| `NotificationRequested` | msg 服务投递 | toast 提示 + 通知中心未读数 +1 |
| `HomeworkSubmitted` | 学生提交作业 | toast + 作业批改列表 invalidate |
### 5.2 SSE 流式P5 AI 辅助出题)
```
GET /api/v1/ai/generate-questions (SSE)
data: {"delta": "题目"}\n\n
data: {"delta": "A. option1"}\n\n
data: {"done": true}\n\n
```
前端用 `AsyncIterable<T>` 消费Tiptap 逐字插入。
## 6. 横切关注点对齐清单
### 6.1 权限(前端等价)
| 路由 | requiredPermission |
| ----------------------------- | ------------------------ |
| `/teacher/dashboard` | `TEACHER_DASHBOARD_VIEW` |
| `/teacher/classes` | `CLASSES_READ` |
| `/teacher/classes/new` | `CLASSES_CREATE` |
| `/teacher/exams` | `EXAMS_READ` |
| `/teacher/exams/new` | `EXAMS_CREATE` |
| `/teacher/homework` | `HOMEWORK_READ` |
| `/teacher/homework/:id/grade` | `HOMEWORK_GRADE` |
| `/teacher/grades` | `GRADES_READ` |
| `/teacher/ai-assist` | `AI_GENERATE` |
| `/teacher/lesson-prep` | `LESSON_PREP_VIEW` |
| `/teacher/knowledge-graph` | `CONTENT_READ` |
> 完整权限点常量集中在 `packages/contracts/src/permissions.ts`待建立coord 负责 shared-tsai07 负责调用。L3 组件级视口用 `<RequirePermission perm="EXAMS_CREATE"><Button>新建考试</Button></RequirePermission>`。
### 6.2 错误码清单(前端 i18n 路由)
| 前缀 | 来源服务 | i18n key 模式 |
| -------------- | ----------- | ------------------------ |
| `IAM_` | iam | `iam.error.{{code}}` |
| `CORE_EDU_` | core-edu | `coreEdu.error.{{code}}` |
| `CLASSES_` | core-edu | `classes.error.{{code}}` |
| `CONTENT_` | content | `content.error.{{code}}` |
| `MSG_` | msg | `msg.error.{{code}}` |
| `AI_` | ai | `ai.error.{{code}}` |
| `BFF_TEACHER_` | teacher-bff | `bff.error.{{code}}` |
| `GW_` | api-gateway | `gateway.error.{{code}}` |
| `NETWORK_` | 前端网络层 | `network.error.{{code}}` |
### 6.3 Logger
```typescript
// packages/shared-ts/src/logger.ts
interface Logger {
info(msg: string, meta?: Record<string, unknown>): void;
warn(msg: string, meta?: Record<string, unknown>): void;
error(msg: string, meta?: Record<string, unknown>): void;
}
// 实现:开发环境 console + 结构化;生产环境 → SentryP6
// 必含字段trace_id从响应头提取、user_id、scope、path
```
### 6.4 MetricsWeb Vitals
| 指标 | 类型 | 上报 |
| ----------------------------- | ---- | --------------------------------------------------- |
| `teacher_portal_lcp_seconds` | LCP | `next/web-vitals``POST /api/v1/admin/web-vitals` |
| `teacher_portal_cls` | CLS | 同上 |
| `teacher_portal_fid_seconds` | FID | 同上 |
| `teacher_portal_ttfb_seconds` | TTFB | 同上 |
P6 接入P2-P5 暂缓。
### 6.5 TracerOTel browser SDKP6
```typescript
// packages/shared-ts/src/tracer.ts
import { WebTracerProvider } from "@opentelemetry/sdk-trace-web";
// BatchSpanProcessor → OTLP exporter → collector → Tempo
// 自动埋点fetch、XMLHttpRequest、document load、user interaction
```
### 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` 可达 + 内存 < 阈值 |
### 6.7 优雅关闭
Next.js 无长连接(除 SSE/WS无需特殊处理。SSE/WS 在 P5 由 push-gateway 管理,前端断线自动重连。
## 7. 共享组件库packages/ui-components/待建立ai07 维护)
| 组件 | 用途 | 来源 |
| ------------------------------------------ | --------------------------------------------------------------------------------------------------- | ------------------------------ |
| `AppShell` | 左侧栏 + 主内容区布局 | teacher-portal 现有 → 抽取共享 |
| `RequirePermission` | L3 组件级视口控制(无权限不渲染 children | 新建 |
| `ErrorBoundary` | React 渲染异常兜底fallback UI | 新建 |
| `Loading` | 骨架屏Skeleton | 新建 |
| `Empty` | 空态(插画 + 文案 + CTA | 新建 |
| `Modal` / `Dialog` | 全局 ModalModalRoot + Zustand ui-store | shadcn/ui |
| `Toast` | 全局 toast错误/成功/警告) | shadcn/ui sonner |
| `Button` / `Input` / `Select` / `Textarea` | 基础表单 | shadcn/ui |
| `DataTable` | 表格(排序/分页/筛选) | shadcn/ui + TanStack Table |
| `Chart` | 图表封装recharts | 新建 |
| `A11y` 工具集 | useA11yId / mergeA11yProps / describeInput / focus-trap / skip-link / visually-hidden / aria-status | 迁移指南 §7.7 |
| `Form` | react-hook-form + zodResolver 封装 | 新建 |
| `RichTextEditor` | Tiptap 封装(备课/出题/反馈) | 新建 |
## 8. 共享 Hookspackages/hooks/待建立ai07 维护)
| Hook | 职责 |
| --------------------- | --------------------------------------------------- |
| `useAuth()` | 会话状态user/token/refresh/login/logout |
| `usePermission()` | 权限查询hasPermission/hasAny/hasAll + dataScope |
| `useViewports(scope)` | 视口列表(按 scope 过滤) |
| `useApi()` | ApiClient 实例(注入 token + 401 处理) |
| `useA11yId()` | 唯一 ARIA ID 生成 |
| `useAriaLive()` | aria-live 区域管理 |
| `useToast()` | 全局 toastZustand ui-store |
## 9. 设计令牌三层packages/ui-tokens/待建立ai07 维护)
```
packages/ui-tokens/
├─ primitive.css # Layer 1 原始色板/字号/间距/阴影
├─ semantic-light.css # Layer 2 语义令牌(亮色)
├─ semantic-dark.css # Layer 2 语义令牌(暗色)
├─ tailwind-theme.css # Layer 3 @theme inline 暴露 bg-*/text-*/font-*
└─ package.json
```
**强制规则**project_rules §3.10
- 禁止 `#hex` 字面量ESLint `no-restricted-syntax`
- 禁止 `'Inter'`/`'Fraunces'`/`'JetBrains Mono'` 字面量ESLint `design-tokens/no-hardcoded-fonts`
- 禁止 `font-size: Npx`(用 `var(--font-size-1~9)`
- 禁止 Tailwind 任意值 `w-[Npx]`(用 `--space-*` 或默认阶梯)
**令牌命名**(迁移指南 §7.1
| Layer 1 Primitive | Layer 2 Semantic | Layer 3 Tailwind |
| ------------------ | ------------------ | ---------------- |
| `--color-blue-500` | `--color-accent` | `bg-accent` |
| `--font-size-3` | `--font-size-body` | `text-body` |
| `--space-4` | `--space-md` | `p-md` |
## 10. 与其他模块的交互点(契约清单)
| 方向 | 对方服务 | 协议 | 接口/事件 | 用途 | 阶段 |
| ------ | ------------ | ------------------ | --------------------------------------------------- | ---------------------------- | ---- |
| 调用 | api-gateway | HTTP/REST | `/api/v1/*` 代理 | 全部业务请求 | P1+ |
| 调用 | push-gateway | WebSocket | `ws://push-gateway/ws` | 实时推送 | P5 |
| 调用 | ai | SSE | `GET /api/v1/ai/generate-questions` | AI 流式出题 | P5 |
| 被调用 | — | — | — | 前端不暴露接口给其他服务 | — |
| 消费 | teacher-bff | HTTP经 Gateway | `GET /teacher/viewports` 等 | 教师场景聚合 | P2+ |
| 消费 | iam | HTTP经 Gateway | `/iam/*` | 登录/权限/视口/用户管理 | P2+ |
| 消费 | core-edu | HTTP经 Gateway | `/classes/*` `/exams/*` `/homework/*` `/grades/*` | 教学核心 | P2+ |
| 消费 | content | HTTP经 Gateway | `/textbooks/*` `/knowledge-points/*` `/questions/*` | 内容资源 | P4+ |
| 消费 | data-ana | HTTP经 Gateway | `/analytics/*` | 学情分析 | P4+ |
| 消费 | msg | HTTP经 Gateway | `/notifications/*` | 通知中心 | P5+ |
| 依赖 | coord 维护 | — | `packages/shared-proto` | TS 类型(仅 contracts 部分) | P1+ |
| 依赖 | coord 维护 | — | `packages/shared-ts`(待建) | ApiClient/Logger/通用工具 | P2+ |
| 依赖 | ai07 维护 | — | `packages/ui-tokens`(待建) | 三层设计令牌 | P2+ |
| 依赖 | ai07 维护 | — | `packages/ui-components`(待建) | shadcn + 共享组件 | P2+ |
| 依赖 | ai07 维护 | — | `packages/hooks`(待建) | usePermission/useAuth 等 | P2+ |
| 依赖 | coord 维护 | — | `packages/contracts`(待建) | Permissions 常量 + 类型 | P2+ |
> **proto 不直接消费**:前端不调用 gRPCBFF 把 gRPC 聚合为 REST/GraphQL 暴露给前端。前端仅消费 `packages/contracts/src/permissions.ts` 中的权限点常量TS 文件,非 proto 生成)。
## 11. 风险与假设
### 11.1 假设
1. **假设 coord 建立 `packages/shared-ts`、`packages/contracts`**:包含 ApiClient、Logger、Permissions 常量、通用类型。若 coord 未建立ai07 自行在 `apps/teacher-portal/src/shared/` 内实现,后续提取到 packages。
2. **假设 iam 提供 `GET /iam/effective-permissions`**:返回 `{ permissions, viewports, dataScope }`。当前已实现known-issues §2.3 iam
3. **假设 teacher-bff 提供 `GET /teacher/viewports`**:返回 L1 导航视口。当前已实现。
4. **假设 core-edu classes 模块维持 `ActionState` 响应结构**:前端 API 请求层依赖此契约。
5. **假设 Next.js 14+ Module Federation 2.0 稳定**`@module-federation/nextjs-mf` 在 Next.js App Router 下可用。若不稳定,降级为 4 端独立部署 + 各自 Shell重复实现 AppShell
### 11.2 技术风险
| 风险 | 影响 | 缓解 |
| ------------------------ | ----------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| MF SSR 对齐复杂 | Remote 在 SSR 时需 Shell 提供上下文 | 优先 CSRSSR 仅用于首屏 dashboardMF 2.0 支持 SSR |
| 共享依赖版本漂移 | Remote 与 Shell 的 react/react-dom 版本不一致导致运行时错误 | MF `shared.singleton: true` + CI 检查版本对齐 |
| Token 刷新竞态 | 多请求同时 401 触发多次 refresh | ApiClient 全局单例 + refresh promise 复用 |
| 权限缓存陈旧 | 角色变更后前端 5min 内仍用旧权限 | iam 角色变更发 Kafka 事件 → msg 推送 WebSocket → 前端 invalidate |
| 设计令牌迁移破坏现有样式 | teacher-portal 现有硬编码令牌迁移到三层模型后样式漂移 | 灰度迁移:先建 ui-tokens 包teacher-portal 引入但不删除旧 globals.css验证后切换 |
| TanStack Query 缓存膨胀 | 长时间使用后缓存项过多 | `gcTime` 5min + `staleTime` 按数据类型分级 |
### 11.3 未决设计决策(需 coord 仲裁)
1. **packages 归属**`ui-tokens` / `ui-components` / `hooks` 是 ai07 维护还是 coord 维护建议ai07 维护前端专属coord 仅维护 `shared-ts` / `contracts`(跨语言/跨服务)。
2. **GraphQL vs REST**004 §11.3 提到 BFF GraphQL Yoga + DataLoader但当前 teacher-bff 实现为 REST。前端 API 请求层是否需要 GraphQL clienturql/apollo建议P2-P3 用 RESTP4 起若 BFF 切 GraphQL 再引入 urql。
3. **i18n key 命名**`iam.error.IAM_INVALID_CREDENTIALS` 还是 `error.iam.invalid_credentials`?建议:`error.{{service}}.{{code_snake_case}}`,与错误码前缀对齐。
4. **MF 暴露粒度**Shell 暴露整个 AppShell 还是暴露更细粒度的组件Sidebar、Header、Content建议暴露 AppShell 整体 + 各 Remote 自行决定内部布局。
## 12. coord 交叉审查所需信息
### 12.1 端口矩阵
| 端 | dev 端口 | 生产端口 | 备注 |
| -------------- | -------- | -------- | ---------- |
| teacher-portal | 3000 | 3000 | Shell 宿主 |
> 与 [full-stack-runbook](../../../docs/standards/full-stack-runbook.md) 端口矩阵对齐。
### 12.2 依赖的共享包(需 coord 建立)
| 包 | 路径 | 维护方 | 内容 |
| --------------- | ------------------------- | ------------ | ------------------------------------------------- |
| `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 |
### 12.3 依赖的后端契约(需对应 AI 确认)
| 契约 | 提供方 | 当前状态 |
| ------------------------------------------------------------------ | ------------------ | ------------------- |
| `POST /iam/login``GET /iam/effective-permissions``GET /iam/me` | iam | ✅ 已实现 |
| `GET /teacher/viewports``GET /teacher/dashboard` | teacher-bff | ✅ 已实现 |
| `/classes/*` CRUD | core-edu | ✅ 已实现 |
| `/exams/*` `/homework/*` `/grades/*` | core-edu | ✅ 已实现P3 |
| `/textbooks/*` `/knowledge-points/*` `/questions/*` | content | ✅ 已实现P4 |
| `/analytics/*` | data-ana | ✅ 已实现P4 CDC |
| `/notifications/*` + WebSocket 推送 | msg + push-gateway | 📐 待 P5 |
| `GET /ai/generate-questions`SSE | ai | 📐 待 P5 |
### 12.4 错误码前缀(前端 i18n 路由依赖)
前端不产生错误码,仅消费。需各服务确认错误码前缀不重叠:
| 前缀 | 服务 | 状态 |
| ------------------------------ | ----------- | --------- |
| `IAM_` | iam | ✅ 已用 |
| `CLASSES_` | core-edu | ✅ 已用 |
| `EXAMS_`/`HOMEWORK_`/`GRADES_` | core-edu | ⚠️ 待确认 |
| `CONTENT_` | content | ⚠️ 待确认 |
| `MSG_` | msg | ⚠️ 待确认 |
| `AI_` | ai | ⚠️ 待确认 |
| `BFF_TEACHER_` | teacher-bff | ⚠️ 待确认 |
| `GW_` | api-gateway | ✅ 已用 |
| `NETWORK_` | 前端 | ai07 自有 |
### 12.5 不产生 Kafka 事件
前端不发布/消费 Kafka 事件。WebSocket 推送由 push-gateway 消费 Kafka 转发。
## 13. 实施路线ai07 自用)
### P2 收尾teacher-portal 审计对齐)
1.`packages/ui-tokens/`(三层设计令牌)+ `packages/ui-components/`ErrorBoundary/RequirePermission/Loading/Empty+ `packages/hooks/`usePermission/useAuth
2. teacher-portal 引入 TanStack Query + Zustand + nuqs + react-hook-form
3. 抽取 `lib/api.ts` 统一 API 请求层
4. AppShell 改用 `usePermission()`,删除 `user.roles.join(", ")` 硬编码
5. globals.css / tailwind.config.js 迁移到 ui-tokens 三层令牌
6. 引入 next-intl + i18n key 路由
7. 引入 ESLint flat config 自定义规则no-hardcoded-fonts / design-tokens
8. 补 ErrorBoundary + /api/health route
9. 配置 next.config.js Module FederationShell 角色)
10. 补 Vitest 单测 + Playwright E2E覆盖率 ≥ 80%
### P5推送 + AI 接入)
1. teacher-portal 接入 WebSocketpush-gateway
2. teacher-portal AI 辅助出题SSE + Tiptap
### P6硬化
1. Web Vitals + OTel browser SDK 接入
2. A11y WCAG 2.2 AA 审计
3. 性能优化MF shared 单例验证、bundle 分析)
---
**AI Agent**: ai07 (teacher-portal shell)
**Branch**: docs/teacher-portal-stage1-stage2-design-ai07
**Coordinator**: coord-ai