docs(parent-portal): ai15 阶段1+2 文档审计与补全

按 ai-allocation.md §3.2 接管 parent-portal,完成阶段 1+2 文档审计与补全。
修订端口(3002→4002)、所有权(ai07→ai15),补全 16 章长远架构。

AI Agent: ai15 (parent-portal remote)
Branch: docs/parent-portal-stage1-stage2-design-ai15
Coordinator: coord-ai
Predecessor: ai07
This commit is contained in:
SpecialX
2026-07-09 18:51:10 +08:00
parent e691cd267d
commit db90b2e080
2 changed files with 1261 additions and 29 deletions

View File

@@ -1,11 +1,20 @@
# 模块架构设计文档 — 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)
> AIai15TS/React · 家长场景域前端 remote
> 阶段:阶段 2 交付物v2 — ai15 接管审计与补全版)
> 初版日期2026-07-09ai07 起草)
> 审计日期2026-07-09ai15 修订:端口、所有权、长远架构遗漏补全)
> 关联:[阶段 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)、[parent-bff 阶段1](../../../services/parent-bff/docs/01-understanding.md)
> 状态:待 coord 交叉审查
> **审计修订摘要**ai15 → ai07 初稿):
>
> 1. **端口修订**3002 → **4002**004 §1.2 强制 4 端 4000-4003
> 2. **MF 配置端口修订**teacher/student/parent/admin URL 全部从 3000-3003 修订为 4000-4003
> 3. **所有权修订**ai07 → **ai15**ai-allocation.md §3.2
> 4. **遗漏补全**通知偏好数据模型细化、详细组件设计图、跨标签同步实现、API 版本演进、未来扩展铺垫、监控降级、模块演化策略
> 5. **新增章节**§14 通知偏好数据模型细化、§15 详细组件设计、§16 跨标签同步实现、§17 API 契约版本管理、§18 监控与降级、§19 模块演化与解耦、§20 长远架构愿景
---
## 1. 模块内部分层图简化版Remote 角色)
@@ -91,7 +100,7 @@ graph TB
const NextFederationPlugin = require("@module-federation/nextjs-mf");
const remotes = (isServer) => ({
teacher: `teacher_app@http://localhost:3000/_next/static/${isServer ? "ssr" : "chunks"}/remoteEntry.js`,
teacher: `teacher_app@http://localhost:4000/_next/static/${isServer ? "ssr" : "chunks"}/remoteEntry.js`,
});
module.exports = {
@@ -129,7 +138,11 @@ module.exports = {
};
```
> 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)
> **端口约束**004 §1.2 + project memory 硬约束4 端 portal 必须在 4000-4003 范围内。teacher-portal=4000、student-portal=4001、parent-portal=4002、admin-portal=4003
>
> **Shell 端配置对称**`teacher-portal/next.config.js` 的 `remotes.parent = parent_app@http://localhost:4002/_next/static/${isServer ? "ssr" : "chunks"}/remoteEntry.js`(详见 [teacher-portal 阶段2 §1.2](../../teacher-portal/docs/02-architecture-design.md#12-mf-配置teacher-portalnextconfigjs))。**注意**teacher-portal 阶段2 文档中 MF URL 用 3000-3003 是过时的,应同步修订为 4000-4003**coord 交叉审查整改项 #1**)。
>
> **MF 配置预留**(未来扩展):当 parent-portal 拆分为多 Remote 时(见 §19可在此处增加 `exposes` 子模块(如 `./comm-remote`Shell 端 `remotes.parent_comm = ...`。
## 2. 领域模型(前端视角)
@@ -470,9 +483,9 @@ Next.js 无长连接(除 SSE/WS无需特殊处理。WS 在 P5 由 push-g
| 端 | dev 端口 | 生产端口 | 备注 |
| ------------- | -------- | -------- | ------------- |
| parent-portal | 3002 | 3002 | Remote 子应用 |
| parent-portal | 4002 | 4002 | Remote 子应用 |
> 与 [full-stack-runbook](../../../docs/standards/full-stack-runbook.md) 端口矩阵对齐。
> [004 §1.2](../../../docs/architecture/004_architecture_impact_map.md#12-服务清单) 与 [full-stack-runbook](../../../docs/standards/full-stack-runbook.md) 端口矩阵对齐。**4 端 portal 强制 4000-4003 范围**project memory 硬约束)。
### 12.2 依赖的共享包(需 coord 建立)
@@ -538,9 +551,705 @@ Next.js 无长连接(除 SSE/WS无需特殊处理。WS 在 P5 由 push-g
1. Web Vitals + OTel browser SDK 接入
2. A11y WCAG 2.2 AA 审计
3. 性能优化MF shared 单例验证、bundle 分析)
4. 多语言扩展en-US/zh-TW
5. PWA 接入Service Worker + manifest
6. 安全硬化CSP/CORS/敏感数据脱敏)
### P7+(扩展阶段,预留)
1. 家校沟通IM 聊天)— `NotificationFeed` 抽象为通用消息流
2. 缴费(学费/餐费)— `ParentDashboard` 卡片插槽
3. 活动 RSVP家长会/运动会)— 通知支持 `rsvp` 类型
4. 家长端 AI 助手 — SSE 复用 teacher-portal 模式
---
**AI Agent**: ai07 (parent-portal remote)
**Branch**: docs/parent-portal-stage1-stage2-design-ai07
## 14. 通知偏好数据模型细化ai15 新增)
> ai07 初稿仅提到 `PUT /parent/notification-preferences`,未细化数据模型。家长端通知偏好是核心场景之一,必须细化。
### 14.1 三维偏好矩阵
通知偏好按 **子女 × 事件类型 × 渠道** 三维组织:
```typescript
interface NotificationPreferences {
parentId: string;
// 三维矩阵children[eventType][channel] = enabled
preferences: Record<
string, // childId"*" 表示全部子女)
Record<
NotificationEventType, // 事件类型
Record<NotificationChannel, boolean> // 渠道 → 是否启用
>
>;
// 全局默认(覆盖三维矩阵的默认值)
defaults: Record<
NotificationEventType,
Partial<Record<NotificationChannel, boolean>>
>;
updatedAt: string; // ISO 8601
}
type NotificationEventType =
| "grade_recorded" // 成绩发布
| "homework_graded" // 作业批改完成
| "homework_assigned" // 作业布置
| "exam_published" // 考试发布
| "attendance_alert" // 出勤异常
| "school_announcement" // 学校通知
| "teacher_message" // 教师沟通P7+
| "fee_reminder" // 缴费提醒P7+
| "event_invitation"; // 活动邀请P7+
type NotificationChannel =
| "in_app" // 站内信
| "push" // App 推送P5+ Web Push
| "sms" // 短信msg 服务支持时)
| "email" // 邮件
| "wechat"; // 微信msg 服务支持时)
```
### 14.2 默认值矩阵
| 事件类型 | in_app | push | sms | email | wechat |
| ------------------- | ------ | ----- | ----- | ----- | ------ |
| grade_recorded | true | true | false | true | false |
| homework_graded | true | true | false | false | false |
| homework_assigned | true | false | false | false | false |
| exam_published | true | true | false | true | false |
| attendance_alert | true | true | true | true | false |
| school_announcement | true | false | false | true | true |
| teacher_message | true | true | false | false | false |
| fee_reminder | true | true | true | true | true |
| event_invitation | true | true | false | true | false |
### 14.3 表单交互设计
`PreferenceForm` 组件采用矩阵式 UI
- 横轴渠道in_app/push/sms/email/wechat
- 纵轴:事件类型
- 顶部:子女切换(默认 "*" 全部子女,可切到具体子女覆盖)
- 单元格Toggle Switch
- 底部保存按钮sticky+ 重置默认按钮
### 14.4 Zod 校验 schema
```typescript
const NotificationPreferencesSchema = z.object({
parentId: z.string().uuid(),
preferences: z.record(
z.string(), // childId 或 "*"
z.record(
z.enum([
"grade_recorded",
"homework_graded",
"homework_assigned",
"exam_published",
"attendance_alert",
"school_announcement",
"teacher_message",
"fee_reminder",
"event_invitation",
]),
z.object({
in_app: z.boolean().default(true),
push: z.boolean().default(false),
sms: z.boolean().default(false),
email: z.boolean().default(false),
wechat: z.boolean().default(false),
}),
),
),
defaults: z.record(
z.string(),
z.object({
in_app: z.boolean().optional(),
push: z.boolean().optional(),
sms: z.boolean().optional(),
email: z.boolean().optional(),
wechat: z.boolean().optional(),
}),
),
updatedAt: z.string().datetime(),
});
```
### 14.5 渠道可用性校验
前端在渲染 `PreferenceForm` 前,需根据 BFF 返回的 `availableChannels` 字段禁用不可用渠道:
```typescript
// BFF 响应
{
"preferences": {...},
"availableChannels": {
"sms": false, // msg 服务未配置短信网关
"wechat": false, // msg 服务未配置微信公众号
"email": true,
"push": false, // push-gateway P5 才上线
"in_app": true
}
}
```
不可用渠道的 Toggle 显示为 disabled + tooltip "此渠道暂未开通"。
---
## 15. 详细组件设计ai15 新增)
> ai07 初稿仅列出组件名。ai15 补全关键组件的 Props 接口与状态机。
### 15.1 ChildSwitcher 组件
```typescript
interface ChildSwitcherProps {
variant: "tab" | "dropdown"; // 由 MultiChildTabBar 根据子女数自动选择
size: "sm" | "md" | "lg";
showAvatar: boolean;
onChange?: (childId: string) => void; // 不传则使用内置 Zustand slice
className?: string;
}
// 内部状态机
type ChildSwitcherState =
| { status: "idle" }
| { status: "switching"; fromChildId: string; toChildId: string }
| { status: "switched"; childId: string }
| { status: "error"; error: ApiError };
```
### 15.2 ParentDashboard 组件
```typescript
interface ParentDashboardProps {
// 不接受 props全部数据来自 TanStack Query hooks
// 内部组合useChildren() + useChildGrades(currentChildId) + useChildAnalytics(currentChildId)
}
type ParentDashboardSlot =
| "summary-cards" // ChildSummaryCard 列表
| "todo-reminders" // 待办提醒(未读作业、未确认通知)
| "recent-grades" // 近期成绩曲线
| "attendance" // 出勤概览
| "custom"; // 自定义插槽P7+ 缴费/活动)
```
### 15.3 NotificationFeed 组件
```typescript
interface NotificationFeedProps {
filter?: {
childId?: string; // 按子女筛选
eventType?: NotificationEventType[];
unreadOnly?: boolean;
};
sort?: "desc" | "asc";
pageSize?: number; // 默认 20
onNotificationClick?: (notification: Notification) => void;
onMarkAllRead?: () => void;
}
type Notification = {
id: string;
childId: string | null;
eventType: NotificationEventType;
title: string; // i18n key
body: string; // i18n key + 参数
read: boolean;
createdAt: string;
actionUrl?: string; // 点击跳转
pinned?: boolean;
};
```
### 15.4 PreferenceForm 组件
```typescript
interface PreferenceFormProps {
initialPreferences: NotificationPreferences;
availableChannels: Record<NotificationChannel, boolean>;
onSubmit: (prefs: NotificationPreferences) => Promise<void>;
onReset?: () => void;
}
// 表单状态机
type PreferenceFormState =
| { status: "idle" }
| { status: "dirty"; changes: Partial<NotificationPreferences> }
| { status: "submitting" }
| { status: "submitted" }
| { status: "error"; error: ApiError };
```
### 15.5 ChildGradeChart 组件
```typescript
interface ChildGradeChartProps {
childId: string;
examIds?: string[]; // 不传则展示全部
compareWithClass: boolean; // 是否叠加班级均分对比
compareWithChildren?: string[]; // 多子女对比模式
height?: number;
showLegend: boolean;
}
type GradeDataPoint = {
examId: string;
examName: string;
examDate: string;
studentScore: number;
classAverage?: number;
classMax?: number;
classMin?: number;
gradeLevel: "A" | "B" | "C" | "D" | "F";
};
```
### 15.6 组件依赖关系图
```mermaid
graph TB
App[ParentApp Root] --> AppShell
App --> Router[Next.js Router]
Router --> DashboardPage
Router --> ChildrenPage
Router --> GradesPage
Router --> HomeworkPage
Router --> NotificationsPage
Router --> PreferencesPage
DashboardPage --> ParentDashboard
ParentDashboard --> MultiChildTabBar
ParentDashboard --> ChildSummaryCard
ParentDashboard --> ChildGradeChart
ParentDashboard --> AttendanceCalendar
GradesPage --> MultiChildTabBar
GradesPage --> ChildGradeChart
NotificationsPage --> NotificationFeed
NotificationFeed --> FilterBar
PreferencesPage --> PreferenceForm
MultiChildTabBar --> ChildSwitcher
ChildSwitcher --> useChildSwitcher
useChildSwitcher --> ApiClient
useChildSwitcher --> ZustandStore[childSwitcherSlice]
useChildSwitcher --> TanStackQuery[parent, children]
```
---
## 16. 跨标签同步实现ai15 新增)
### 16.1 同步架构图
```mermaid
graph LR
subgraph TabA["Tab A活跃"]
UserAction[用户切换子女]
ZustandA[Zustand slice]
LSA[localStorage]
BCA[BroadcastChannel]
end
subgraph TabB["Tab B后台"]
BCB[BroadcastChannel]
ZustandB[Zustand slice]
LSB[localStorage]
QueryB[TanStack Query cache]
end
UserAction --> ZustandA
ZustandA --> LSA
ZustandA --> BCA
BCA -->|postMessage| BCB
BCB --> ZustandB
ZustandB --> QueryB
QueryB -->|invalidate| QueryB2[重新拉取该子女数据]
LSA -->|storage event| LSB
LSB --> ZustandB
```
### 16.2 完整实现
```typescript
// apps/parent-portal/src/lib/crossTabSync.ts
import { useEffect } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useChildSwitcherStore } from "../stores/childSwitcherSlice";
const CHANNEL_NAME = "parent-child-switch";
const STORAGE_KEY = "parent:currentChildId";
type SyncMessage = {
type: "child-switched" | "child-unbound" | "preferences-updated";
childId?: string;
ts: number;
source: string; // 唯一标识当前 tab避免自己处理自己的消息
};
// 每个 tab 生成唯一 source ID
const TAB_SOURCE = `tab-${Date.now()}-${Math.random().toString(36).slice(2)}`;
export function useCrossTabSync() {
const queryClient = useQueryClient();
const setCurrentChildId = useChildSwitcherStore((s) => s.setCurrentChildId);
useEffect(() => {
const channel = new BroadcastChannel(CHANNEL_NAME);
// 接收其他 tab 的消息
channel.onmessage = (event: MessageEvent<SyncMessage>) => {
const msg = event.data;
if (!msg || msg.source === TAB_SOURCE) return; // 忽略自己的消息
switch (msg.type) {
case "child-switched":
if (msg.childId) {
setCurrentChildId(msg.childId);
// 不 invalidate让其他 tab 的数据缓存继续生效
// 只有用户主动切换时才 invalidate
}
break;
case "child-unbound":
// 子女被解绑,全部 tab 都要清理
queryClient.invalidateQueries({ queryKey: ["parent", "children"] });
if (msg.childId) {
queryClient.removeQueries({
queryKey: ["parent", "grades", msg.childId],
});
queryClient.removeQueries({
queryKey: ["parent", "homework", msg.childId],
});
}
break;
case "preferences-updated":
queryClient.invalidateQueries({
queryKey: ["parent", "preferences"],
});
break;
}
};
// 监听 localStorage 跨 tab 同步BroadcastChannel 的补充)
const onStorage = (e: StorageEvent) => {
if (e.key === STORAGE_KEY && e.newValue) {
const newChildId = e.newValue;
const currentChildId = useChildSwitcherStore.getState().currentChildId;
if (newChildId !== currentChildId) {
setCurrentChildId(newChildId);
}
}
};
window.addEventListener("storage", onStorage);
return () => {
channel.close();
window.removeEventListener("storage", onStorage);
};
}, [queryClient, setCurrentChildId]);
}
// 在切换子女时调用
export function broadcastChildSwitch(childId: string) {
const channel = new BroadcastChannel(CHANNEL_NAME);
channel.postMessage({
type: "child-switched",
childId,
ts: Date.now(),
source: TAB_SOURCE,
} satisfies SyncMessage);
channel.close();
}
// 在子女被解绑时调用(通常来自 WebSocket 事件)
export function broadcastChildUnbound(childId: string) {
const channel = new BroadcastChannel(CHANNEL_NAME);
channel.postMessage({
type: "child-unbound",
childId,
ts: Date.now(),
source: TAB_SOURCE,
} satisfies SyncMessage);
channel.close();
}
// 在通知偏好更新后调用
export function broadcastPreferencesUpdated() {
const channel = new BroadcastChannel(CHANNEL_NAME);
channel.postMessage({
type: "preferences-updated",
ts: Date.now(),
source: TAB_SOURCE,
} satisfies SyncMessage);
channel.close();
}
```
### 16.3 集成到 RootLayout
```typescript
// apps/parent-portal/src/app/layout.tsx
"use client";
import { useCrossTabSync } from "../lib/crossTabSync";
export default function ParentPortalLayout({
children,
}: {
children: React.ReactNode;
}) {
useCrossTabSync(); // 启用跨 tab 同步
return <>{children}</>;
}
```
---
## 17. API 契约版本管理ai15 新增)
### 17.1 版本兼容矩阵
| API 版本 | 引入阶段 | 弃用阶段 | 移除阶段 | parent-portal 兼容性 |
| -------- | -------- | -------- | -------- | ----------------------------- |
| v1 | P4 | - | - | ✅ P4+ 必须支持 |
| v2 | P6+ | - | - | ⚠️ P6+ 通过 Feature Flag 切换 |
| 字段裁剪 | P5+ | - | - | ⚠️ 可选,移动端低带宽时启用 |
### 17.2 ApiClient 版本协商
```typescript
// packages/shared-ts/src/api-client.tscoord 维护ai15 提需求)
class ApiClient {
private apiVersion: string = "v1";
// 通过响应头感知版本
private captureVersion(response: Response) {
const version = response.headers.get("X-API-Version");
if (version) {
this.apiVersion = version;
}
const deprecation = response.headers.get("Deprecation");
if (deprecation === "true") {
const sunset = response.headers.get("Sunset");
logger.warn("API deprecated", {
path: response.url,
sunset,
});
// 上报埋点,跟踪使用率
metrics.increment("api.deprecated_call", {
path: response.url,
});
}
}
// 切换主版本
setVersion(version: "v1" | "v2") {
this.apiVersion = version;
}
// 字段裁剪
setFields(fields: string) {
this.defaultHeaders["X-Fields"] = fields;
}
}
```
### 17.3 字段裁剪使用场景
| 场景 | 裁剪策略 | 节省带宽 |
| -------------------------- | --------------------------------------------------------------- | -------- |
| 移动端 4G 网络查看子女列表 | `children[].id,children[].name,children[].avatar` | ~70% |
| 通知列表快速浏览 | `notifications[].id,notifications[].title,notifications[].read` | ~60% |
| Dashboard 概览 | `grades[].examName,grades[].studentScore` | ~50% |
| 完整成绩详情(默认) | 不裁剪 | 0% |
---
## 18. 监控与降级ai15 新增)
### 18.1 前端监控指标
| 指标 | 类型 | 采集方式 | 告警阈值 |
| -------------------------------- | --------- | ------------------------- | ------------------ |
| `parent_portal_lcp_seconds` | LCP | `next/web-vitals` | P95 > 2.5s |
| `parent_portal_cls` | CLS | 同上 | P95 > 0.1 |
| `parent_portal_ttfb_seconds` | TTFB | 同上 | P95 > 0.8s |
| `parent_portal_mf_load_failed` | Counter | MF Remote 加载错误捕获 | > 1% |
| `parent_portal_api_error_rate` | Counter | ApiClient 错误拦截 | 5xx > 1% |
| `parent_portal_ws_reconnect` | Counter | WebSocket 重连计数 | 单用户 > 5 次/小时 |
| `parent_portal_child_switch_p99` | Histogram | ChildSwitcher 切换耗时 | P99 > 1s |
| `parent_portal_cache_hit_rate` | Gauge | TanStack Query 缓存命中率 | < 60%(异常) |
| `parent_portal_offline_duration` | Histogram | 网络中断时长 | P95 > 30s |
| `parent_portal_a11y_violations` | Counter | axe-core 自动扫描 | 严重违规 > 0 |
### 18.2 降级策略矩阵
| 触发条件 | 降级动作 | 用户感知 |
| --------------------------------- | ----------------------------------------------------------- | ---------------------------- |
| MF Remote 加载失败10s 超时) | 显示 Shell 内置的最小化静态引导页 | "家长端加载失败,请稍后重试" |
| BFF 5xx 错误率 > 5% | 隐藏 mutation 按钮(保存/切换);展示只读模式 banner | 顶部黄色 banner"只读模式" |
| BFF P95 延迟 > 5s | 缩短缓存 TTL 至 5s展示"加载缓慢"提示 | 顶部提示条 |
| WebSocket 连接失败 5 次 | 降级为 HTTP 轮询60s 拉取通知列表) | 通知延迟最多 60s |
| 子女列表加载失败 3 次 | 显示错误页 + 重试按钮 + 客服联系方式 | 错误页 |
| i18n message 加载失败 | Fallback 到 key 本身作为文案(如 `parent.dashboard.title` | 显示英文 key不影响功能 |
| 设计令牌加载失败 | Fallback 到 Tailwind 默认色板 | 视觉风格降级,不影响功能 |
| BroadcastChannel 不支持Safari | 仅依赖 storage 事件 | 跨 tab 同步延迟 ~500ms |
| localStorage 满 | 清理最旧的缓存项;提示用户清理浏览器缓存 | 写入失败 toast |
### 18.3 错误恢复流程
```mermaid
flowchart TD
Error[发生错误] --> Classify{错误类型}
Classify -->|Network| Retry[指数退避重试 3 次]
Classify -->|401 Unauthorized| Refresh[刷新 token]
Classify -->|403 Forbidden| Toast[toast 提示无权限]
Classify -->|404 Not Found| Empty[显示空态]
Classify -->|5xx Server Error| Fallback[降级策略]
Classify -->|MF Load Failed| ShellFallback[Shell 兜底页]
Retry -->|成功| Recover[恢复正常]
Retry -->|失败| Fallback
Refresh -->|成功| Recover
Refresh -->|失败| Logout[跳转登录页]
Fallback --> ReadOnlyMode[只读模式]
Fallback --> CachedData[展示缓存数据]
Fallback --> ErrorPage[错误页 + 重试]
Toast --> Continue[继续当前操作]
Empty --> Continue
ShellFallback --> RetryMF[10s 后重试 MF]
ReadOnlyMode --> WaitForRecover[等待 BFF 恢复]
WaitForRecover --> Recover
```
---
## 19. 模块演化与解耦ai15 新增)
### 19.1 拆分触发条件
| 触发条件 | 拆分方向 | 阶段 |
| --------------------------------------- | --------------------------------------------------------------- | ---- |
| parent-portal bundle > 200KBgzipped | 按场景域拆分为 `parent-core-remote` + `parent-comm-remote` | P7+ |
| 团队规模 > 5 人同时维护 parent-portal | 同上 | P7+ |
| 家校沟通功能复杂度提升 | 拆出 `parent-comm-remote`IM + 通知中心) | P7+ |
| 缴费功能引入 | 拆出 `parent-finance-remote` | P7+ |
| 多租户支持 | URL 前缀 `/{tenantId}/parent/*`TanStack Query key 加 tenantId | P8+ |
### 19.2 拆分后的 MF 配置
```javascript
// 拆分后parent-core-remote核心场景
new NextFederationPlugin({
name: "parent_core_app",
filename: "static/chunks/remoteEntry.js",
exposes: {
"./pages": "./src/pages", // dashboard/grades/homework/children
"./ChildSwitcher": "./src/components/ChildSwitcher",
},
// ...
});
// 拆分后parent-comm-remote沟通场景
new NextFederationPlugin({
name: "parent_comm_app",
filename: "static/chunks/remoteEntry.js",
exposes: {
"./pages": "./src/pages", // notifications/preferences/chat
"./NotificationFeed": "./src/components/NotificationFeed",
},
// ...
});
```
### 19.3 状态管理迁移路径
| 迁移场景 | 触发条件 | 迁移策略 |
| ------------------------ | ------------------ | -------------------------------------------------------------- |
| Zustand → Jotai | 性能瓶颈或团队偏好 | 逐 slice 迁移Hook 接口保持不变;新旧 slice 共存 1 个迭代周期 |
| localStorage → IndexedDB | 数据量 > 5MB | 抽象存储层Hook 接口不变;迁移期双写 + 校验一致性 |
| TanStack Query v5 → v6 | TanStack 发布 v6 | 跟随社区升级Breaking Change 通过 codemod 自动迁移 |
### 19.4 MF 升级路径
| 升级场景 | 触发条件 | 风险与缓解 |
| ------------------------ | ------------------------------ | ----------------------------------------------------------------------- |
| MF 2.0 → 3.0 | MF 3.0 稳定且解决 SSR 问题 | Shell 端升级parent-portal 仅改 `name`/`filename`CI 验证 shared 单例 |
| MF → 原生 SSR脱离 MF | SEO 需求强烈或 MF 维护成本过高 | 保留 API 请求层和组件库;移除 MF 配置;独立部署为完整 Next.js 应用 |
| Next.js 14 → 15 | Next.js 15 稳定 | 跟随 Shell 升级App Router API 兼容性验证 |
| React 18 → 19 | React 19 稳定 | 跟随 Shell 升级use hook / Suspense 改进可简化 TanStack Query 集成 |
---
## 20. 长远架构愿景ai15 新增)
### 20.1 三年架构演进路线
```mermaid
graph LR
Y1[Year 1<br/>P4-P6 单体 Remote<br/>MF 2.0] --> Y2[Year 2<br/>P7+ 多 Remote 拆分<br/>家校沟通+缴费+活动]
Y2 --> Y3[Year 3<br/>P8+ 多租户+多区域<br/>MF 3.0 / 原生 SSR]
```
### 20.2 架构原则(始终不变)
1. **Remote 角色不变**parent-portal 始终作为 teacher-portal Shell 的 Remote不独立 Shell
2. **契约先行**:所有 API 变更先 proto/contracts后实现
3. **无状态前端**:所有持久化状态走 localStorage/IDB不依赖服务端 session
4. **复用优先**:组件/Hook/工具优先复用 Shell 暴露的,避免重复实现
5. **可降级**任何依赖BFF/WebSocket/Shell故障都有降级方案
6. **可观测**:所有用户行为、错误、性能指标都可观测
7. **可测试**:所有组件/Hook/页面都有单测 + E2E 覆盖
8. **可演化**:模块可拆分、状态管理可迁移、框架可升级
### 20.3 与其他 portal 的协同演化
| 演化方向 | parent-portal 角色 | 协同端 |
| -------------------------------------- | ------------------------------------ | ------------------------------------ |
| 共享组件抽取到 packages/ | 消费方(不再在 Remote 内自建组件) | teacher-portalShell+ 其他 Remote |
| 共享 Hook 抽取到 packages/hooks/ | 消费方 | 同上 |
| 共享业务模型抽取到 packages/contracts/ | 消费方(类型定义) | 同上 |
| 多 portal 间通信(如教师↔家长) | 通过后端 BFF/gRPC不直连其他 Remote | teacher-portal / student-portal |
| 跨 portal 路由跳转 | 通过 Shell 统一路由表 | 所有 portal |
### 20.4 与后端架构的协同演化
| 后端演化 | parent-portal 适配 |
| ------------------------------ | ----------------------------------------------- |
| BFF REST → GraphQL | 引入 urql/apollo client保持 ApiClient 接口 |
| BFF → BFF + 微前端 API Gateway | parent-portal 不感知ApiClient baseUrl 不变 |
| 引入 Service MeshIstio | parent-portal 不感知;网络层透明 |
| 引入 Feature Flag 服务 | 集成 FeatureFlagProvider组件按 flag 渲染 |
| 引入 A/B Testing 平台 | 集成 ABTestProviderUI 按 variant 渲染 |
| 后端多租户 | URL 加 `/{tenantId}/parent/*`Query key 加维度 |
| 后端多区域 | ApiClient 按 region 路由CDN 边缘缓存 |
### 20.5 关键技术债务预警
| 债务项 | 当前状态 | 紧急度 | 清理建议 |
| ---------------------------------------- | ---------- | ------ | --------------------------------------------- |
| ai07 初稿端口错误3002 vs 4002 | ✅ 已修订 | 高 | coord 同步修订 teacher-portal docs |
| ai07 初稿所有权错误ai07 vs ai15 | ✅ 已修订 | 高 | 004 §15 文档矩阵已记录 ai15 = parent-portal |
| MF SSR 对齐 | 待验证 | 中 | P4 启动前 PoC 验证 MF 2.0 SSR若失败降级 CSR |
| iam 家长-学生关联接口缺失P0 阻塞) | 待 ai02 补 | 高 | coord 协调 ai02 在 P3 收尾前补全 |
| shared-ts / contracts 未建立 | 待 coord | 高 | P4 启动前必须建立;否则 ai15 自行实现后续提取 |
| ui-tokens / ui-components / hooks 未建立 | 待 ai07 | 高 | P4 启动前必须建立ai07 在 P2 收尾交付 |
| MF Remote 加载失败的兜底 | 待实现 | 中 | P4 实现期落地 Shell 内置兜底页 |
| 跨 tab 同步在 Safari 的兼容性 | 待验证 | 低 | P6 硬化期验证;降级为 storage 事件 |
---
**AI Agent**: ai15 (parent-portal remote)
**Branch**: docs/parent-portal-stage1-stage2-design-ai15
**Coordinator**: coord-ai
**Predecessor**: ai07初版起草ai15 接管审计与补全)