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,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