From 14c5903aef92aac01f5c3101fa42f93acb1946c0 Mon Sep 17 00:00:00 2001 From: sophie <16087569+sophie_liang@user.noreply.gitee.com> Date: Tue, 2 Jun 2026 10:32:44 +0800 Subject: [PATCH 1/8] =?UTF-8?q?fix(exception):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E5=BC=82=E5=B8=B8=E9=94=99=E8=AF=AF=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/user.py | 8 +++++--- backend/tests/test_tasks_0304.py | 10 +++++++--- frontend/src/i18n.ts | 12 ++++++++++++ 3 files changed, 24 insertions(+), 6 deletions(-) diff --git a/backend/app/api/user.py b/backend/app/api/user.py index d8b5e0eb..f78a62f1 100644 --- a/backend/app/api/user.py +++ b/backend/app/api/user.py @@ -632,15 +632,15 @@ def login(): if not user: _write_login_audit('password', 'failed', username=username, reason='user_not_found') db.session.commit() - raise NotFoundError('User not found') + raise AppError(code='AUTH.USER_NOT_FOUND', message='User not found', http_status=404) if not user.check_password(password): _write_login_audit('password', 'failed', user=user, reason='incorrect_password') db.session.commit() - raise UnauthorizedError('Incorrect password') + raise AppError(code='AUTH.INCORRECT_PASSWORD', message='Incorrect password', http_status=401) if user.status != 'active': _write_login_audit('password', 'failed', user=user, reason='account_disabled') db.session.commit() - raise ForbiddenError('Account is disabled') + raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403) _write_login_audit('password', 'success', user=user) db.session.commit() return jsonify(_build_login_payload(user, 'password')) @@ -662,6 +662,8 @@ def login(): except (OperationalError, DatabaseError) as retry_exc: current_app.logger.warning('Password login retry failed: %s', retry_exc) raise ServiceUnavailableError('Database connection failed') + except AppError: + raise except Exception as e: db.session.rollback() current_app.logger.exception('Login error: %s', e) diff --git a/backend/tests/test_tasks_0304.py b/backend/tests/test_tasks_0304.py index 6d9e7dac..62cad169 100644 --- a/backend/tests/test_tasks_0304.py +++ b/backend/tests/test_tasks_0304.py @@ -100,8 +100,12 @@ def test_login_success(client): def test_login_fail(client): res = client.post('/api/user/login', json={'username': 'test1', 'password': 'wrongpassword'}) assert res.status_code == 401 - assert 'Incorrect password' in res.get_json()['error'] - + body = res.get_json() + assert body['error']['code'] == 'AUTH.INCORRECT_PASSWORD' + assert 'Incorrect password' in body['error']['message'] + res = client.post('/api/user/login', json={'username': 'nonexistent', 'password': 'password'}) assert res.status_code == 404 - assert 'User not found' in res.get_json()['error'] + body = res.get_json() + assert body['error']['code'] == 'AUTH.USER_NOT_FOUND' + assert 'User not found' in body['error']['message'] diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index b9a988d3..7018cbe1 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -156,6 +156,9 @@ const messages = { generic: 'Request failed.', codes: { AUTH_UNAUTHORIZED: 'Please log in first.', + AUTH_INCORRECT_PASSWORD: 'Incorrect password', + AUTH_USER_NOT_FOUND: 'User not found', + AUTH_ACCOUNT_DISABLED: 'Account is disabled', AUTH_FORBIDDEN: 'You do not have permission to perform this action.', RESOURCE_NOT_FOUND: 'The requested resource was not found.', RESOURCE_CONFLICT: 'Request conflict. Please refresh and try again.', @@ -1639,6 +1642,9 @@ const messages = { generic: '请求失败。', codes: { AUTH_UNAUTHORIZED: '请先登录。', + AUTH_INCORRECT_PASSWORD: '密码错误', + AUTH_USER_NOT_FOUND: '用户不存在', + AUTH_ACCOUNT_DISABLED: '账号已禁用', AUTH_FORBIDDEN: '你没有权限执行该操作。', RESOURCE_NOT_FOUND: '请求的资源不存在。', RESOURCE_CONFLICT: '请求冲突,请刷新后重试。', @@ -3086,6 +3092,9 @@ const messages = { generic: '請求失敗。', codes: { AUTH_UNAUTHORIZED: '請先登入。', + AUTH_INCORRECT_PASSWORD: '密碼錯誤', + AUTH_USER_NOT_FOUND: '用戶不存在', + AUTH_ACCOUNT_DISABLED: '帳號已禁用', AUTH_FORBIDDEN: '你沒有權限執行此操作。', RESOURCE_NOT_FOUND: '請求的資源不存在。', RESOURCE_CONFLICT: '請求衝突,請刷新後重試。', @@ -4408,6 +4417,9 @@ const messages = { generic: 'คำขอล้มเหลว', codes: { AUTH_UNAUTHORIZED: 'กรุณาเข้าสู่ระบบก่อน', + AUTH_INCORRECT_PASSWORD: 'รหัสผ่านไม่ถูกต้อง', + AUTH_USER_NOT_FOUND: 'ไม่พบผู้ใช้', + AUTH_ACCOUNT_DISABLED: 'บัญชีถูกปิดใช้งาน', AUTH_FORBIDDEN: 'คุณไม่มีสิทธิ์ดำเนินการนี้', RESOURCE_NOT_FOUND: 'ไม่พบทรัพยากรที่ร้องขอ', RESOURCE_CONFLICT: 'คำขอขัดแย้ง โปรดรีเฟรชแล้วลองใหม่', From 1b56810cc71b918c1fa2e2b908a6956d3ca44b57 Mon Sep 17 00:00:00 2001 From: sophie <16087569+sophie_liang@user.noreply.gitee.com> Date: Tue, 2 Jun 2026 13:17:00 +0800 Subject: [PATCH 2/8] fix bugs --- backend/app/api/admin.py | 18 ++-- backend/tests/test_admin.py | 3 +- backend/tests/test_user_fields.py | 9 +- frontend/src/i18n.ts | 16 ++++ frontend/src/views/AdminView.vue | 135 ++++++++++++++---------------- 5 files changed, 101 insertions(+), 80 deletions(-) diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py index c1457427..be761240 100644 --- a/backend/app/api/admin.py +++ b/backend/app/api/admin.py @@ -397,16 +397,24 @@ def list_users(): @require_admin def create_user(): data = request.get_json() or {} - if not data.get('username'): - raise AppError(code='USER.USERNAME_REQUIRED', message='Username is required', http_status=400, details={'field': 'username'}) + required_field_errors = ( + ('username', 'USER.USERNAME_REQUIRED', 'Username is required'), + ('password', 'USER.PASSWORD_REQUIRED', 'Password is required'), + ('email', 'USER.EMAIL_REQUIRED', 'Email is required'), + ('real_name', 'USER.REAL_NAME_REQUIRED', 'Real name is required'), + ('employee_id', 'USER.EMPLOYEE_ID_REQUIRED', 'Employee ID is required'), + ('phone_number', 'USER.PHONE_REQUIRED', 'Phone number is required'), + ) + for field, code, message in required_field_errors: + if _empty_to_none(data.get(field)) is None: + raise AppError(code=code, message=message, http_status=400, details={'field': field}) if db.session.query(User).filter_by(username=data['username']).first(): raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS', details={'field': 'username'}) email = _empty_to_none(data.get('email')) - if email is not None and (not _is_valid_email(email)): + if not _is_valid_email(email): raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'}) 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'))) - if data.get('password'): - user.set_password(data['password']) + 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 diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py index 003003b4..12f576a5 100644 --- a/backend/tests/test_admin.py +++ b/backend/tests/test_admin.py @@ -60,7 +60,8 @@ def test_user_management(client, admin_headers): "role": "user", "password": "password123", "real_name": "Test User", - "employee_id": "EMP001" + "employee_id": "EMP001", + "phone_number": "13800000001" } response = client.post('/api/admin/users', json=new_user, headers=admin_headers) assert response.status_code == 201 diff --git a/backend/tests/test_user_fields.py b/backend/tests/test_user_fields.py index b05375fc..010e484f 100644 --- a/backend/tests/test_user_fields.py +++ b/backend/tests/test_user_fields.py @@ -52,7 +52,8 @@ def test_admin_duplicate_employee_id(client, admin_headers): "password": "pwd", "email": "au1@e.com", "real_name": "Admin User 1", - "employee_id": "ADM001" + "employee_id": "ADM001", + "phone_number": "13800000011" } response = client.post('/api/admin/users', json=u1, headers=admin_headers) assert response.status_code == 201 @@ -63,7 +64,8 @@ def test_admin_duplicate_employee_id(client, admin_headers): "password": "pwd", "email": "au2@e.com", "real_name": "Admin User 2", - "employee_id": "ADM001" + "employee_id": "ADM001", + "phone_number": "13800000012" } response = client.post('/api/admin/users', json=u2, headers=admin_headers) assert response.status_code == 400 @@ -76,7 +78,8 @@ def test_admin_duplicate_employee_id(client, admin_headers): "password": "pwd", "email": "au3@e.com", "real_name": "Admin User 3", - "employee_id": "ADM003" + "employee_id": "ADM003", + "phone_number": "13800000013" } res = client.post('/api/admin/users', json=u3, headers=admin_headers) u3_id = res.json['id'] diff --git a/frontend/src/i18n.ts b/frontend/src/i18n.ts index 7018cbe1..9d85770e 100644 --- a/frontend/src/i18n.ts +++ b/frontend/src/i18n.ts @@ -546,7 +546,11 @@ const messages = { confirmClean: 'Are you sure you want to delete all REJECTED users?', confirmBatchDelete: 'Are you sure you want to delete {count} users?', msgs: { + realNameRequired: 'Real name is required', + employeeIdRequired: 'Employee ID is required', + phoneRequired: 'Phone number is required', usernameRequired: 'Username is required', + emailRequired: 'Email is required', passwordRequired: 'Password is required for new users', invalidEmail: 'Invalid email format', created: 'User created successfully', @@ -2033,7 +2037,11 @@ const messages = { confirmClean: '确定要删除所有“已拒绝”的用户吗?', confirmBatchDelete: '确定要删除选中的 {count} 个用户吗?', msgs: { + realNameRequired: '真实姓名必填', + employeeIdRequired: '工号必填', + phoneRequired: '手机号必填', usernameRequired: '用户名必填', + emailRequired: '邮箱必填', passwordRequired: '新用户必须设置密码', invalidEmail: '邮箱格式不正确', created: '用户创建成功', @@ -3483,7 +3491,11 @@ const messages = { confirmClean: '確定要刪除所有“已拒絕”的用戶嗎?', confirmBatchDelete: '確定要刪除選中的 {count} 個用戶嗎?', msgs: { + realNameRequired: '真實姓名必填', + employeeIdRequired: '工號必填', + phoneRequired: '手機號必填', usernameRequired: '用戶名必填', + emailRequired: '郵箱必填', passwordRequired: '新用戶必須設置密碼', invalidEmail: '郵箱格式不正確', created: '用戶創建成功', @@ -4725,7 +4737,11 @@ const messages = { confirmClean: 'คุณแน่ใจหรือไม่ว่าต้องการลบผู้ใช้ที่ถูกปฏิเสธทั้งหมด?', confirmBatchDelete: 'คุณแน่ใจหรือไม่ว่าต้องการลบผู้ใช้ {count} คน?', msgs: { + realNameRequired: 'กรุณากรอกชื่อจริง', + employeeIdRequired: 'กรุณากรอกรหัสพนักงาน', + phoneRequired: 'กรุณากรอกเบอร์โทรศัพท์', usernameRequired: 'กรุณากรอกชื่อผู้ใช้', + emailRequired: 'กรุณากรอกอีเมล', passwordRequired: 'ต้องระบุรหัสผ่านสำหรับผู้ใช้ใหม่', invalidEmail: 'รูปแบบอีเมลไม่ถูกต้อง', created: 'สร้างผู้ใช้สำเร็จ', diff --git a/frontend/src/views/AdminView.vue b/frontend/src/views/AdminView.vue index cfff5f95..a164d9b5 100644 --- a/frontend/src/views/AdminView.vue +++ b/frontend/src/views/AdminView.vue @@ -366,20 +366,48 @@ const openEditUserModal = (user: UserRow) => { }; const saveUser = async () => { - if (!editingUser.value.username) { - msg.warning(t('admin.user.msgs.usernameRequired')); - return; - } + const isCreate = !editingUser.value.id; - const email = (editingUser.value.email || '').trim(); - if (email && !EMAIL_PATTERN.test(email)) { - msg.warning(t('admin.user.msgs.invalidEmail')); - return; - } - - if (!editingUser.value.id && !editingUser.value.password) { - msg.warning(t('admin.user.msgs.passwordRequired')); - return; + if (isCreate) { + if (!(editingUser.value.real_name || '').trim()) { + msg.warning(t('admin.user.msgs.realNameRequired')); + return; + } + if (!(editingUser.value.employee_id || '').trim()) { + msg.warning(t('admin.user.msgs.employeeIdRequired')); + return; + } + if (!(editingUser.value.phone_number || '').trim()) { + msg.warning(t('admin.user.msgs.phoneRequired')); + return; + } + if (!(editingUser.value.username || '').trim()) { + msg.warning(t('admin.user.msgs.usernameRequired')); + return; + } + const email = (editingUser.value.email || '').trim(); + if (!email) { + msg.warning(t('admin.user.msgs.emailRequired')); + return; + } + if (!EMAIL_PATTERN.test(email)) { + msg.warning(t('admin.user.msgs.invalidEmail')); + return; + } + if (!(editingUser.value.password || '').trim()) { + msg.warning(t('admin.user.msgs.passwordRequired')); + return; + } + } else { + if (!editingUser.value.username) { + msg.warning(t('admin.user.msgs.usernameRequired')); + return; + } + const email = (editingUser.value.email || '').trim(); + if (email && !EMAIL_PATTERN.test(email)) { + msg.warning(t('admin.user.msgs.invalidEmail')); + return; + } } isSaving.value = true; @@ -1350,7 +1378,6 @@ interface Department { } const departments = ref([]); const editingDept = ref>({}); -const isManagingDepts = ref(false); const loadDepartments = async () => { try { @@ -3427,12 +3454,6 @@ const handlePermissionImport = async (event: Event) => {

{{ t('admin.user.subtitle') }}

-
@@ -6234,51 +6272,6 @@ const handlePermissionImport = async (event: Event) => { - -
-
-

{{ t('admin.user.manageDepts') }}

- -
- - -
- -
-
{{ t('admin.dept.noDepts') }}
-
- {{ d.name }} - -
-
- -
- -
-
-
- Date: Tue, 2 Jun 2026 13:34:50 +0800 Subject: [PATCH 3/8] =?UTF-8?q?=E8=AF=B7=E5=81=87=E7=94=B3=E8=AF=B7?= =?UTF-8?q?=E7=9B=B4=E6=8E=A5=E9=97=AE=E7=AD=94dify=E7=9F=A5=E8=AF=86?= =?UTF-8?q?=E5=BA=93=E6=8A=A5=E9=94=99bug=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/admin.py | 2 +- backend/app/services/dify.py | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py index be761240..be75e3ab 100644 --- a/backend/app/api/admin.py +++ b/backend/app/api/admin.py @@ -303,7 +303,7 @@ def test_agent(id): payload = {'inputs': {'query': '系统连通性测试,请简短回复OK。'}, 'response_mode': 'blocking', 'user': 'admin_test'} else: request_url = DifyService._build_chat_messages_url(base_url) - payload = {'inputs': {}, 'query': '系统连通性测试,请简短回复OK。', 'response_mode': 'blocking', 'conversation_id': '', 'user': 'admin_test'} + payload = {'inputs': {}, 'query': '系统连通性测试,请简短回复OK。', 'response_mode': 'blocking', 'user': 'admin_test'} headers = {'Authorization': f'Bearer {agent.dify_api_key}', 'Content-Type': 'application/json'} try: resp = requests.post(request_url, headers=headers, json=payload, timeout=(5, 25)) diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index 8a8a205a..19f30dd4 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -525,9 +525,10 @@ class DifyService: 'inputs': {}, 'query': query, 'response_mode': 'streaming', - 'conversation_id': normalized_conversation_id, 'user': str(user_id), } + if normalized_conversation_id: + payload['conversation_id'] = normalized_conversation_id if files: payload['files'] = files From 854bc8e4dbfe2368ca4941baa5a38bcf03e420d9 Mon Sep 17 00:00:00 2001 From: "DESKTOP-JKIE562\\PC" <1013397054@qq.com> Date: Tue, 2 Jun 2026 21:07:04 +0800 Subject: [PATCH 4/8] =?UTF-8?q?=E5=8E=9F=E5=A7=8B=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E6=B0=94=E6=B3=A1=E6=98=A0=E5=B0=84=E9=94=99=E8=AF=AF=20+=20?= =?UTF-8?q?=E5=A4=9A=E7=89=88=E6=9C=AC=E4=B8=8B=E8=BD=BD=E9=94=99=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/chat.py | 14 +-- backend/app/api/integration.py | 110 +++++++++++++++--- backend/app/api/knowledge_base.py | 9 +- backend/app/services/dify.py | 9 +- backend/app/services/integration_api.py | 20 +++- .../knowledge_cleaning/dify_sync_service.py | 17 +-- frontend/src/views/ChatView.vue | 104 +++++++++++------ 7 files changed, 203 insertions(+), 80 deletions(-) diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index 8e969446..4664c2dc 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -246,10 +246,13 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * log = db.session.query(ChatLog).filter(stmt).params(url=f'%{raw_url}%').order_by(ChatLog.created_at.desc()).first() if log and log.retriever_resources: for r in log.retriever_resources: + if not isinstance(r, dict): + continue source_url = str(r.get('source_download_url') or '') if source_url == raw_url or (source_url and source_url.split('&token=')[0] == raw_url.split('&token=')[0]): - dataset_id = dataset_id or str(r.get('dataset_id') or r.get('metadata', {}).get('dataset_id') or '').strip() - remote_document_id = remote_document_id or str(r.get('remote_document_id') or r.get('metadata', {}).get('remote_document_id') or r.get('document_id') or '').strip() + resolved_dataset_id, resolved_remote_document_id = DifyService._extract_dify_ids(r) + dataset_id = dataset_id or str(resolved_dataset_id or '').strip() + remote_document_id = remote_document_id or str(resolved_remote_document_id or '').strip() if dataset_id and remote_document_id: break except Exception as e: @@ -1411,12 +1414,6 @@ def resolve_source_file(): source_ext = str(payload.get('source_ext') or '').strip().lower() source_download_url = payload.get('source_download_url') - if source_ext in {'txt', 'md', 'markdown', 'csv', 'vtt', 'properties', 'html', 'htm'}: - current_agent = getattr(g, 'current_agent', None) - source_download_url = ( - f"{request.host_url.rstrip('/')}/api/chat/source-file-text" - f"?agent_id={getattr(current_agent, 'id', '')}&dataset_id={dataset_id}&remote_document_id={remote_document_id}" - ) return jsonify({ 'dataset_id': dataset_id, @@ -1649,7 +1646,6 @@ def preview_file_raw(): # 避免在服务端走旧版转换链路导致长时间卡住。 needs_pdf_conversion = ( request.args.get('download') != '1' - and original_ext in ('doc', 'ppt', 'pptx') and ext in ('doc', 'ppt', 'pptx') ) if needs_pdf_conversion: diff --git a/backend/app/api/integration.py b/backend/app/api/integration.py index 3bfee934..1a87683e 100644 --- a/backend/app/api/integration.py +++ b/backend/app/api/integration.py @@ -12,6 +12,95 @@ from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status integration_bp = Blueprint('integration', __name__) + +def _integration_token_secret() -> str: + configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip() + return configured or str(current_app.config.get('SECRET_KEY') or 'default-secret').strip() + + +def _decode_integration_token(token: str | None) -> dict | None: + normalized_token = str(token or '').strip() + if not normalized_token: + return None + try: + import jwt + payload = jwt.decode( + normalized_token, + _integration_token_secret(), + algorithms=['HS256'], + ) + return payload if isinstance(payload, dict) else None + except Exception as e: + current_app.logger.warning(f"Integration API token validation failed: {e}") + return None + + +def _build_download_url(document_id: int, *, kind: str, version_id: int | None = None) -> str: + base_url = _integration_base_url() + url = f'{base_url}/api/integration/files/{document_id}/download?kind={kind}' + if version_id is not None: + url += f'&version_id={version_id}' + return url + + +def _version_query(): + return ( + db.session.query(KbDocumentVersion) + .join(KbDocument, KbDocument.id == KbDocumentVersion.document_id) + .filter(KbDocument.is_deleted.is_(False)) + ) + + +def _resolve_requested_version(file_id: int) -> tuple[KbDocumentVersion | None, KbDocument | None]: + requested_version_id = request.args.get('version_id', type=int) + token_payload = _decode_integration_token(request.args.get('token')) + if isinstance(token_payload, dict): + token_version_id = token_payload.get('version_id') + if token_version_id is not None: + try: + requested_version_id = int(token_version_id) + except (TypeError, ValueError): + current_app.logger.warning( + 'Integration API token carried invalid version_id: %r', + token_version_id, + ) + dataset_id = str(token_payload.get('dataset_id') or '').strip() + remote_document_id = str(token_payload.get('remote_document_id') or '').strip() + if dataset_id and remote_document_id: + record = ( + db.session.query(KbDifySyncRecord) + .join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id) + .join(KbDocument, KbDocument.id == KbDocumentVersion.document_id) + .options(joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.document)) + .filter( + KbDocument.is_deleted.is_(False), + KbDocument.id == file_id, + KbDifySyncRecord.dataset_id == dataset_id, + KbDifySyncRecord.remote_document_id == remote_document_id, + ) + .order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc()) + .first() + ) + if record and record.document_version and record.document_version.document: + return record.document_version, record.document_version.document + + if requested_version_id is not None: + version = ( + _version_query() + .filter( + KbDocumentVersion.id == requested_version_id, + KbDocumentVersion.document_id == file_id, + ) + .first() + ) + if version: + return version, version.document + + document = _document_query().filter(KbDocument.id == file_id).first() + if not document: + return None, None + return _current_version(document), document + def _require_integration_key(): configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip() incoming = str(request.headers.get('X-Integration-Key') or '').strip() @@ -24,15 +113,8 @@ def _require_integration_key(): return None token = request.args.get('token') - if token: - try: - import jwt - secret = configured or str(current_app.config.get('SECRET_KEY') or 'default-secret').strip() - jwt.decode(token, secret, algorithms=['HS256']) - return None - except Exception as e: - current_app.logger.warning(f"Integration API token validation failed: {e}") - pass + if token and _decode_integration_token(token): + return None raise UnauthorizedError('Unauthorized') @@ -57,9 +139,8 @@ def _serialize_integration_document(document: KbDocument, *, version: KbDocument if not version: abort(404, description='No current version found.') sync_record = sync_record or (next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None) or (version.sync_records[0] if getattr(version, 'sync_records', None) else None)) - base_url = _integration_base_url() - source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source' - markdown_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=md' if version.cleaned_file_path or version.cleaned_preview_path else None + source_download_url = _build_download_url(document.id, kind='source', version_id=version.id) + markdown_download_url = _build_download_url(document.id, kind='md', version_id=version.id) if version.cleaned_file_path or version.cleaned_preview_path else None return {'document_id': document.id, 'knowledge_base': {'id': document.group.id if document.group else None, 'name': document.group.name if document.group else None, 'department_id': document.group.department_id if document.group else None, 'dify_dataset_id': document.group.dify_dataset_id if document.group else None}, 'title': document.title, 'source_filename': version.source_file_name, 'source_ext': version.source_file_ext, 'file_name': version.source_file_name, 'version_id': version.id, 'version_no': version.version_no, 'convert_status': version.status, 'sync_status': sync_record.status if sync_record else None, 'uploaded_at': version.created_at.isoformat() if version.created_at else None, 'converted_at': version.converted_at.isoformat() if version.converted_at else None, 'download_url_expires_at': None, 'source_download_url': source_download_url, 'markdown_download_url': markdown_download_url, 'markdown_download_url_expires_at': None, 'markdown_public_url': markdown_download_url, 'dify': {'dataset_id': sync_record.dataset_id if sync_record else document.group.dify_dataset_id if document.group else None, 'remote_document_id': sync_record.remote_document_id if sync_record else None, 'status': sync_record.status if sync_record else None, 'last_synced_at': sync_record.synced_at.isoformat() if sync_record and sync_record.synced_at else None}} def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict: @@ -189,13 +270,12 @@ def resolve_files_by_dify(): @integration_bp.route('/files//download', methods=['GET']) def download_file(file_id: int): kind = str(request.args.get('kind') or 'md').strip().lower() - document = _document_query().filter(KbDocument.id == file_id).first() + version, document = _resolve_requested_version(file_id) if not document: raise NotFoundError('Document not found.') - version = _current_version(document) if not version: raise NotFoundError('No version found.') path, filename = _resolve_download_path(version, kind) if not path.exists(): raise NotFoundError('File not found on disk.') - return send_file(path, as_attachment=True, download_name=filename) \ No newline at end of file + return send_file(path, as_attachment=True, download_name=filename) diff --git a/backend/app/api/knowledge_base.py b/backend/app/api/knowledge_base.py index d0479035..450fd790 100644 --- a/backend/app/api/knowledge_base.py +++ b/backend/app/api/knowledge_base.py @@ -26,12 +26,9 @@ def _safe_upload_filename(raw_filename: str | None) -> str: original_name = Path(raw_filename or '').name.strip() if not original_name: return 'uploaded_file' - original_path = Path(original_name) - safe_stem = secure_filename(original_path.stem) - suffix = original_path.suffix.lower() - if not safe_stem: - safe_stem = 'uploaded_file' - return f'{safe_stem}{suffix}' + import re + safe_name = re.sub(r'[\\/*?:"<>|]', '_', original_name) + return safe_name or 'uploaded_file' def _require_user(): user = get_current_user() diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index 19f30dd4..a9b759ce 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -867,22 +867,23 @@ class DifyService: remote_document_id = ( resource.get('remote_document_id') or resource.get('dify_document_id') - or resource.get('document_id') + or resource.get('source_document_id') or resource.get('doc_id') or metadata.get('remote_document_id') or metadata.get('dify_document_id') - or metadata.get('document_id') + or metadata.get('source_document_id') or metadata.get('doc_id') or DifyService._find_first_by_keys( resource, [ 'remote_document_id', 'dify_document_id', - 'document_id', - 'doc_id', 'source_document_id', + 'doc_id', ], ) + or resource.get('document_id') + or metadata.get('document_id') ) return dataset_id, remote_document_id diff --git a/backend/app/services/integration_api.py b/backend/app/services/integration_api.py index 3227bc39..af193887 100644 --- a/backend/app/services/integration_api.py +++ b/backend/app/services/integration_api.py @@ -203,13 +203,19 @@ class IntegrationApiService: from app import db from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument + normalized_dataset_id = str(dataset_id or '').strip() + normalized_remote_document_id = str(remote_document_id or '').strip() + if not normalized_dataset_id or not normalized_remote_document_id: + return None + record = ( db.session.query(KbDifySyncRecord) .join(KbDocumentVersion, KbDocumentVersion.id == KbDifySyncRecord.document_version_id) .join(KbDocument, KbDocument.id == KbDocumentVersion.document_id) .filter( KbDocument.is_deleted.is_(False), - KbDifySyncRecord.remote_document_id == remote_document_id, + KbDifySyncRecord.dataset_id == normalized_dataset_id, + KbDifySyncRecord.remote_document_id == normalized_remote_document_id, ) .order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc()) .first() @@ -236,13 +242,17 @@ class IntegrationApiService: secret = str(current_app.config.get('SECRET_KEY') or 'default-secret').strip() exp = int(time.time()) + 86400 * 7 # 7 days expiration for local tokens payload = { - 'dataset_id': 'local', - 'remote_document_id': remote_document_id, + 'dataset_id': normalized_dataset_id, + 'remote_document_id': normalized_remote_document_id, + 'version_id': version.id, 'exp': exp } token = jwt.encode(payload, secret, algorithm='HS256') - source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source&token={token}' + source_download_url = ( + f'{base_url}/api/integration/files/{document.id}/download' + f'?kind=source&version_id={version.id}&token={token}' + ) return { "source_download_url": source_download_url, @@ -266,7 +276,7 @@ class IntegrationApiService: base_url = IntegrationApiService.get_base_url() api_key = IntegrationApiService.get_api_key() if not base_url or not api_key: - return None + return IntegrationApiService._lookup_local_db(dataset_id, remote_document_id) url = f"{base_url}/api/integration/dify-file" headers = {"X-Integration-Key": api_key} diff --git a/backend/app/services/knowledge_cleaning/dify_sync_service.py b/backend/app/services/knowledge_cleaning/dify_sync_service.py index 36285771..e28f217a 100644 --- a/backend/app/services/knowledge_cleaning/dify_sync_service.py +++ b/backend/app/services/knowledge_cleaning/dify_sync_service.py @@ -177,6 +177,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | remote_document_id = None remote_document_name = None + upload_name = version.source_file_name or document.title if existing_record and existing_record.dataset_id == dataset_id and existing_record.sync_hash == sync_hash: try: payload = service.get_document( @@ -184,23 +185,23 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | document_id=existing_record.remote_document_id, ) remote_document_id = payload.get('id') or existing_record.remote_document_id - remote_document_name = payload.get('name') or existing_record.remote_document_name or document.title + remote_document_name = payload.get('name') or existing_record.remote_document_name or upload_name except KbDifySyncError as exc: if not _is_remote_document_missing(str(exc)): raise payload = service.create_document_by_text( dataset_id=dataset_id, - name=document.title, + name=upload_name, text=text, ) remote_document_id = payload.get('document', {}).get('id') or payload.get('id') - remote_document_name = payload.get('document', {}).get('name') or document.title + remote_document_name = payload.get('document', {}).get('name') or upload_name elif existing_record and existing_record.dataset_id == dataset_id: try: payload = service.update_document_by_text( dataset_id=dataset_id, document_id=existing_record.remote_document_id, - name=document.title, + name=upload_name, text=text, ) except KbDifySyncError as exc: @@ -208,19 +209,19 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | raise payload = service.create_document_by_text( dataset_id=dataset_id, - name=document.title, + name=upload_name, text=text, ) remote_document_id = payload.get('document', {}).get('id') or payload.get('id') or existing_record.remote_document_id - remote_document_name = payload.get('document', {}).get('name') or document.title + remote_document_name = payload.get('document', {}).get('name') or upload_name else: payload = service.create_document_by_text( dataset_id=dataset_id, - name=document.title, + name=upload_name, text=text, ) remote_document_id = payload.get('document', {}).get('id') or payload.get('id') - remote_document_name = payload.get('document', {}).get('name') or document.title + remote_document_name = payload.get('document', {}).get('name') or upload_name if not remote_document_id: raise KbDifySyncError('Dify 未返回远端文档 ID') diff --git a/frontend/src/views/ChatView.vue b/frontend/src/views/ChatView.vue index 2cd2b85e..cd091f65 100644 --- a/frontend/src/views/ChatView.vue +++ b/frontend/src/views/ChatView.vue @@ -311,18 +311,57 @@ const findFirstByKeys = (payload: any, keyCandidates: string[]): string => { return ''; }; +const findDirectByKeys = (payloads: any[], keyCandidates: string[]): string => { + for (const payload of payloads) { + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) continue; + for (const key of keyCandidates) { + const value = payload?.[key]; + if (value != null && String(value).trim()) { + return String(value).trim(); + } + } + } + return ''; +}; + const getResourceIds = (item: any) => { + const metadata = item?.metadata && typeof item.metadata === 'object' && !Array.isArray(item.metadata) + ? item.metadata + : null; const datasetId = findFirstByKeys(item, ['dataset_id', 'dify_dataset_id', 'knowledge_base_id', 'kb_id']); - const remoteDocumentId = findFirstByKeys(item, [ + const remoteDocumentId = findDirectByKeys([item, metadata], [ 'remote_document_id', 'dify_document_id', - 'document_id', - 'doc_id', 'source_document_id', - ]); + 'doc_id', + ]) || findFirstByKeys(item, [ + 'remote_document_id', + 'dify_document_id', + 'source_document_id', + 'doc_id', + ]) || findDirectByKeys([item, metadata], ['document_id']); return { datasetId, remoteDocumentId }; }; +const canPreviewSourceLink = (link: Partial | null | undefined) => { + if (!link) return false; + return Boolean(link.url || (link.datasetId && link.remoteDocumentId)); +}; + +const buildSourceLinkKey = (name: string, datasetId?: string, remoteDocumentId?: string, url?: string) => { + const normalizedName = String(name || '').trim(); + const normalizedDatasetId = String(datasetId || '').trim(); + const normalizedRemoteDocumentId = String(remoteDocumentId || '').trim(); + const normalizedUrl = String(url || '').split('?')[0]; + if (normalizedDatasetId && normalizedRemoteDocumentId) { + return `${normalizedName}|${normalizedDatasetId}|${normalizedRemoteDocumentId}`; + } + if (looksLikeFileName(normalizedName)) { + return normalizedUrl ? `${normalizedName}|${normalizedUrl}` : normalizedName; + } + return `${normalizedName}|${normalizedUrl}`; +}; + const isMarkdownFileName = (name: string) => /\.(md|markdown)$/i.test((name || '').trim()); const isMarkdownByUrl = (url: string) => /\.(md|markdown)(?:$|\?)/i.test((url || '').toLowerCase()); @@ -405,8 +444,8 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => { const forceName = item?.source_filename || item?.document_name || item?.title; const forceUrl = normalizeUrl(item?.source_download_url || item?.url || ''); - if (forceName) { - const key = forceName; + if (forceName && (forceUrl || (datasetId && remoteDocumentId))) { + const key = buildSourceLinkKey(forceName, datasetId, remoteDocumentId, forceUrl); mergeSourceLink(key, { name: forceName, ...(forceUrl ? { url: forceUrl } : {}), @@ -442,8 +481,7 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => { // 根据配置决定是否显示 MD 文件 if (isMarkdownFileName(name) || isMarkdownByUrl(url)) continue; - // Deduplicate by name if it looks like a filename, else by name + base URL - const key = looksLikeFileName(name) ? name : `${name}|${url.split('?')[0]}`; + const key = buildSourceLinkKey(name, datasetId, remoteDocumentId, url); mergeSourceLink(key, { name, url, @@ -452,7 +490,7 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => { }); } } - const links = Array.from(map.values()); + const links = Array.from(map.values()).filter((link) => canPreviewSourceLink(link)); // 暂时注释掉 isPreferredSourceLink 的过滤,让所有解析出来的气泡都能显示 // const preferred = links.filter((l) => isPreferredSourceLink(l.url)); // return preferred.length > 0 ? preferred : links; @@ -481,18 +519,19 @@ const getMessageLinks = (msg: any): SourceFileLink[] => { }); }; for (const link of links) { + if (!canPreviewSourceLink(link)) continue; const linkUrl = link.url || ''; if (linkUrl && isChunkLikeLink(linkUrl)) continue; // 文件名有效时,保留文件按钮(即便 URL 是临时签名地址)。 if (isNoisySourceName(link.name)) continue; if (isMarkdownFileName(link.name) || isMarkdownByUrl(linkUrl)) continue; if (isMarkdownFileName(link.name)) { - const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${linkUrl.split('?')[0]}`; + const key = buildSourceLinkKey(link.name, link.datasetId, link.remoteDocumentId, linkUrl); mergeMessageLink(key, link); continue; } if (linkUrl && isNoisySourceUrl(linkUrl) && !looksLikeFileName(link.name)) continue; - const key = looksLikeFileName(link.name) ? link.name : `${link.name}|${linkUrl.split('?')[0]}`; + const key = buildSourceLinkKey(link.name, link.datasetId, link.remoteDocumentId, linkUrl); mergeMessageLink(key, link); } }; @@ -561,33 +600,32 @@ const filePreviewVisible = ref(false); const previewFile = ref<{ name: string; url: string; actualExt?: string } | null>(null); const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string; url: string; actualExt?: string }> => { - if (file.url) { - return { - name: file.name, - url: file.url, - actualExt: file.actualExt, - }; + if (file.datasetId && file.remoteDocumentId) { + const data = await resolveChatSourceFile({ + agent_id: agentId, + dataset_id: file.datasetId, + remote_document_id: file.remoteDocumentId, + }); + + const resolvedUrl = normalizeUrl(data?.source_download_url || ''); + if (resolvedUrl) { + return { + ...file, + url: resolvedUrl, + name: data?.source_filename || file.name, + actualExt: String(data?.source_ext || '').trim().toLowerCase() || undefined, + }; + } } - if (!file.datasetId || !file.remoteDocumentId) { + + if (!file.url) { throw new Error('当前源文件暂未返回可预览链接'); } - const data = await resolveChatSourceFile({ - agent_id: agentId, - dataset_id: file.datasetId, - remote_document_id: file.remoteDocumentId, - }); - - const resolvedUrl = normalizeUrl(data?.source_download_url || ''); - if (!resolvedUrl) { - throw new Error('未查询到源文件下载地址'); - } - return { - ...file, - url: resolvedUrl, - name: data?.source_filename || file.name, - actualExt: String(data?.source_ext || '').trim().toLowerCase() || undefined, + name: file.name, + url: file.url, + actualExt: file.actualExt, }; }; From 07a1494a1e3aacd9a91061073776f3cd25748dc6 Mon Sep 17 00:00:00 2001 From: "DESKTOP-JKIE562\\PC" <1013397054@qq.com> Date: Tue, 2 Jun 2026 21:42:04 +0800 Subject: [PATCH 5/8] =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=9F=A5=E7=9C=8B?= =?UTF-8?q?=E6=BA=90=E6=96=87=E4=BB=B6=E6=8A=A5objact?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/chat.py | 38 ++++++++++---- frontend/src/components/FilePreviewModal.vue | 53 ++++++++++++++++---- 2 files changed, 69 insertions(+), 22 deletions(-) diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index 4664c2dc..33a8c3a2 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -303,12 +303,26 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * ctype = (resp.headers.get('content-type') or '').split(';')[0].strip().lower() if resp.status_code == 401: return True + if resp.status_code in (403, 404) and 'token=' in file_url: + return True if ctype == 'application/json': body = (resp.content or b'')[:512].decode('utf-8', errors='ignore').lower() if 'unauthorized' in body or '"error"' in body: return True return False - if base_url and file_url.startswith(base_url) and ('token=' in file_url): + + def _retry_with_refreshed_url(raw_url: str): + refreshed_url = _resolve_latest_integration_url(raw_url) + if not refreshed_url or refreshed_url == raw_url: + return None, raw_url + retry_headers = _build_headers(refreshed_url) + try: + return requests.get(refreshed_url, headers=retry_headers, timeout=(5, 20)), refreshed_url + except requests.RequestException as e: + current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e) + return None, refreshed_url + + if 'token=' in file_url: try: parsed = urlparse(file_url) qs = parse_qs(parsed.query) @@ -330,18 +344,20 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * except requests.RequestException as e: current_app.logger.warning('[file-preview] upstream request failed: %s', e) return (None, None, ('failed to fetch source file', 502)) - if base_url and file_url.startswith(base_url) and ('token=' in file_url) and _should_refresh_from_response(upstream): - refreshed_url = _resolve_latest_integration_url(file_url) - if refreshed_url != file_url: - headers = _build_headers(refreshed_url) - try: - upstream = requests.get(refreshed_url, headers=headers, timeout=(5, 20)) - file_url = refreshed_url - except requests.RequestException as e: - current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e) - return (None, None, ('failed to fetch source file', 502)) + if 'token=' in file_url and _should_refresh_from_response(upstream): + refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url) + if refreshed_upstream is not None: + upstream = refreshed_upstream + file_url = refreshed_url if upstream.status_code != 200: + if 'token=' in file_url: + refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url) + if refreshed_upstream is not None: + upstream = refreshed_upstream + file_url = refreshed_url current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}") + if upstream.status_code == 404: + return None, None, ('source file not found', 404) return None, None, (f'upstream returned status {upstream.status_code}', 502) content = upstream.content or b'' diff --git a/frontend/src/components/FilePreviewModal.vue b/frontend/src/components/FilePreviewModal.vue index b674c376..1febc1b9 100644 --- a/frontend/src/components/FilePreviewModal.vue +++ b/frontend/src/components/FilePreviewModal.vue @@ -129,6 +129,42 @@ const clearOfficeObjectUrl = () => { officeKind.value = null; }; +const extractErrorMessage = (payload: any, fallback: string) => { + if (!payload) return fallback; + if (typeof payload === 'string' && payload.trim()) return payload.trim(); + if (typeof payload?.message === 'string' && payload.message.trim()) return payload.message.trim(); + if (typeof payload?.error === 'string' && payload.error.trim()) return payload.error.trim(); + if (typeof payload?.error?.message === 'string' && payload.error.message.trim()) return payload.error.message.trim(); + if (typeof payload?.detail === 'string' && payload.detail.trim()) return payload.detail.trim(); + return fallback; +}; + +const readErrorMessage = async (res: Response) => { + const fallback = `HTTP ${res.status}`; + const contentType = (res.headers.get('content-type') || '').toLowerCase(); + if (contentType.includes('application/json')) { + const payload = await res.json().catch(() => null); + return extractErrorMessage(payload, fallback); + } + const text = await res.text().catch(() => ''); + return extractErrorMessage(text, fallback); +}; + +const extractDownloadFilename = (res: Response) => { + const disposition = res.headers.get('content-disposition') || ''; + const utf8Match = disposition.match(/filename\*=UTF-8''([^;]+)/i); + if (utf8Match?.[1]) { + try { + return decodeURIComponent(utf8Match[1]); + } catch { + return utf8Match[1]; + } + } + const asciiMatch = disposition.match(/filename="([^"]+)"/i); + if (asciiMatch?.[1]) return asciiMatch[1]; + return ''; +}; + const applyExcelPreview = (buffer: ArrayBuffer) => { const workbook = XLSX.read(buffer, { type: 'array' }); if (!workbook.SheetNames.length) { @@ -182,8 +218,7 @@ const loadSheetPreview = async () => { headers: props.authHeaders || {}, }); if (!res.ok) { - const data = await res.json().catch(() => ({})); - throw new Error(data?.error || `HTTP ${res.status}`); + throw new Error(await readErrorMessage(res)); } excelPreview.value = await res.json(); @@ -202,8 +237,7 @@ const loadOfficeContent = async () => { headers: props.authHeaders || {}, }); if (!res.ok) { - const err = await res.json().catch(() => ({})); - throw new Error(err?.error || `HTTP ${res.status}`); + throw new Error(await readErrorMessage(res)); } const buffer = await res.arrayBuffer(); @@ -238,8 +272,7 @@ const loadPdfContent = async (): Promise<'iframe' | 'office' | 'sheet'> => { headers: props.authHeaders || {}, }); if (!res.ok) { - const err = await res.json().catch(() => ({})); - throw new Error(err?.error || `HTTP ${res.status}`); + throw new Error(await readErrorMessage(res)); } const blob = await res.blob(); @@ -290,8 +323,7 @@ const loadBinaryContent = async () => { headers: props.authHeaders || {}, }); if (!res.ok) { - const err = await res.json().catch(() => ({})); - throw new Error(err?.error || `HTTP ${res.status}`); + throw new Error(await readErrorMessage(res)); } const blob = await res.blob(); @@ -314,15 +346,14 @@ const downloadFile = async () => { headers: props.authHeaders || {}, }); if (!res.ok) { - const err = await res.json().catch(() => ({})); - throw new Error(err?.error || `HTTP ${res.status}`); + throw new Error(await readErrorMessage(res)); } const blob = await res.blob(); const downloadUrl = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = downloadUrl; - link.download = props.file.name || 'download'; + link.download = extractDownloadFilename(res) || props.file.name || 'download'; document.body.appendChild(link); link.click(); link.remove(); From fed1b103e6f0bac13db4b162eae907eeac5977cf Mon Sep 17 00:00:00 2001 From: "DESKTOP-JKIE562\\PC" <1013397054@qq.com> Date: Tue, 2 Jun 2026 21:55:21 +0800 Subject: [PATCH 6/8] test --- backend/app/api/integration.py | 26 ++++++++++++++++++++++---- 1 file changed, 22 insertions(+), 4 deletions(-) diff --git a/backend/app/api/integration.py b/backend/app/api/integration.py index 1a87683e..cc4e2755 100644 --- a/backend/app/api/integration.py +++ b/backend/app/api/integration.py @@ -125,6 +125,23 @@ def _integration_base_url() -> str: return explicit return request.host_url.rstrip('/') +def _kb_storage_root() -> Path: + root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve() + root.mkdir(parents=True, exist_ok=True) + return root + +def _resolve_storage_path(path_value: str | None) -> Path | None: + if not path_value: + return None + raw_path = Path(str(path_value)) + candidate = (raw_path if raw_path.is_absolute() else (_kb_storage_root() / raw_path)).resolve() + root = _kb_storage_root() + try: + candidate.relative_to(root) + except ValueError: + return None + return candidate + def _current_version(document: KbDocument) -> KbDocumentVersion | None: versions = list(getattr(document, 'versions', []) or []) if not versions: @@ -167,15 +184,16 @@ def _list_files_payload(*, knowledge_base_id: int | None=None, department_id: in def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]: if kind == 'source': - path = Path(version.source_file_path) + path = _resolve_storage_path(version.source_file_path) + if path is None: + raise NotFoundError('File not found on disk.') filename = version.source_file_name or f'document-{version.document_id}' return (path, filename) - preferred = version.cleaned_file_path or version.cleaned_preview_path + preferred = _resolve_storage_path(version.cleaned_file_path) or _resolve_storage_path(version.cleaned_preview_path) if not preferred: abort(409, description='Markdown not ready.') - path = Path(preferred) filename = f'document-{version.document_id}-v{version.version_no}.md' - return (path, filename) + return (preferred, filename) @integration_bp.before_request def _verify_integration_access(): From 61693d014de3c989a089807f50111abe22f1f506 Mon Sep 17 00:00:00 2001 From: sophie <16087569+sophie_liang@user.noreply.gitee.com> Date: Tue, 2 Jun 2026 15:36:22 +0800 Subject: [PATCH 7/8] =?UTF-8?q?refactor:=20=E9=87=8D=E6=9E=84=E5=89=8D?= =?UTF-8?q?=E7=AB=AF=E9=AA=A8=E6=9E=B6=EF=BC=8C=E5=8F=8Aadmin=E6=A8=A1?= =?UTF-8?q?=E5=9D=97=E5=AD=90=E8=B7=AF=E7=94=B1=E5=92=8C=E6=87=92=E5=8A=A0?= =?UTF-8?q?=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit refactor: 优化多次请求,并使用pinia状态管理 --- backend/app/api/admin.py | 81 +- backend/tests/test_admin.py | 16 + docs/frontend_architecture_refactor.md | 453 ++ frontend/package-lock.json | 136 + frontend/package.json | 1 + frontend/src/api/admin.ts | 10 + frontend/src/app/plugins/pinia.ts | 7 + frontend/src/app/router/guards.ts | 49 + frontend/src/app/router/index.ts | 16 + .../src/app/router/routes/admin.routes.ts | 110 + frontend/src/app/router/routes/auth.routes.ts | 14 + frontend/src/app/router/routes/chat.routes.ts | 10 + frontend/src/app/router/routes/index.ts | 16 + frontend/src/app/router/routes/kb.routes.ts | 11 + frontend/src/config.ts | 1 + .../features/admin/components/AdminNav.vue | 128 + .../admin/composables/useAdminNavBadges.ts | 12 + .../src/features/admin/constants/modules.ts | 52 + frontend/src/features/admin/index.ts | 10 + .../admin/modules/agents/AgentsPage.vue | 253 + .../components/AgentPermissionModal.vue | 94 + .../agents/components/AgentTestModal.vue | 82 + .../agents/composables/useAgentsAdmin.ts | 305 + .../announcements/AnnouncementsPage.vue | 107 + .../composables/useAnnouncementsAdmin.ts | 109 + .../admin/modules/approvals/ApprovalsPage.vue | 108 + .../composables/useApprovalsAdmin.ts | 98 + .../admin/modules/dashboard/DashboardPage.vue | 94 + .../composables/useDashboardAdmin.ts | 42 + .../modules/departments/DepartmentsPage.vue | 163 + .../composables/useDepartmentsAdmin.ts | 131 + .../knowledge-base/KnowledgeBasePage.vue | 13 + .../modules/permissions/PermissionsPage.vue | 195 + .../composables/usePermissionsAdmin.ts | 205 + .../admin/modules/questions/QuestionsPage.vue | 174 + .../composables/useQuestionsAdmin.ts | 149 + .../admin/modules/reports/ReportsPage.vue | 390 + .../reports/composables/useReportsAdmin.ts | 865 +++ .../admin/modules/requests/RequestsPage.vue | 100 + .../requests/composables/useRequestsAdmin.ts | 68 + .../admin/modules/schedules/SchedulesPage.vue | 1127 +++ .../composables/useSchedulesAdmin.ts | 972 +++ .../admin/modules/users/UsersPage.vue | 244 + .../users/components/BatchEditUserModal.vue | 62 + .../users/components/BatchPermissionModal.vue | 70 + .../users/components/UserFormModal.vue | 109 + .../users/composables/useUsersAdmin.ts | 360 + .../admin/modules/wecom/WecomPage.vue | 456 ++ .../wecom/composables/useWecomAdmin.ts | 456 ++ .../features/admin/stores/admin-nav.store.ts | 94 + .../src/features/admin/types/admin.types.ts | 62 + .../src/features/admin/types/agent.types.ts | 54 + .../admin/types/announcement.types.ts | 14 + .../features/admin/types/dashboard.types.ts | 31 + .../features/admin/types/department.types.ts | 19 + .../features/admin/types/permission.types.ts | 16 + .../features/admin/types/question.types.ts | 28 + .../src/features/admin/types/report.types.ts | 31 + .../src/features/admin/types/request.types.ts | 14 + .../src/features/admin/types/user.types.ts | 63 + .../src/features/admin/types/wecom.types.ts | 104 + .../src/features/admin/views/AdminLayout.vue | 52 + .../src/features/auth/composables/useAuth.ts | 23 + frontend/src/features/auth/index.ts | 2 + .../src/features/auth/stores/auth.store.ts | 85 + .../src/features/chat/stores/chat.store.ts | 20 + frontend/src/main.ts | 39 +- frontend/src/router/index.ts | 105 +- frontend/src/shared/api/client.ts | 12 + frontend/src/shared/constants/routes.ts | 10 + frontend/src/shared/types/auth.types.ts | 1 + frontend/src/views/AdminView.vue | 6284 ----------------- frontend/tsconfig.app.json | 4 + frontend/vite.config.ts | 10 +- 74 files changed, 9493 insertions(+), 6418 deletions(-) create mode 100644 docs/frontend_architecture_refactor.md create mode 100644 frontend/src/app/plugins/pinia.ts create mode 100644 frontend/src/app/router/guards.ts create mode 100644 frontend/src/app/router/index.ts create mode 100644 frontend/src/app/router/routes/admin.routes.ts create mode 100644 frontend/src/app/router/routes/auth.routes.ts create mode 100644 frontend/src/app/router/routes/chat.routes.ts create mode 100644 frontend/src/app/router/routes/index.ts create mode 100644 frontend/src/app/router/routes/kb.routes.ts create mode 100644 frontend/src/features/admin/components/AdminNav.vue create mode 100644 frontend/src/features/admin/composables/useAdminNavBadges.ts create mode 100644 frontend/src/features/admin/constants/modules.ts create mode 100644 frontend/src/features/admin/index.ts create mode 100644 frontend/src/features/admin/modules/agents/AgentsPage.vue create mode 100644 frontend/src/features/admin/modules/agents/components/AgentPermissionModal.vue create mode 100644 frontend/src/features/admin/modules/agents/components/AgentTestModal.vue create mode 100644 frontend/src/features/admin/modules/agents/composables/useAgentsAdmin.ts create mode 100644 frontend/src/features/admin/modules/announcements/AnnouncementsPage.vue create mode 100644 frontend/src/features/admin/modules/announcements/composables/useAnnouncementsAdmin.ts create mode 100644 frontend/src/features/admin/modules/approvals/ApprovalsPage.vue create mode 100644 frontend/src/features/admin/modules/approvals/composables/useApprovalsAdmin.ts create mode 100644 frontend/src/features/admin/modules/dashboard/DashboardPage.vue create mode 100644 frontend/src/features/admin/modules/dashboard/composables/useDashboardAdmin.ts create mode 100644 frontend/src/features/admin/modules/departments/DepartmentsPage.vue create mode 100644 frontend/src/features/admin/modules/departments/composables/useDepartmentsAdmin.ts create mode 100644 frontend/src/features/admin/modules/knowledge-base/KnowledgeBasePage.vue create mode 100644 frontend/src/features/admin/modules/permissions/PermissionsPage.vue create mode 100644 frontend/src/features/admin/modules/permissions/composables/usePermissionsAdmin.ts create mode 100644 frontend/src/features/admin/modules/questions/QuestionsPage.vue create mode 100644 frontend/src/features/admin/modules/questions/composables/useQuestionsAdmin.ts create mode 100644 frontend/src/features/admin/modules/reports/ReportsPage.vue create mode 100644 frontend/src/features/admin/modules/reports/composables/useReportsAdmin.ts create mode 100644 frontend/src/features/admin/modules/requests/RequestsPage.vue create mode 100644 frontend/src/features/admin/modules/requests/composables/useRequestsAdmin.ts create mode 100644 frontend/src/features/admin/modules/schedules/SchedulesPage.vue create mode 100644 frontend/src/features/admin/modules/schedules/composables/useSchedulesAdmin.ts create mode 100644 frontend/src/features/admin/modules/users/UsersPage.vue create mode 100644 frontend/src/features/admin/modules/users/components/BatchEditUserModal.vue create mode 100644 frontend/src/features/admin/modules/users/components/BatchPermissionModal.vue create mode 100644 frontend/src/features/admin/modules/users/components/UserFormModal.vue create mode 100644 frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts create mode 100644 frontend/src/features/admin/modules/wecom/WecomPage.vue create mode 100644 frontend/src/features/admin/modules/wecom/composables/useWecomAdmin.ts create mode 100644 frontend/src/features/admin/stores/admin-nav.store.ts create mode 100644 frontend/src/features/admin/types/admin.types.ts create mode 100644 frontend/src/features/admin/types/agent.types.ts create mode 100644 frontend/src/features/admin/types/announcement.types.ts create mode 100644 frontend/src/features/admin/types/dashboard.types.ts create mode 100644 frontend/src/features/admin/types/department.types.ts create mode 100644 frontend/src/features/admin/types/permission.types.ts create mode 100644 frontend/src/features/admin/types/question.types.ts create mode 100644 frontend/src/features/admin/types/report.types.ts create mode 100644 frontend/src/features/admin/types/request.types.ts create mode 100644 frontend/src/features/admin/types/user.types.ts create mode 100644 frontend/src/features/admin/types/wecom.types.ts create mode 100644 frontend/src/features/admin/views/AdminLayout.vue create mode 100644 frontend/src/features/auth/composables/useAuth.ts create mode 100644 frontend/src/features/auth/index.ts create mode 100644 frontend/src/features/auth/stores/auth.store.ts create mode 100644 frontend/src/features/chat/stores/chat.store.ts create mode 100644 frontend/src/shared/api/client.ts create mode 100644 frontend/src/shared/constants/routes.ts create mode 100644 frontend/src/shared/types/auth.types.ts delete mode 100644 frontend/src/views/AdminView.vue diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py index be75e3ab..4c1dce56 100644 --- a/backend/app/api/admin.py +++ b/backend/app/api/admin.py @@ -154,19 +154,84 @@ def debug_wecom_user_by_code(): payload['match_preview'] = _build_wecom_match_preview(identity, rules, operator) return jsonify(payload) +def _compute_dashboard_summary(): + """ + 聚合仪表盘四张卡片所需的统计值(仅 COUNT/AVG,不返回列表)。 + + 返回字段: + - agent_count: 启用中的 Agent 数量 + - user_count: 用户总数 + - total_conversations: 对话日志总数 + - avg_score: 反馈平均分(保留 1 位小数) + """ + total_users = db.session.query(func.count(User.id)).scalar() or 0 + active_agents = db.session.query(func.count(Agent.id)).filter_by(is_active=True).scalar() or 0 + total_conversations = db.session.query(func.count(ChatLog.id)).scalar() or 0 + avg_score = db.session.query(func.avg(Feedback.score)).scalar() + avg_score = round(float(avg_score), 1) if avg_score else 0.0 + return { + 'agent_count': active_agents, + 'user_count': total_users, + 'total_conversations': total_conversations, + 'avg_score': avg_score, + } + +def _compute_dashboard_badges(): + """ + 聚合侧栏角标所需的待办数量(仅 COUNT,不拉 users / permission_requests 全表)。 + + 返回字段: + - pending_approvals: status=pending 的注册用户数量(「用户审批」角标) + - pending_requests: status=pending 的权限申请数量(「权限申请」角标) + """ + pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar() or 0 + pending_requests = db.session.query(func.count(PermissionRequest.id)).filter_by(status='pending').scalar() or 0 + return { + 'pending_approvals': pending_approvals, + 'pending_requests': pending_requests, + } + +@admin_bp.route('/dashboard/summary', methods=['GET']) +@require_admin +def dashboard_summary(): + """ + 管理后台仪表盘概览(供 Dashboard 页单次请求)。 + + GET /api/admin/dashboard/summary + 响应示例:{"agent_count": 5, "user_count": 120, "total_conversations": 3000, "avg_score": 4.2} + """ + return jsonify(_compute_dashboard_summary()) + +@admin_bp.route('/dashboard/badges', methods=['GET']) +@require_admin +def dashboard_badges(): + """ + 管理后台侧栏待办角标(供 AdminLayout 轻量轮询/缓存刷新)。 + + GET /api/admin/dashboard/badges + 响应示例:{"pending_approvals": 2, "pending_requests": 5} + """ + return jsonify(_compute_dashboard_badges()) + @admin_bp.route('/dashboard', methods=['GET']) @require_admin def dashboard_stats(): """ - Dashboard statistics + 仪表盘统计(遗留接口,字段名与早期前端兼容;新代码请用 /dashboard/summary 与 /dashboard/badges)。 + + GET /api/admin/dashboard + 响应含 summary 四指标 + pending_approvals / pending_requests。 """ - total_users = db.session.query(func.count(User.id)).scalar() - active_agents = db.session.query(func.count(Agent.id)).filter_by(is_active=True).scalar() - total_conversations = db.session.query(func.count(ChatLog.id)).scalar() - avg_score = db.session.query(func.avg(Feedback.score)).scalar() - avg_score = float(avg_score) if avg_score else 0.0 - pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar() - return jsonify({'total_users': total_users, 'active_agents': active_agents, 'total_conversations': total_conversations, 'avg_score': round(avg_score, 1), 'pending_approvals': pending_approvals}) + summary = _compute_dashboard_summary() + badges = _compute_dashboard_badges() + return jsonify({ + 'total_users': summary['user_count'], + 'active_agents': summary['agent_count'], + 'total_conversations': summary['total_conversations'], + 'avg_score': summary['avg_score'], + 'pending_approvals': badges['pending_approvals'], + 'pending_requests': badges['pending_requests'], + }) @admin_bp.route('/departments', methods=['GET']) @require_admin diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py index 12f576a5..a6ea3a68 100644 --- a/backend/tests/test_admin.py +++ b/backend/tests/test_admin.py @@ -181,6 +181,22 @@ def test_reports(client, admin_headers): """ Test report endpoints """ + response = client.get('/api/admin/dashboard/summary', headers=admin_headers) + assert response.status_code == 200 + data = response.json + assert set(data.keys()) == {'agent_count', 'user_count', 'total_conversations', 'avg_score'} + assert isinstance(data['agent_count'], int) + assert isinstance(data['user_count'], int) + assert isinstance(data['total_conversations'], int) + assert isinstance(data['avg_score'], (int, float)) + + response = client.get('/api/admin/dashboard/badges', headers=admin_headers) + assert response.status_code == 200 + badges = response.json + assert set(badges.keys()) == {'pending_approvals', 'pending_requests'} + assert isinstance(badges['pending_approvals'], int) + assert isinstance(badges['pending_requests'], int) + response = client.get('/api/admin/reports/usage', headers=admin_headers) assert response.status_code == 200 data = response.json diff --git a/docs/frontend_architecture_refactor.md b/docs/frontend_architecture_refactor.md new file mode 100644 index 00000000..f31518f9 --- /dev/null +++ b/docs/frontend_architecture_refactor.md @@ -0,0 +1,453 @@ +# HXOPS 前端重构架构方案 + +> 更新时间:2026-06-02 +> 适用范围:`frontend/` 目录 +> 文档定位:定义推荐的目标架构(Feature-Module + Composables + Pinia),作为后续分阶段重构的基准。 + +--- + +## 1. 架构选型 + +在现有技术栈(Vue 3 + TypeScript + Vite + Vue Router + Vue I18n + TailwindCSS)基础上,采用 **Feature-Module 垂直切分 + Composables 逻辑封装 + Pinia 共享状态** 的组合架构。 + +**选型理由:** + +- 与 Vue 3 Composition API 天然契合,学习成本低 +- 业务域清晰(聊天 / 管理后台 / 知识库 / 认证),适合按 feature 垂直拆分 +- 相比 FSD(Feature-Sliced Design)目录层级更浅,迁移成本可控 +- 相比引入 Element Plus 等 UI 库,可继续沿用现有 Tailwind 设计体系(`tokens.css`、`components-ds.css`) + +**保持不变的技术栈:** + +| 层级 | 选型 | +|------|------| +| 框架 | Vue 3(Composition API + ` + + diff --git a/frontend/src/features/admin/composables/useAdminNavBadges.ts b/frontend/src/features/admin/composables/useAdminNavBadges.ts new file mode 100644 index 00000000..7e9beb7a --- /dev/null +++ b/frontend/src/features/admin/composables/useAdminNavBadges.ts @@ -0,0 +1,12 @@ +/** + * features/admin/composables/useAdminNavBadges.ts + * 暴露角标刷新入口;拉取与缓存放 admin-nav.store(不在此 composable 内 onMounted,避免子页面重复请求)。 + */ +import { useAdminNavStore } from '../stores/admin-nav.store'; + +export function useAdminNavBadges() { + const navStore = useAdminNavStore(); + return { + refreshBadges: () => navStore.refreshBadges(), + }; +} diff --git a/frontend/src/features/admin/constants/modules.ts b/frontend/src/features/admin/constants/modules.ts new file mode 100644 index 00000000..76cd646f --- /dev/null +++ b/frontend/src/features/admin/constants/modules.ts @@ -0,0 +1,52 @@ +/** + * features/admin/constants/modules.ts + * 管理后台模块元数据,AdminNav 与子路由共用。 + */ + +import type { AdminModuleId, AdminReportTableId } from '../types/admin.types'; + +export interface AdminModuleMeta { + id: AdminModuleId; + routeName: string; + path: string; + labelKey: string; + configKey: keyof typeof import('@/config').config.admin.modules; +} + +/** 已独立拆分的模块(全部 admin 模块均已拆分) */ +export const STANDALONE_ADMIN_MODULES = new Set([ + 'dashboard', 'agents', 'users', 'departments', 'approvals', 'announcements', 'questions', 'requests', 'permissions', 'schedules', 'knowledge_base', 'wecom', 'reports', +]); + +export const ADMIN_MODULE_METAS: AdminModuleMeta[] = [ + { id: 'dashboard', routeName: 'AdminDashboard', path: 'dashboard', labelKey: 'admin.nav.dashboard', configKey: 'dashboard' }, + { id: 'approvals', routeName: 'AdminApprovals', path: 'approvals', labelKey: 'admin.nav.approvals', configKey: 'approvals' }, + { id: 'users', routeName: 'AdminUsers', path: 'users', labelKey: 'admin.nav.users', configKey: 'users' }, + { id: 'departments', routeName: 'AdminDepartments', path: 'departments', labelKey: 'admin.nav.departments', configKey: 'departments' }, + { id: 'agents', routeName: 'AdminAgents', path: 'agents', labelKey: 'admin.nav.agents', configKey: 'agents' }, + { id: 'knowledge_base', routeName: 'AdminKnowledgeBase', path: 'knowledge-base', labelKey: 'admin.nav.knowledgeBase', configKey: 'knowledge_base' }, + { id: 'schedules', routeName: 'AdminSchedules', path: 'schedules', labelKey: 'admin.nav.schedules', configKey: 'schedules' }, + { id: 'announcements', routeName: 'AdminAnnouncements', path: 'announcements', labelKey: 'admin.nav.announcements', configKey: 'announcements' }, + { id: 'questions', routeName: 'AdminQuestions', path: 'questions', labelKey: 'admin.nav.questions', configKey: 'questions' }, + { id: 'wecom', routeName: 'AdminWecom', path: 'wecom', labelKey: 'admin.nav.wecom', configKey: 'wecom' }, + { id: 'permissions', routeName: 'AdminPermissions', path: 'permissions', labelKey: 'admin.nav.permissions', configKey: 'permissions' }, + { id: 'requests', routeName: 'AdminRequests', path: 'requests', labelKey: 'admin.nav.requests', configKey: 'requests' }, +]; + +export const ADMIN_REPORT_TABLES: AdminReportTableId[] = [ + 'users', + 'agents', + 'chat_logs', + 'permission_requests', + 'general_feedbacks', + 'feedbacks', +]; + +export const LEGACY_MODULE_QUERY_TO_PATH: Record = {}; + +export const adminModulePath = (moduleId: AdminModuleId | string): string => { + if (moduleId === 'reports') return '/admin/reports'; + const meta = ADMIN_MODULE_METAS.find((m) => m.id === moduleId); + if (meta) return `/admin/${meta.path}`; + return `/admin/${LEGACY_MODULE_QUERY_TO_PATH[moduleId] || moduleId}`; +}; diff --git a/frontend/src/features/admin/index.ts b/frontend/src/features/admin/index.ts new file mode 100644 index 00000000..5408d13e --- /dev/null +++ b/frontend/src/features/admin/index.ts @@ -0,0 +1,10 @@ +/** + * features/admin/index.ts + * + * 管理后台 feature 的公共导出入口,便于其他模块按需 import。 + */ + +export { default as AdminLayout } from './views/AdminLayout.vue'; +export { useAdminNavStore } from './stores/admin-nav.store'; +export { adminModulePath, ADMIN_MODULE_METAS } from './constants/modules'; +export type { AdminModuleId } from './types/admin.types'; diff --git a/frontend/src/features/admin/modules/agents/AgentsPage.vue b/frontend/src/features/admin/modules/agents/AgentsPage.vue new file mode 100644 index 00000000..e4c66bdd --- /dev/null +++ b/frontend/src/features/admin/modules/agents/AgentsPage.vue @@ -0,0 +1,253 @@ +/** + * features/admin/modules/agents/AgentsPage.vue + * + * Agent 管理独立页面(Phase 1 首个拆分模块)。 + * 路由:/admin/agents + */ + + + + diff --git a/frontend/src/features/admin/modules/agents/components/AgentPermissionModal.vue b/frontend/src/features/admin/modules/agents/components/AgentPermissionModal.vue new file mode 100644 index 00000000..2b5d3685 --- /dev/null +++ b/frontend/src/features/admin/modules/agents/components/AgentPermissionModal.vue @@ -0,0 +1,94 @@ +/** + * features/admin/modules/agents/components/AgentPermissionModal.vue + * + * 为指定 Agent 批量勾选可访问用户的权限弹窗。 + */ + + + + diff --git a/frontend/src/features/admin/modules/agents/components/AgentTestModal.vue b/frontend/src/features/admin/modules/agents/components/AgentTestModal.vue new file mode 100644 index 00000000..7ef7d6f4 --- /dev/null +++ b/frontend/src/features/admin/modules/agents/components/AgentTestModal.vue @@ -0,0 +1,82 @@ +/** + * features/admin/modules/agents/components/AgentTestModal.vue + * + * Agent 连通性测试弹窗:展示请求 URL、输出信息与分析结果。 + */ + + + + diff --git a/frontend/src/features/admin/modules/agents/composables/useAgentsAdmin.ts b/frontend/src/features/admin/modules/agents/composables/useAgentsAdmin.ts new file mode 100644 index 00000000..d96fa326 --- /dev/null +++ b/frontend/src/features/admin/modules/agents/composables/useAgentsAdmin.ts @@ -0,0 +1,305 @@ +/** + * features/admin/modules/agents/composables/useAgentsAdmin.ts + * + * Agent 管理模块的业务逻辑:列表 CRUD、连通性测试、权限分配。 + * 从原 AdminView.vue 的 agents 相关 script 抽取,供 AgentsPage 使用。 + */ + +import { ref } from 'vue'; +import { useI18n } from 'vue-i18n'; +import { + createAdminAgent, + deleteAdminAgent, + listAdminAgents, + listAdminUsers, + saveAdminAgentPermissions, + testAdminAgent, + updateAdminAgent, +} from '@/api/admin'; +import { useMessage } from '@/composables/useMessage'; +import type { AdminUserRow } from '@/features/admin/types/admin.types'; +import type { AgentFormState, AgentRow, AgentTestResult } from '@/features/admin/types/agent.types'; +import { createEmptyAgentForm } from '@/features/admin/types/agent.types'; + +export function useAgentsAdmin() { + const { t } = useI18n(); + const msg = useMessage(); + + const agents = ref([]); + const users = ref([]); + const isLoading = ref(true); + const isSaving = ref(false); + const isEditing = ref(false); + const selectedAgentId = ref(null); + const form = ref(createEmptyAgentForm()); + + const showTestModal = ref(false); + const isTesting = ref(false); + const testingAgent = ref(null); + const testResult = ref(null); + + const showPermissionModal = ref(false); + const permissionAgent = ref(null); + const permissionUserIds = ref([]); + + const showDeleteConfirmDialog = ref(false); + const deleteConfirmMessage = ref(''); + let deleteConfirmAction: (() => Promise | void) | null = null; + + const activeUsers = () => users.value.filter((u) => u.status !== 'pending'); + + const loadAgents = async (): Promise => { + try { + agents.value = await listAdminAgents(); + } catch (e) { + console.error('Error loading agents:', e); + agents.value = []; + } + }; + + const loadUsers = async (): Promise => { + try { + users.value = await listAdminUsers(); + } catch (e) { + console.error('Error loading users:', e); + users.value = []; + } + }; + + const loadAll = async (): Promise => { + isLoading.value = true; + await Promise.all([loadAgents(), loadUsers()]); + isLoading.value = false; + }; + + const resetForm = (): void => { + selectedAgentId.value = null; + form.value = createEmptyAgentForm(); + isEditing.value = false; + }; + + const selectAgent = (agent: AgentRow): void => { + selectedAgentId.value = agent.id; + form.value = { + id: agent.id, + name: agent.name, + dify_app_id: agent.dify_app_id, + dify_api_key: agent.dify_api_key || '', + description: agent.description || '', + type: agent.type, + dify_app_type: agent.extra_config?.dify_app_type === 'workflow' ? 'workflow' : 'chatflow', + api_base_url: agent.api_base_url || '', + iframe_url: String(agent.extra_config?.iframe_url || ''), + is_active: agent.is_active, + }; + isEditing.value = true; + }; + + const openDeleteConfirm = ( + message: string, + action: () => Promise | void, + ): void => { + deleteConfirmMessage.value = message; + deleteConfirmAction = action; + showDeleteConfirmDialog.value = true; + }; + + const closeDeleteConfirm = (): void => { + showDeleteConfirmDialog.value = false; + deleteConfirmAction = null; + }; + + const confirmDelete = async (): Promise => { + if (!deleteConfirmAction) return; + try { + await deleteConfirmAction(); + } finally { + closeDeleteConfirm(); + } + }; + + const submitAgent = async (): Promise => { + if (!form.value.name) { + msg.warning(t('admin.dept.msg.nameRequired')); + return; + } + + isSaving.value = true; + const extra_config: Record = {}; + if (form.value.type === 'iframe' && form.value.iframe_url) { + extra_config.iframe_url = form.value.iframe_url; + } + if (form.value.type === 'api') { + extra_config.dify_app_type = form.value.dify_app_type === 'workflow' ? 'workflow' : 'chatflow'; + } + + try { + const editingId = isEditing.value ? Number(form.value.id) : null; + if (isEditing.value && form.value.id != null) { + const payload: Record = { + name: form.value.name, + dify_app_id: form.value.dify_app_id, + description: form.value.description, + type: form.value.type, + api_base_url: form.value.api_base_url, + extra_config, + is_active: form.value.is_active, + }; + if (form.value.dify_api_key) { + payload.dify_api_key = form.value.dify_api_key; + } + await updateAdminAgent(form.value.id, payload); + } else { + await createAdminAgent({ + name: form.value.name, + dify_app_id: form.value.dify_app_id, + dify_api_key: form.value.dify_api_key, + description: form.value.description, + type: form.value.type, + api_base_url: form.value.api_base_url, + extra_config, + }); + } + + await loadAgents(); + if (editingId) { + const updated = agents.value.find((a) => a.id === editingId); + if (updated) selectAgent(updated); + } else { + resetForm(); + } + } catch (e) { + console.error(e); + msg.error((e as Error).message || t('admin.msg.requestFailed')); + } finally { + isSaving.value = false; + } + }; + + const deleteAgent = async (id: number): Promise => { + openDeleteConfirm(t('admin.agent.confirmDelete'), async () => { + try { + await deleteAdminAgent(id); + await loadAgents(); + if (selectedAgentId.value === id) { + resetForm(); + } + } catch (e) { + console.error(e); + msg.error((e as Error).message || t('admin.msg.requestFailed')); + } + }); + }; + + const openTestModal = (agent: AgentRow): void => { + testingAgent.value = agent; + testResult.value = null; + showTestModal.value = true; + void runAgentTest(agent); + }; + + const runAgentTest = async (agent?: AgentRow): Promise => { + const target = agent || testingAgent.value; + if (!target) return; + isTesting.value = true; + try { + const data = await testAdminAgent(target.id); + testResult.value = { + success: !!data.success, + request_url: data.request_url || '', + output_info: data.output_info || '', + analysis: data.analysis || (data.success ? t('admin.agent.testDone') : t('admin.agent.testFailed')), + http_status: data.http_status, + tested_at: data.tested_at, + }; + + if (data.success) { + const idx = agents.value.findIndex((a) => a.id === target.id); + const row = idx >= 0 ? agents.value[idx] : undefined; + if (row) { + row.is_active = true; + } + if (selectedAgentId.value === target.id) { + form.value.is_active = true; + } + } + } catch (e) { + testResult.value = { + success: false, + request_url: '', + output_info: (e as Error).message || t('admin.agent.networkError'), + analysis: t('admin.agent.testFailedRequestException'), + http_status: 0, + }; + } finally { + isTesting.value = false; + } + }; + + const openPermissionModal = (agent: AgentRow): void => { + permissionAgent.value = agent; + permissionUserIds.value = users.value + .filter((u) => u.agent_ids.includes(agent.id)) + .map((u) => u.id); + showPermissionModal.value = true; + }; + + const togglePermissionUser = (userId: number): void => { + const index = permissionUserIds.value.indexOf(userId); + if (index === -1) { + permissionUserIds.value.push(userId); + } else { + permissionUserIds.value.splice(index, 1); + } + }; + + const savePermissions = async (): Promise => { + if (!permissionAgent.value) return; + isSaving.value = true; + try { + await saveAdminAgentPermissions( + permissionAgent.value.id, + permissionUserIds.value, + ); + await loadUsers(); + showPermissionModal.value = false; + } catch (e) { + console.error(e); + msg.error((e as Error).message || t('admin.msg.failed')); + } finally { + isSaving.value = false; + } + }; + + return { + agents, + users, + activeUsers, + isLoading, + isSaving, + isEditing, + selectedAgentId, + form, + showTestModal, + isTesting, + testingAgent, + testResult, + showPermissionModal, + permissionAgent, + permissionUserIds, + showDeleteConfirmDialog, + deleteConfirmMessage, + loadAll, + resetForm, + selectAgent, + submitAgent, + deleteAgent, + openTestModal, + runAgentTest, + openPermissionModal, + togglePermissionUser, + savePermissions, + closeDeleteConfirm, + confirmDelete, + }; +} diff --git a/frontend/src/features/admin/modules/announcements/AnnouncementsPage.vue b/frontend/src/features/admin/modules/announcements/AnnouncementsPage.vue new file mode 100644 index 00000000..7b28cbbc --- /dev/null +++ b/frontend/src/features/admin/modules/announcements/AnnouncementsPage.vue @@ -0,0 +1,107 @@ +/** + * features/admin/modules/announcements/AnnouncementsPage.vue + * 公告管理独立页面。路由:/admin/announcements + */ + + +