From 6757ad869f892e37633542158bb3fa688cf38820 Mon Sep 17 00:00:00 2001 From: sophie Date: Thu, 18 Jun 2026 10:18:18 +0800 Subject: [PATCH 01/11] =?UTF-8?q?fix(admin):=20=E7=94=A8=E6=88=B7=E5=AD=97?= =?UTF-8?q?=E6=AE=B5=E5=94=AF=E4=B8=80=E6=80=A7=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/admin.py | 65 ++++++++++++++++++++++++------- backend/tests/test_user_fields.py | 65 ++++++++++++++++++++++++++++--- 2 files changed, 109 insertions(+), 21 deletions(-) diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py index d4758864..81fcb1c0 100644 --- a/backend/app/api/admin.py +++ b/backend/app/api/admin.py @@ -41,6 +41,29 @@ def _raise_user_integrity_conflict(exc: IntegrityError) -> None: raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS') raise ConflictError('Data uniqueness conflict', code='USER.UNIQUENESS_CONFLICT') +def _assert_user_unique_fields(exclude_user_id: int | None, **fields: str | None) -> None: + """ + 校验用户唯一字段(邮箱、工号、手机号)不与其它账号冲突。 + 核心逻辑:对传入的非 None 字段查询 User 表;编辑时 exclude_user_id 排除当前用户。 + @param exclude_user_id: 编辑场景传当前用户 id;创建场景传 None + @param fields: email / employee_id / phone_number 等待校验值 + @raises ConflictError: 唯一字段已被占用 + """ + checks = ( + ('email', 'USER.EMAIL_EXISTS', 'Email already exists'), + ('employee_id', 'USER.EMPLOYEE_ID_EXISTS', 'Employee ID already exists'), + ('phone_number', 'USER.PHONE_EXISTS', 'Phone number already exists'), + ) + for field, code, message in checks: + value = fields.get(field) + if value is None: + continue + query = db.session.query(User.id).filter(getattr(User, field) == value) + if exclude_user_id is not None: + query = query.filter(User.id != exclude_user_id) + if query.first(): + raise ConflictError(message, code=code, details={'field': field}) + def _empty_to_none(value): if value is None: return None @@ -564,13 +587,19 @@ def create_user(): email = _empty_to_none(data.get('email')) if not _is_valid_email(email): raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'}) + _assert_user_unique_fields( + None, + email=email, + employee_id=_empty_to_none(data.get('employee_id')), + phone_number=_empty_to_none(data.get('phone_number')), + ) user = User(username=data['username'], email=email, department=_empty_to_none(data.get('department')), role=data.get('role', 'user'), status=data.get('status', 'active'), real_name=_empty_to_none(data.get('real_name')), employee_id=_empty_to_none(data.get('employee_id')), phone_number=_empty_to_none(data.get('phone_number'))) user.set_password(data['password']) - if data.get('agent_ids'): - agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all() - user.agents = agents db.session.add(user) try: + if data.get('agent_ids'): + agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all() + user.agents = agents user_api._sync_casdoor_create_user( username=user.username, password=data['password'], @@ -597,7 +626,7 @@ def create_user(): def update_user(id): """ 管理端编辑用户:资料仅写本地库;仅改密时同步 Casdoor set-password。 - 核心逻辑:应用本地字段 →(有 new_password 时)_sync_casdoor_update_user → commit。 + 核心逻辑:唯一字段预校验 → 应用本地字段与 agent_ids →(有 new_password 时)_sync_casdoor_update_user → commit。 Request JSON: email, department, role, status, password 等;password 为空表示不改密 Returns: { status: ok };Casdoor 改密/唯一约束失败时抛出 AppError/ConflictError @@ -611,19 +640,25 @@ def update_user(id): email = _empty_to_none(data.get('email')) if email is not None and (not _is_valid_email(email)): raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'}) + unique_updates = { + field: _empty_to_none(data[field]) + for field in ('email', 'employee_id', 'phone_number') + if field in data + } + _assert_user_unique_fields(id, **unique_updates) new_password = _empty_to_none(data.get('password')) - for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']: - if k in data: - if k in ['email', 'department', 'real_name', 'employee_id', 'phone_number']: - setattr(user, k, _empty_to_none(data[k])) - else: - setattr(user, k, data[k]) - if new_password: - user.set_password(new_password) - if 'agent_ids' in data: - agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all() - user.agents = agents try: + for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']: + if k in data: + if k in ['email', 'department', 'real_name', 'employee_id', 'phone_number']: + setattr(user, k, _empty_to_none(data[k])) + else: + setattr(user, k, data[k]) + if new_password: + user.set_password(new_password) + if 'agent_ids' in data: + agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all() + user.agents = agents if new_password: user_api._sync_casdoor_update_user(user, new_password=new_password) db.session.commit() diff --git a/backend/tests/test_user_fields.py b/backend/tests/test_user_fields.py index 010e484f..a5385ed4 100644 --- a/backend/tests/test_user_fields.py +++ b/backend/tests/test_user_fields.py @@ -1,7 +1,21 @@ import pytest -from app.models import User +from app.models import User, Agent from app import db +def _error_message(response): + body = response.get_json() or {} + error = body.get('error') + if isinstance(error, dict): + return str(error.get('message') or '') + return str(error or '') + +def _error_code(response): + body = response.get_json() or {} + error = body.get('error') + if isinstance(error, dict): + return str(error.get('code') or '') + return '' + def test_register_fields_validation(client): """ Test user registration field validation @@ -40,7 +54,7 @@ def test_register_fields_validation(client): } response = client.post('/api/user/register', json=dup_user) assert response.status_code == 400 - assert "Employee ID already exists" in response.json['error'] + assert "Employee ID already exists" in _error_message(response) def test_admin_duplicate_employee_id(client, admin_headers): """ @@ -68,8 +82,8 @@ def test_admin_duplicate_employee_id(client, admin_headers): "phone_number": "13800000012" } response = client.post('/api/admin/users', json=u2, headers=admin_headers) - assert response.status_code == 400 - assert "Employee ID already exists" in response.json['error'] + assert response.status_code == 409 + assert "Employee ID already exists" in _error_message(response) # 3. Update user to duplicate ID # Create u3 with valid ID @@ -86,5 +100,44 @@ def test_admin_duplicate_employee_id(client, admin_headers): # Update u3 to ADM001 (which exists) res = client.put(f'/api/admin/users/{u3_id}', json={"employee_id": "ADM001"}, headers=admin_headers) - assert res.status_code == 400 - assert "Employee ID already exists" in res.json['error'] + assert res.status_code == 409 + assert "Employee ID already exists" in _error_message(res) + assert _error_code(res) == 'USER.EMPLOYEE_ID_EXISTS' + +def test_admin_duplicate_phone_on_update_with_agent_ids(client, admin_headers): + """ + 编辑用户时若手机号重复且同时提交 agent_ids,应在 autoflush 前返回冲突而非 500。 + """ + existing = { + "username": "phone_owner", + "password": "pwd", + "email": "phone_owner@e.com", + "real_name": "Phone Owner", + "employee_id": "PHN001", + "phone_number": "123456", + } + target = { + "username": "phone_target", + "password": "pwd", + "email": "phone_target@e.com", + "real_name": "Phone Target", + "employee_id": "PHN002", + "phone_number": "13800009999", + } + assert client.post('/api/admin/users', json=existing, headers=admin_headers).status_code == 201 + target_res = client.post('/api/admin/users', json=target, headers=admin_headers) + assert target_res.status_code == 201 + target_id = target_res.json['id'] + + agent = Agent(name='Dup Phone Agent', dify_app_id='dup-phone-agent', type='chat') + db.session.add(agent) + db.session.commit() + + res = client.put( + f'/api/admin/users/{target_id}', + json={'phone_number': '123456', 'agent_ids': [agent.id]}, + headers=admin_headers, + ) + assert res.status_code == 409 + assert _error_code(res) == 'USER.PHONE_EXISTS' + assert "Phone number already exists" in _error_message(res) From 10b6f9b692ef1772a0afd40561ba509a883f303e Mon Sep 17 00:00:00 2001 From: sophie Date: Fri, 19 Jun 2026 21:25:14 +0800 Subject: [PATCH 02/11] =?UTF-8?q?fix(chat):=20=E5=B0=86=E6=B5=81=E5=BC=8F?= =?UTF-8?q?=E9=94=99=E8=AF=AF=E4=BF=A1=E6=81=AF=E6=98=A0=E5=B0=84=E4=B8=BA?= =?UTF-8?q?=E9=9D=A2=E5=90=91=E7=94=A8=E6=88=B7=E7=9A=84=E6=8F=90=E7=A4=BA?= =?UTF-8?q?=E6=96=B9=E6=A1=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/features/chat/composables/useChat.ts | 14 ++- .../src/features/chat/types/chat.types.ts | 2 + .../features/chat/utils/streamErrorMessage.ts | 88 +++++++++++++++++++ .../chat/utils/toolRunProgressConfig.ts | 1 + frontend/src/locales/en/chat.json | 6 ++ frontend/src/locales/th/chat.json | 6 ++ frontend/src/locales/zh-CN/chat.json | 6 ++ frontend/src/locales/zh-TW/chat.json | 6 ++ 8 files changed, 127 insertions(+), 2 deletions(-) create mode 100644 frontend/src/features/chat/utils/streamErrorMessage.ts diff --git a/frontend/src/features/chat/composables/useChat.ts b/frontend/src/features/chat/composables/useChat.ts index 0ef6d555..85f5f17f 100644 --- a/frontend/src/features/chat/composables/useChat.ts +++ b/frontend/src/features/chat/composables/useChat.ts @@ -3,7 +3,9 @@ * SSE 流式对话核心:消息列表、runs、发送与接收。 */ import { ref } from 'vue'; +import { useI18n } from 'vue-i18n'; import { getAuthHeaders } from '@/shared/utils/auth'; +import { applyStreamErrorToMessage, type StreamErrorLabels } from '../utils/streamErrorMessage'; import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types'; const normalizeResources = (resources: unknown) => { @@ -110,6 +112,7 @@ const applyEventMetadata = (msg: ChatMessage, data: Record) => }; export function useChat() { + const { t } = useI18n(); const messages = ref([]); const isThinking = ref(false); const viewId = ref(0); @@ -169,6 +172,13 @@ export function useChat() { return String(message ?? 'Unknown error'); }; + const streamErrorLabels = (): StreamErrorLabels => ({ + networkDisconnectedEmpty: t('chat.streamError.networkDisconnectedEmpty'), + partialInterrupted: t('chat.streamError.partialInterrupted'), + upstreamDisconnected: t('chat.streamError.upstreamDisconnected'), + generic: t('chat.streamError.generic'), + }); + const sendMessage = async ( query: string, agentId: number, @@ -338,7 +348,7 @@ export function useChat() { } else if (eventName === 'error') { const botMsg = ensureBotMessage(); if (!botMsg) continue; - botMsg.content += `\n[Error: ${formatStreamError(data.message)}]`; + applyStreamErrorToMessage(botMsg, formatStreamError(data.message), streamErrorLabels()); run.status = 'error'; if (messages.value === runMessages) isThinking.value = false; } else if (typeof data.answer === 'string' && data.answer.length > 0) { @@ -356,7 +366,7 @@ export function useChat() { const botMsg = ensureBotMessage(); if (botMsg) { const message = e instanceof Error ? e.message : 'Network Issue'; - botMsg.content += `\n[Error: ${message}]`; + applyStreamErrorToMessage(botMsg, message, streamErrorLabels()); } } finally { if (messages.value === runMessages) { diff --git a/frontend/src/features/chat/types/chat.types.ts b/frontend/src/features/chat/types/chat.types.ts index 3f5f0fb0..d9584985 100644 --- a/frontend/src/features/chat/types/chat.types.ts +++ b/frontend/src/features/chat/types/chat.types.ts @@ -35,6 +35,8 @@ export interface ChatMessage { variant?: 'primary' | 'secondary' | 'danger'; }>; shipping_actions_used?: boolean; + /** 流式对话是否因网络/上游中断而附带错误提示 */ + stream_error?: boolean; } export type ChatRunStatus = 'running' | 'done' | 'error'; diff --git a/frontend/src/features/chat/utils/streamErrorMessage.ts b/frontend/src/features/chat/utils/streamErrorMessage.ts new file mode 100644 index 00000000..a8e692de --- /dev/null +++ b/frontend/src/features/chat/utils/streamErrorMessage.ts @@ -0,0 +1,88 @@ +/** + * features/chat/utils/streamErrorMessage.ts + * 用途:将 SSE / 浏览器流式读错映射为用户可读文案。 + * 依赖:vue-i18n chat.streamError 词条。 + * 逻辑:useChat 在 catch 与 error 事件中调用 applyStreamErrorToMessage。 + */ +import type { ChatMessage } from '../types/chat.types'; + +const NETWORK_DISCONNECT_PATTERNS = [ + 'network error', + 'failed to fetch', + 'load failed', + 'networkerror when attempting to fetch resource', + 'network issue', +]; + +const UPSTREAM_DISCONNECT_PATTERNS = [ + 'response ended prematurely', + 'chunkedencodingerror', +]; + +export interface StreamErrorLabels { + networkDisconnectedEmpty: string; + partialInterrupted: string; + upstreamDisconnected: string; + generic: string; +} + +/** + * 判断是否为浏览器侧 SSE / fetch 连接中断类错误。 + */ +export function isNetworkDisconnectError(message: string): boolean { + const normalized = message.trim().toLowerCase(); + if (!normalized) return false; + return NETWORK_DISCONNECT_PATTERNS.some( + (pattern) => normalized === pattern || normalized.includes(pattern), + ); +} + +/** + * 判断是否为上游(Dify)流式响应提前结束。 + */ +export function isUpstreamDisconnectError(message: string): boolean { + const normalized = message.trim().toLowerCase(); + return UPSTREAM_DISCONNECT_PATTERNS.some((pattern) => normalized.includes(pattern)); +} + +/** + * 将原始错误信息映射为面向用户的提示文案。 + * + * @param rawMessage - 浏览器或后端返回的原始错误 + * @param hasContent - 是否已有部分回答内容 + * @param labels - i18n 文案集合 + */ +export function resolveStreamErrorText( + rawMessage: string, + hasContent: boolean, + labels: StreamErrorLabels, +): string { + if (isNetworkDisconnectError(rawMessage)) { + return hasContent ? labels.partialInterrupted : labels.networkDisconnectedEmpty; + } + if (isUpstreamDisconnectError(rawMessage)) { + return hasContent ? labels.partialInterrupted : labels.upstreamDisconnected; + } + if (/[\u4e00-\u9fff]/.test(rawMessage)) { + return rawMessage; + } + return labels.generic; +} + +/** + * 把流式错误写入 assistant 消息:无内容时整段替换,有部分内容时在末尾追加提示。 + */ +export function applyStreamErrorToMessage( + msg: ChatMessage, + rawMessage: string, + labels: StreamErrorLabels, +): void { + const hasContent = Boolean(msg.content.trim()); + const text = resolveStreamErrorText(rawMessage, hasContent, labels); + msg.stream_error = true; + if (hasContent) { + msg.content += `\n\n${text}`; + } else { + msg.content = text; + } +} diff --git a/frontend/src/features/chat/utils/toolRunProgressConfig.ts b/frontend/src/features/chat/utils/toolRunProgressConfig.ts index 51819839..bb0a4e18 100644 --- a/frontend/src/features/chat/utils/toolRunProgressConfig.ts +++ b/frontend/src/features/chat/utils/toolRunProgressConfig.ts @@ -41,6 +41,7 @@ export function resolveMessageAnchorKey(msg: ChatMessage, index: number): string } export function assistantMessageHasError(msg: ChatMessage | null | undefined): boolean { + if (msg?.stream_error) return true; return String(msg?.content || '').includes('[Error:'); } diff --git a/frontend/src/locales/en/chat.json b/frontend/src/locales/en/chat.json index 09bfa3b4..75280711 100644 --- a/frontend/src/locales/en/chat.json +++ b/frontend/src/locales/en/chat.json @@ -293,6 +293,12 @@ "searchByNameOrEmployeeId": "Search by name or employee ID, press Enter", "name": "Name", "employeeIdRequired": "Employee ID is required.", + "streamError": { + "networkDisconnectedEmpty": "Connection lost before a reply was received. Please try again.", + "partialInterrupted": "The reply was interrupted. The content above may be incomplete—please ask again.", + "upstreamDisconnected": "The AI service connection was interrupted. Please try again.", + "generic": "The request failed. Please try again." + }, "actions": { "copy": "Copy", "edit": "Edit", diff --git a/frontend/src/locales/th/chat.json b/frontend/src/locales/th/chat.json index 92114b71..766fa52c 100644 --- a/frontend/src/locales/th/chat.json +++ b/frontend/src/locales/th/chat.json @@ -293,6 +293,12 @@ "searchByNameOrEmployeeId": "ค้นหาด้วยชื่อหรือรหัสพนักงาน แล้วกด Enter", "name": "ชื่อ", "employeeIdRequired": "รหัสพนักงานห้ามว่าง", + "streamError": { + "networkDisconnectedEmpty": "การเชื่อมต่อขาดหายก่อนได้รับคำตอบ โปรดลองใหม่อีกครั้ง", + "partialInterrupted": "การสร้างคำตอบถูกขัดจังหวะ เนื้อหาด้านบนอาจไม่สมบูรณ์ โปรดถามใหม่", + "upstreamDisconnected": "การเชื่อมต่อบริการ AI ขาดหาย โปรดลองใหม่อีกครั้ง", + "generic": "คำขอล้มเหลว โปรดลองใหม่อีกครั้ง" + }, "actions": { "copy": "คัดลอก", "edit": "แก้ไข", diff --git a/frontend/src/locales/zh-CN/chat.json b/frontend/src/locales/zh-CN/chat.json index 1a234a8d..a30a41ac 100644 --- a/frontend/src/locales/zh-CN/chat.json +++ b/frontend/src/locales/zh-CN/chat.json @@ -293,6 +293,12 @@ "searchByNameOrEmployeeId": "输入姓名或工号搜索,按回车键查询", "name": "姓名", "employeeIdRequired": "工号不能为空。", + "streamError": { + "networkDisconnectedEmpty": "连接中断,未能获取回答,请稍后重试。", + "partialInterrupted": "回答生成中断,以上内容可能不完整,请重新提问。", + "upstreamDisconnected": "AI 服务连接中断,请稍后重试。", + "generic": "请求失败,请稍后重试。" + }, "actions": { "copy": "复制", "edit": "编辑", diff --git a/frontend/src/locales/zh-TW/chat.json b/frontend/src/locales/zh-TW/chat.json index 06cc8cb7..57ffdd81 100644 --- a/frontend/src/locales/zh-TW/chat.json +++ b/frontend/src/locales/zh-TW/chat.json @@ -293,6 +293,12 @@ "searchByNameOrEmployeeId": "輸入姓名或工號搜尋,按 Enter 查詢", "name": "姓名", "employeeIdRequired": "工號不能為空。", + "streamError": { + "networkDisconnectedEmpty": "連線中斷,未能取得回答,請稍後重試。", + "partialInterrupted": "回答生成中斷,以上內容可能不完整,請重新提問。", + "upstreamDisconnected": "AI 服務連線中斷,請稍後重試。", + "generic": "請求失敗,請稍後重試。" + }, "actions": { "copy": "複製", "edit": "編輯", From c38a56536e931915e5ecf3fd86c8032fdba8a4af Mon Sep 17 00:00:00 2001 From: sophie Date: Mon, 22 Jun 2026 10:30:18 +0800 Subject: [PATCH 03/11] =?UTF-8?q?docs(agents.md):=20=E8=A1=A5=E5=85=85?= =?UTF-8?q?=E5=89=8D=E7=AB=AF=E6=9E=B6=E6=9E=84=E7=BA=A6=E6=9D=9F=E4=B8=8E?= =?UTF-8?q?=E9=94=99=E8=AF=AF=E5=A4=84=E7=90=86=E8=A7=84=E8=8C=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 20 +- .../frontend_architecture_refactor.md | 1125 ++++------------- .../frontend_architecture_refactor_phases.md | 948 ++++++++++++++ 3 files changed, 1230 insertions(+), 863 deletions(-) create mode 100644 docs/refactor/frontend_architecture_refactor_phases.md diff --git a/AGENTS.md b/AGENTS.md index 3e88cfe4..c231030a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,14 +43,23 @@ backend/app/ response_utils.py / errors.py / decorators.py # 统一返回、异常、权限装饰器 backend/migrations/ # Alembic 迁移文件 frontend/src/ - features/ # 按业务域组织(admin / auth / chat) - composables/# Hooks(如 useChat.ts) - views/ components/ i18n.ts + main.ts · App.vue · i18n.ts · config.ts # Vite 入口(保留 src 根) + app/ # 应用基础设施:router/(routes/* · guards)、plugins/pinia + shared/ # 跨域共享(无业务语义) + # api/client · composables · components · layouts · utils · styles + features/ # 业务域垂直切分(新代码主要落在这里) + # auth · workspace · chat · admin · kb + # 域内:api/ · composables/ · views/ · stores/ · components/ + # admin 子模块:modules//*Page.vue + use*Admin.ts + locales/ # i18n 四语言 JSON(zh-CN / zh-TW / en / th),按域拆分 scripts/ # 部署与运维脚本(deploy_compose.sh、healthcheck.sh ...) docs/ # 权威文档(规范、上下文、流程、发布说明) ``` -**约定**:新逻辑优先放入对应 `services/`(后端)或 `features/composables/`(前端),复用既有 `response_utils` / `errors` / `decorators` 模式,不要另造轮子。 +**约定**: + +- **后端**:新逻辑优先放入 `services/`,复用 `response_utils` / `errors` / `decorators` 模式,不要另造轮子。 +- **前端**:Feature-Module + Composables + Pinia;新功能放入 `features//`(`api/` · `composables/` · `views/` 等),跨域通用代码放 `shared/`;HTTP 统一 `@/shared/api/client`。**禁止**在已废弃的 `src/api/`、`src/views/`、`src/composables/` 等路径新增代码。完整规范见 **[docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md)**。 --- @@ -143,6 +152,7 @@ docker compose logs -f hxops-backend - 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。 - ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。 - 📝 **注释两层标准(强制)**:新建或调整代码须满足 §5 文件层 + 函数层注释;AI 生成/重构代码同样适用,不得省略。 +- ⚠️ **错误处理统一契约**:JSON API 使用 `{ success, data | error, request_id }` envelope;后端业务失败 **`raise AppError` 子类**(`app/errors.py`),禁止新写 `jsonify({"error": ...})`;前端 HTTP 统一 **`requestJson`**(`@/shared/api/client`),失败为 **`BusinessError`**,在 composable/view 用 **`useMessage()`** 展示;新增 `error.code` 须同步四语言 **`locales/*/errors.json`**。详见 **[docs/convention/error_handling.md](docs/convention/error_handling.md)**。 - ⚠️ 改动**数据库结构、部署脚本(`scripts/`、`Jenkinsfile`、`docker-compose.yml`)或敏感配置**前,先说明影响面再动手。 合并前最低自检(详见 [新人文档 §3.3](docs/新人环境搭建与配置文档.md)):前后端可启动、`frontend/` 改动后 `npm run build` 通过、关键页面与登录可用。 @@ -183,3 +193,5 @@ docker compose logs -f hxops-backend | Excel/CSV 切块与 Dify 分段 | [docs/kb-excel-dify-chunking.md](docs/kb-excel-dify-chunking.md) | | FAQ 缓存 / 热点发现运维 | [docs/faq_cache_ops_manual.md](docs/faq_cache_ops_manual.md) | | 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) | +| 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) | +| 错误处理规范 | [docs/convention/error_handling.md](docs/convention/error_handling.md) | diff --git a/docs/refactor/frontend_architecture_refactor.md b/docs/refactor/frontend_architecture_refactor.md index 0ffa783b..12f42c7b 100644 --- a/docs/refactor/frontend_architecture_refactor.md +++ b/docs/refactor/frontend_architecture_refactor.md @@ -1,942 +1,349 @@ -# HXOPS 前端重构架构方案 +# HXOPS 前端架构规范(总览版) -> 更新时间:2026-06-11 +> 更新时间:2026-06-22 > 适用范围:`frontend/` 目录 -> 文档定位:定义推荐的目标架构(Feature-Module + Composables + Pinia),作为后续分阶段重构的基准。 +> 读者:组内同事、AI 编程助手(Cursor / Codex 等) +> 文档定位:**当前权威架构与编码约束**。新功能开发与既有代码修改均须遵循本文,避免架构漂移。 +> 分阶段迁移细节见附录:[frontend_architecture_refactor_phases.md](./frontend_architecture_refactor_phases.md) + +--- + +## 0. 如何使用本文 + +| 场景 | 先看 | +|------|------| +| 新增业务功能 | §2 目录结构 → §3 分层 → §6 新功能清单 | +| 修改现有页面 | §4 设计原则 → §5 各域模式 → 对照同域已有代码 | +| AI Agent 写代码 | §4.1 依赖红线 + §7 禁止项 + §8 import 规范 | +| UI / 样式 | [UI 设计系统](../ui/DESIGN_SYSTEM.md) · [UI 编码规范](../ui/UI_CODING_GUIDELINES.md) | + +**合并前自检**:`cd frontend && npm run build` 通过;新增文案四语言齐全(`zh-CN` / `zh-TW` / `en-US` / `th-TH`)。 --- ## 1. 架构选型 -在现有技术栈(Vue 3 + TypeScript + Vite + Vue Router + Vue I18n + TailwindCSS)基础上,采用 **Feature-Module 垂直切分 + Composables 逻辑封装 + Pinia 共享状态** 的组合架构。 +在既有技术栈上,采用 **Feature-Module 垂直切分 + Composables 逻辑封装 + Pinia 共享状态**。 -**选型理由:** +| 维度 | 选型 | 说明 | +|------|------|------| +| 组织方式 | Feature-Module | 按业务域(auth / workspace / chat / admin / kb)垂直拆分,域内自包含 api / composables / views | +| 逻辑封装 | Composables | 副作用、表单、SSE、分页等放入 `use*`,View 只做编排 | +| 跨页状态 | Pinia | 替代 localStorage + CustomEvent 为主的跨组件可变状态 | +| 未采用 | FSD、Element Plus | 目录层级更浅、迁移成本可控;继续 Tailwind + Design Tokens | -- 与 Vue 3 Composition API 天然契合,学习成本低 -- 业务域清晰(聊天 / 管理后台 / 知识库 / 认证),适合按 feature 垂直拆分 -- 相比 FSD(Feature-Sliced Design)目录层级更浅,迁移成本可控 -- 相比引入 Element Plus 等 UI 库,可继续沿用现有 Tailwind 设计体系(`tokens.css`、`components-ds.css`) +**固定技术栈(勿擅自替换):** -**保持不变的技术栈:** - -| 层级 | 选型 | +| 层级 | 技术 | |------|------| -| 框架 | Vue 3(Composition API + ` - -