Merge branch 'test' into prod
This commit is contained in:
commit
c61f74866c
40 files changed
+4962
-4588
No files matched your search
@@ -47,9 +47,10 @@ GUNICORN_WORKERS=10
|
|||||||
|
|
||||||
# MinIO(知识库文档清洗图片托管;dev 与测试机同机时用测试 MinIO)
|
# MinIO(知识库文档清洗图片托管;dev 与测试机同机时用测试 MinIO)
|
||||||
# 本地非 Docker 跑 worker 时可改为 127.0.0.1:9000 或 192.168.100.192:9000
|
# 本地非 Docker 跑 worker 时可改为 127.0.0.1:9000 或 192.168.100.192:9000
|
||||||
|
# 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD 保持一致
|
||||||
MINIO_ENDPOINT=host.docker.internal:9000
|
MINIO_ENDPOINT=host.docker.internal:9000
|
||||||
MINIO_BUCKET=image-hosting-service
|
MINIO_BUCKET=image-hosting-service
|
||||||
MINIO_ACCESS_KEY=admin
|
MINIO_ACCESS_KEY=minio_testing_admin
|
||||||
MINIO_SECRET_KEY=difyai123456
|
MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx
|
||||||
MINIO_SECURE=false
|
MINIO_SECURE=false
|
||||||
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
||||||
@@ -50,10 +50,11 @@ WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
|
|||||||
|
|
||||||
# MinIO(知识库文档清洗图片托管,容器 minio-app)
|
# MinIO(知识库文档清洗图片托管,容器 minio-app)
|
||||||
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
|
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
|
||||||
|
# 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD(及 DIFY_S3_ACCESS_KEY)保持一致
|
||||||
MINIO_ENDPOINT=host.docker.internal:9000
|
MINIO_ENDPOINT=host.docker.internal:9000
|
||||||
MINIO_BUCKET=image-hosting-service
|
MINIO_BUCKET=image-hosting-service
|
||||||
MINIO_ACCESS_KEY=admin
|
MINIO_ACCESS_KEY=minio_testing_admin
|
||||||
MINIO_SECRET_KEY=difyai123456
|
MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx
|
||||||
MINIO_SECURE=false
|
MINIO_SECURE=false
|
||||||
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
|
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
|
||||||
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
|
||||||
+118
-16
@@ -1,16 +1,18 @@
|
|||||||
|
"""
|
||||||
"""
|
|
||||||
backend/app/__init__.py
|
backend/app/__init__.py
|
||||||
应用工厂
|
应用工厂:创建 Flask 应用、注册蓝图并挂载全局异常与响应处理。
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
|
import uuid
|
||||||
|
|
||||||
from flask import Flask, jsonify, request
|
from flask import Flask, jsonify, request, g
|
||||||
from flask_sqlalchemy import SQLAlchemy
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
from flask_migrate import Migrate
|
from flask_migrate import Migrate
|
||||||
from flask_cors import CORS
|
from flask_cors import CORS
|
||||||
from werkzeug.exceptions import HTTPException
|
from werkzeug.exceptions import HTTPException
|
||||||
from app.config import config
|
from app.config import config
|
||||||
|
from app.errors import AppError
|
||||||
|
from app.response_utils import error_payload, utc_iso_now
|
||||||
|
|
||||||
db = SQLAlchemy()
|
db = SQLAlchemy()
|
||||||
migrate = Migrate()
|
migrate = Migrate()
|
||||||
@@ -42,7 +44,7 @@ def create_app(config_name='default'):
|
|||||||
|
|
||||||
db.init_app(app)
|
db.init_app(app)
|
||||||
migrate.init_app(app, db)
|
migrate.init_app(app, db)
|
||||||
CORS(app) # 允许跨域
|
CORS(app) # 允许跨域
|
||||||
|
|
||||||
# 注册 Blueprints
|
# 注册 Blueprints
|
||||||
from app.api.chat import chat_bp
|
from app.api.chat import chat_bp
|
||||||
@@ -61,11 +63,11 @@ def create_app(config_name='default'):
|
|||||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||||
# 普通用户可见的 Agent 列表接口
|
# 普通用户可见的 Agent 列表接口
|
||||||
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||||
# 当前用户相关接口(首页、常用问题等)
|
# 当前用户相关接口(首页、常见问题等)
|
||||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||||
# 知识库/数据清洗模块接口
|
# 知识库数据清洗模块接口
|
||||||
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
||||||
# 知识库外部集成接口(供聊天/外部系统按 Dify 映射反查源文件)
|
# 知识库外部集成接口(供外部系统按 Dify 映射反查源文件)
|
||||||
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||||
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
||||||
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
||||||
@@ -83,6 +85,41 @@ def create_app(config_name='default'):
|
|||||||
@app.before_request
|
@app.before_request
|
||||||
def _sync_persisted_settings():
|
def _sync_persisted_settings():
|
||||||
_apply_persisted_settings(app)
|
_apply_persisted_settings(app)
|
||||||
|
incoming_request_id = (request.headers.get('X-Request-Id') or '').strip()
|
||||||
|
g.request_id = incoming_request_id or f"req_{uuid.uuid4().hex[:16]}"
|
||||||
|
|
||||||
|
@app.after_request
|
||||||
|
def _wrap_success_response(resp):
|
||||||
|
if not bool(app.config.get('ENABLE_API_ENVELOPE', False)):
|
||||||
|
return resp
|
||||||
|
if not request.path.startswith('/api/'):
|
||||||
|
return resp
|
||||||
|
if resp.is_streamed:
|
||||||
|
return resp
|
||||||
|
if resp.status_code < 200 or resp.status_code >= 300:
|
||||||
|
return resp
|
||||||
|
if not (resp.mimetype or '').startswith('application/json'):
|
||||||
|
return resp
|
||||||
|
try:
|
||||||
|
payload = resp.get_json(silent=True)
|
||||||
|
except Exception:
|
||||||
|
payload = None
|
||||||
|
if isinstance(payload, dict) and 'success' in payload:
|
||||||
|
return resp
|
||||||
|
wrapped = {
|
||||||
|
'success': True,
|
||||||
|
'data': payload,
|
||||||
|
'request_id': getattr(g, 'request_id', None),
|
||||||
|
'timestamp': utc_iso_now(),
|
||||||
|
}
|
||||||
|
wrapped_resp = jsonify(wrapped)
|
||||||
|
wrapped_resp.status_code = resp.status_code
|
||||||
|
for key, value in resp.headers.items():
|
||||||
|
lower = key.lower()
|
||||||
|
if lower in ('content-length', 'content-type'):
|
||||||
|
continue
|
||||||
|
wrapped_resp.headers[key] = value
|
||||||
|
return wrapped_resp
|
||||||
|
|
||||||
def _should_return_json_error() -> bool:
|
def _should_return_json_error() -> bool:
|
||||||
if request.path.startswith('/api/'):
|
if request.path.startswith('/api/'):
|
||||||
@@ -90,24 +127,89 @@ def create_app(config_name='default'):
|
|||||||
accepted = request.headers.get('Accept', '')
|
accepted = request.headers.get('Accept', '')
|
||||||
return 'application/json' in accepted.lower()
|
return 'application/json' in accepted.lower()
|
||||||
|
|
||||||
|
def _log_api_error(
|
||||||
|
*,
|
||||||
|
code: str,
|
||||||
|
message: str,
|
||||||
|
status: int,
|
||||||
|
details: dict | None = None,
|
||||||
|
exc: Exception | None = None,
|
||||||
|
) -> None:
|
||||||
|
request_id = getattr(g, 'request_id', None)
|
||||||
|
log_kwargs = {
|
||||||
|
'method': request.method,
|
||||||
|
'path': request.path,
|
||||||
|
'status': status,
|
||||||
|
'code': code,
|
||||||
|
'message': message,
|
||||||
|
'request_id': request_id,
|
||||||
|
'details': details or {},
|
||||||
|
}
|
||||||
|
log_text = (
|
||||||
|
'API error %(method)s %(path)s status=%(status)s code=%(code)s '
|
||||||
|
'message=%(message)s request_id=%(request_id)s details=%(details)s'
|
||||||
|
)
|
||||||
|
if status >= 500:
|
||||||
|
app.logger.error(log_text, log_kwargs, exc_info=exc)
|
||||||
|
else:
|
||||||
|
app.logger.warning(log_text, log_kwargs)
|
||||||
|
|
||||||
@app.errorhandler(HTTPException)
|
@app.errorhandler(HTTPException)
|
||||||
def _handle_http_exception(exc: HTTPException):
|
def _handle_http_exception(exc: HTTPException):
|
||||||
if not _should_return_json_error():
|
if not _should_return_json_error():
|
||||||
return exc
|
return exc
|
||||||
message = exc.description or exc.name or 'HTTP error'
|
message = exc.description or exc.name or 'HTTP error'
|
||||||
return jsonify({'error': str(message)}), int(exc.code or 500)
|
code_num = int(exc.code or 500)
|
||||||
|
code_map = {
|
||||||
|
400: 'VALIDATION.INVALID_PARAM',
|
||||||
|
401: 'AUTH.UNAUTHORIZED',
|
||||||
|
403: 'AUTH.FORBIDDEN',
|
||||||
|
404: 'RESOURCE.NOT_FOUND',
|
||||||
|
409: 'RESOURCE.CONFLICT',
|
||||||
|
429: 'SYSTEM.RATE_LIMITED',
|
||||||
|
}
|
||||||
|
code = code_map.get(code_num, 'SYSTEM.HTTP_ERROR')
|
||||||
|
_log_api_error(code=code, message=str(message), status=code_num, exc=exc)
|
||||||
|
payload = error_payload(
|
||||||
|
code=code,
|
||||||
|
message=str(message),
|
||||||
|
request_id=getattr(g, 'request_id', None),
|
||||||
|
)
|
||||||
|
return jsonify(payload), code_num
|
||||||
|
|
||||||
|
@app.errorhandler(AppError)
|
||||||
|
def _handle_app_error(exc: AppError):
|
||||||
|
_log_api_error(
|
||||||
|
code=exc.code,
|
||||||
|
message=exc.message,
|
||||||
|
status=exc.http_status,
|
||||||
|
details=exc.details,
|
||||||
|
exc=exc,
|
||||||
|
)
|
||||||
|
payload = error_payload(
|
||||||
|
code=exc.code,
|
||||||
|
message=exc.message,
|
||||||
|
request_id=getattr(g, 'request_id', None),
|
||||||
|
details=exc.details,
|
||||||
|
retryable=exc.retryable,
|
||||||
|
)
|
||||||
|
return jsonify(payload), exc.http_status
|
||||||
|
|
||||||
@app.errorhandler(Exception)
|
@app.errorhandler(Exception)
|
||||||
def _handle_unexpected_exception(exc: Exception):
|
def _handle_unexpected_exception(exc: Exception):
|
||||||
app.logger.exception(
|
_log_api_error(
|
||||||
'Unhandled exception on %s %s',
|
code='SYSTEM.INTERNAL_ERROR',
|
||||||
request.method,
|
message='Internal server error',
|
||||||
request.path,
|
status=500,
|
||||||
exc_info=exc,
|
exc=exc,
|
||||||
)
|
)
|
||||||
if not _should_return_json_error():
|
if not _should_return_json_error():
|
||||||
return '<h1><p>Internal Server Error</p></h1>', 500
|
return '<h1><p>Internal Server Error</p></h1>', 500
|
||||||
message = str(exc).strip() or 'Internal server error'
|
payload = error_payload(
|
||||||
return jsonify({'error': message}), 500
|
code='SYSTEM.INTERNAL_ERROR',
|
||||||
|
message='Internal server error',
|
||||||
|
request_id=getattr(g, 'request_id', None),
|
||||||
|
)
|
||||||
|
return jsonify(payload), 500
|
||||||
|
|
||||||
return app
|
return app
|
||||||
+189
-653
File diff suppressed because it is too large.
Load diff
+952
-351
File diff suppressed because it is too large.
Load diff
+47
-195
@@ -3,27 +3,38 @@ backend/app/api/integration.py
|
|||||||
文件用途:知识库外部集成查询接口
|
文件用途:知识库外部集成查询接口
|
||||||
"""
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from flask import Blueprint, abort, current_app, jsonify, request, send_file
|
from flask import Blueprint, abort, current_app, jsonify, request, send_file
|
||||||
from sqlalchemy import func
|
from sqlalchemy import func
|
||||||
from sqlalchemy.orm import joinedload
|
from sqlalchemy.orm import joinedload
|
||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
|
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__)
|
integration_bp = Blueprint('integration', __name__)
|
||||||
|
|
||||||
|
|
||||||
def _require_integration_key():
|
def _require_integration_key():
|
||||||
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||||||
incoming = str(request.headers.get('X-Integration-Key') or '').strip()
|
incoming = str(request.headers.get('X-Integration-Key') or '').strip()
|
||||||
|
|
||||||
if not configured:
|
if not configured:
|
||||||
return jsonify({'error': 'INTEGRATION_API_KEY is not configured'}), 503
|
|
||||||
if configured != incoming:
|
raise ServiceUnavailableError('INTEGRATION_API_KEY is not configured')
|
||||||
return jsonify({'error': 'Unauthorized'}), 401
|
|
||||||
return None
|
if configured == incoming:
|
||||||
|
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
|
||||||
|
|
||||||
|
raise UnauthorizedError('Unauthorized')
|
||||||
|
|
||||||
|
|
||||||
def _integration_base_url() -> str:
|
def _integration_base_url() -> str:
|
||||||
@@ -32,107 +43,35 @@ def _integration_base_url() -> str:
|
|||||||
return explicit
|
return explicit
|
||||||
return request.host_url.rstrip('/')
|
return request.host_url.rstrip('/')
|
||||||
|
|
||||||
|
|
||||||
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
|
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
|
||||||
versions = list(getattr(document, 'versions', []) or [])
|
versions = list(getattr(document, 'versions', []) or [])
|
||||||
if not versions:
|
if not versions:
|
||||||
return None
|
return None
|
||||||
return next((item for item in versions if item.is_current), versions[0])
|
return next((item for item in versions if item.is_current), versions[0])
|
||||||
|
|
||||||
|
|
||||||
def _document_query():
|
def _document_query():
|
||||||
return (
|
return db.session.query(KbDocument).options(joinedload(KbDocument.group), joinedload(KbDocument.versions).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False))
|
||||||
db.session.query(KbDocument)
|
|
||||||
.options(
|
|
||||||
joinedload(KbDocument.group),
|
|
||||||
joinedload(KbDocument.versions).joinedload(KbDocumentVersion.sync_records),
|
|
||||||
)
|
|
||||||
.filter(KbDocument.is_deleted.is_(False))
|
|
||||||
)
|
|
||||||
|
|
||||||
|
def _serialize_integration_document(document: KbDocument, *, version: KbDocumentVersion | None=None, sync_record: KbDifySyncRecord | None=None):
|
||||||
def _serialize_integration_document(
|
|
||||||
document: KbDocument,
|
|
||||||
*,
|
|
||||||
version: KbDocumentVersion | None = None,
|
|
||||||
sync_record: KbDifySyncRecord | None = None,
|
|
||||||
):
|
|
||||||
version = version or _current_version(document)
|
version = version or _current_version(document)
|
||||||
if not version:
|
if not version:
|
||||||
abort(404, description='No current version found.')
|
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))
|
||||||
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()
|
base_url = _integration_base_url()
|
||||||
source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source'
|
source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source'
|
||||||
markdown_download_url = (
|
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
|
||||||
f'{base_url}/api/integration/files/{document.id}/download?kind=md'
|
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}}
|
||||||
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:
|
def _serialize_knowledge_base(group: KbGroup, *, document_count: int) -> dict:
|
||||||
return {
|
return {'id': group.id, 'knowledge_base_id': group.id, 'name': group.name, 'description': group.description, 'department_id': group.department_id, 'dify_dataset_id': group.dify_dataset_id, 'document_count': int(document_count or 0), 'created_at': group.created_at.isoformat() if group.created_at else None, 'updated_at': group.updated_at.isoformat() if group.updated_at else None}
|
||||||
'id': group.id,
|
|
||||||
'knowledge_base_id': group.id,
|
|
||||||
'name': group.name,
|
|
||||||
'description': group.description,
|
|
||||||
'department_id': group.department_id,
|
|
||||||
'dify_dataset_id': group.dify_dataset_id,
|
|
||||||
'document_count': int(document_count or 0),
|
|
||||||
'created_at': group.created_at.isoformat() if group.created_at else None,
|
|
||||||
'updated_at': group.updated_at.isoformat() if group.updated_at else None,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
def _list_files_payload(*, knowledge_base_id: int | None=None, department_id: int | None=None, file_name: str | None=None) -> list[dict]:
|
||||||
def _list_files_payload(
|
|
||||||
*,
|
|
||||||
knowledge_base_id: int | None = None,
|
|
||||||
department_id: int | None = None,
|
|
||||||
file_name: str | None = None,
|
|
||||||
) -> list[dict]:
|
|
||||||
normalized_file_name = str(file_name or '').strip().lower()
|
normalized_file_name = str(file_name or '').strip().lower()
|
||||||
query = _document_query().order_by(KbDocument.updated_at.desc(), KbDocument.id.desc())
|
query = _document_query().order_by(KbDocument.updated_at.desc(), KbDocument.id.desc())
|
||||||
if knowledge_base_id is not None:
|
if knowledge_base_id is not None:
|
||||||
query = query.filter(KbDocument.group_id == knowledge_base_id)
|
query = query.filter(KbDocument.group_id == knowledge_base_id)
|
||||||
if department_id is not None:
|
if department_id is not None:
|
||||||
query = query.join(KbGroup, KbGroup.id == KbDocument.group_id).filter(KbGroup.department_id == department_id)
|
query = query.join(KbGroup, KbGroup.id == KbDocument.group_id).filter(KbGroup.department_id == department_id)
|
||||||
|
|
||||||
documents = query.all()
|
documents = query.all()
|
||||||
payload = []
|
payload = []
|
||||||
for document in documents:
|
for document in documents:
|
||||||
@@ -140,25 +79,22 @@ def _list_files_payload(
|
|||||||
if not version:
|
if not version:
|
||||||
continue
|
continue
|
||||||
normalized_name = version.source_file_name.lower() if version.source_file_name else ''
|
normalized_name = version.source_file_name.lower() if version.source_file_name else ''
|
||||||
if normalized_file_name and normalized_file_name not in normalized_name and normalized_file_name not in document.title.lower():
|
if normalized_file_name and normalized_file_name not in normalized_name and (normalized_file_name not in document.title.lower()):
|
||||||
continue
|
continue
|
||||||
payload.append(_serialize_integration_document(document, version=version))
|
payload.append(_serialize_integration_document(document, version=version))
|
||||||
return payload
|
return payload
|
||||||
|
|
||||||
|
|
||||||
def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]:
|
def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]:
|
||||||
if kind == 'source':
|
if kind == 'source':
|
||||||
path = Path(version.source_file_path)
|
path = Path(version.source_file_path)
|
||||||
filename = version.source_file_name or f'document-{version.document_id}'
|
filename = version.source_file_name or f'document-{version.document_id}'
|
||||||
return path, filename
|
return (path, filename)
|
||||||
|
|
||||||
preferred = version.cleaned_file_path or version.cleaned_preview_path
|
preferred = version.cleaned_file_path or version.cleaned_preview_path
|
||||||
if not preferred:
|
if not preferred:
|
||||||
abort(409, description='Markdown not ready.')
|
abort(409, description='Markdown not ready.')
|
||||||
path = Path(preferred)
|
path = Path(preferred)
|
||||||
filename = f'document-{version.document_id}-v{version.version_no}.md'
|
filename = f'document-{version.document_id}-v{version.version_no}.md'
|
||||||
return path, filename
|
return (path, filename)
|
||||||
|
|
||||||
|
|
||||||
@integration_bp.before_request
|
@integration_bp.before_request
|
||||||
def _verify_integration_access():
|
def _verify_integration_access():
|
||||||
@@ -167,138 +103,66 @@ def _verify_integration_access():
|
|||||||
return result
|
return result
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
@integration_bp.route('/files/<int:file_id>', methods=['GET'])
|
@integration_bp.route('/files/<int:file_id>', methods=['GET'])
|
||||||
def get_file_detail(file_id: int):
|
def get_file_detail(file_id: int):
|
||||||
document = _document_query().filter(KbDocument.id == file_id).first()
|
document = _document_query().filter(KbDocument.id == file_id).first()
|
||||||
if not document:
|
if not document:
|
||||||
return jsonify({'error': 'Document not found.'}), 404
|
raise NotFoundError('Document not found.')
|
||||||
return jsonify(_serialize_integration_document(document))
|
return jsonify(_serialize_integration_document(document))
|
||||||
|
|
||||||
|
|
||||||
@integration_bp.route('/knowledge-bases', methods=['GET'])
|
@integration_bp.route('/knowledge-bases', methods=['GET'])
|
||||||
def list_knowledge_bases():
|
def list_knowledge_bases():
|
||||||
department_id = request.args.get('department_id', type=int)
|
department_id = request.args.get('department_id', type=int)
|
||||||
q = str(request.args.get('q') or '').strip()
|
q = str(request.args.get('q') or '').strip()
|
||||||
|
document_counts = db.session.query(KbDocument.group_id.label('group_id'), func.count(KbDocument.id).label('document_count')).filter(KbDocument.is_deleted.is_(False)).group_by(KbDocument.group_id).subquery()
|
||||||
document_counts = (
|
query = db.session.query(KbGroup, func.coalesce(document_counts.c.document_count, 0).label('document_count')).outerjoin(document_counts, document_counts.c.group_id == KbGroup.id).filter(KbGroup.is_active.is_(True)).order_by(KbGroup.name.asc())
|
||||||
db.session.query(KbDocument.group_id.label('group_id'), func.count(KbDocument.id).label('document_count'))
|
|
||||||
.filter(KbDocument.is_deleted.is_(False))
|
|
||||||
.group_by(KbDocument.group_id)
|
|
||||||
.subquery()
|
|
||||||
)
|
|
||||||
|
|
||||||
query = (
|
|
||||||
db.session.query(KbGroup, func.coalesce(document_counts.c.document_count, 0).label('document_count'))
|
|
||||||
.outerjoin(document_counts, document_counts.c.group_id == KbGroup.id)
|
|
||||||
.filter(KbGroup.is_active.is_(True))
|
|
||||||
.order_by(KbGroup.name.asc())
|
|
||||||
)
|
|
||||||
if department_id is not None:
|
if department_id is not None:
|
||||||
query = query.filter(KbGroup.department_id == department_id)
|
query = query.filter(KbGroup.department_id == department_id)
|
||||||
if q:
|
if q:
|
||||||
query = query.filter(KbGroup.name.ilike(f'%{q}%'))
|
query = query.filter(KbGroup.name.ilike(f'%{q}%'))
|
||||||
|
|
||||||
rows = query.all()
|
rows = query.all()
|
||||||
return jsonify({'data': [_serialize_knowledge_base(group, document_count=document_count) for group, document_count in rows]})
|
return jsonify({'data': [_serialize_knowledge_base(group, document_count=document_count) for group, document_count in rows]})
|
||||||
|
|
||||||
|
|
||||||
@integration_bp.route('/files', methods=['GET'])
|
@integration_bp.route('/files', methods=['GET'])
|
||||||
def list_files():
|
def list_files():
|
||||||
knowledge_base_id = request.args.get('knowledge_base_id', type=int)
|
knowledge_base_id = request.args.get('knowledge_base_id', type=int)
|
||||||
department_id = request.args.get('department_id', type=int)
|
department_id = request.args.get('department_id', type=int)
|
||||||
file_name = request.args.get('file_name')
|
file_name = request.args.get('file_name')
|
||||||
return jsonify({'data': _list_files_payload(
|
return jsonify({'data': _list_files_payload(knowledge_base_id=knowledge_base_id, department_id=department_id, file_name=file_name)})
|
||||||
knowledge_base_id=knowledge_base_id,
|
|
||||||
department_id=department_id,
|
|
||||||
file_name=file_name,
|
|
||||||
)})
|
|
||||||
|
|
||||||
|
|
||||||
@integration_bp.route('/knowledge-bases/<int:knowledge_base_id>/files', methods=['GET'])
|
@integration_bp.route('/knowledge-bases/<int:knowledge_base_id>/files', methods=['GET'])
|
||||||
def list_files_for_knowledge_base(knowledge_base_id: int):
|
def list_files_for_knowledge_base(knowledge_base_id: int):
|
||||||
return jsonify({'data': _list_files_payload(
|
return jsonify({'data': _list_files_payload(knowledge_base_id=knowledge_base_id, file_name=request.args.get('file_name'))})
|
||||||
knowledge_base_id=knowledge_base_id,
|
|
||||||
file_name=request.args.get('file_name'),
|
|
||||||
)})
|
|
||||||
|
|
||||||
|
|
||||||
@integration_bp.route('/dify-file', methods=['GET'])
|
@integration_bp.route('/dify-file', methods=['GET'])
|
||||||
def get_file_detail_by_dify():
|
def get_file_detail_by_dify():
|
||||||
remote_document_id = str(request.args.get('remote_document_id') or '').strip()
|
remote_document_id = str(request.args.get('remote_document_id') or '').strip()
|
||||||
dataset_id = str(request.args.get('dataset_id') or '').strip() or None
|
dataset_id = str(request.args.get('dataset_id') or '').strip() or None
|
||||||
if not remote_document_id:
|
if not remote_document_id:
|
||||||
return jsonify({'error': 'remote_document_id is required'}), 400
|
raise ValidationError('remote_document_id is required')
|
||||||
|
record_query = 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).joinedload(KbDocument.group), joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False), KbDifySyncRecord.remote_document_id == remote_document_id).order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||||
record_query = (
|
|
||||||
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)
|
|
||||||
.joinedload(KbDocument.group),
|
|
||||||
joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records),
|
|
||||||
)
|
|
||||||
.filter(
|
|
||||||
KbDocument.is_deleted.is_(False),
|
|
||||||
KbDifySyncRecord.remote_document_id == remote_document_id,
|
|
||||||
)
|
|
||||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
|
||||||
)
|
|
||||||
if dataset_id:
|
if dataset_id:
|
||||||
record_query = record_query.filter(KbDifySyncRecord.dataset_id == dataset_id)
|
record_query = record_query.filter(KbDifySyncRecord.dataset_id == dataset_id)
|
||||||
|
|
||||||
record = record_query.first()
|
record = record_query.first()
|
||||||
version = record.document_version if record else None
|
version = record.document_version if record else None
|
||||||
document = version.document if version else None
|
document = version.document if version else None
|
||||||
if not document:
|
if not document:
|
||||||
return jsonify({'error': 'No local file mapping found for the given Dify document.'}), 404
|
raise NotFoundError('No local file mapping found for the given Dify document.')
|
||||||
|
|
||||||
return jsonify(_serialize_integration_document(document, version=version, sync_record=record))
|
return jsonify(_serialize_integration_document(document, version=version, sync_record=record))
|
||||||
|
|
||||||
|
|
||||||
@integration_bp.route('/dify-files/resolve', methods=['POST'])
|
@integration_bp.route('/dify-files/resolve', methods=['POST'])
|
||||||
def resolve_files_by_dify():
|
def resolve_files_by_dify():
|
||||||
data = request.get_json(silent=True) or {}
|
data = request.get_json(silent=True) or {}
|
||||||
items = data.get('items') if isinstance(data.get('items'), list) else []
|
items = data.get('items') if isinstance(data.get('items'), list) else []
|
||||||
if not items:
|
if not items:
|
||||||
return jsonify({'data': []})
|
return jsonify({'data': []})
|
||||||
|
remote_ids = sorted({str(item.get('remote_document_id') or '').strip() for item in items if isinstance(item, dict) and str(item.get('remote_document_id') or '').strip()})
|
||||||
remote_ids = sorted({
|
dataset_ids = sorted({str(item.get('dataset_id') or '').strip() for item in items if isinstance(item, dict) and str(item.get('dataset_id') or '').strip()})
|
||||||
str(item.get('remote_document_id') or '').strip()
|
|
||||||
for item in items
|
|
||||||
if isinstance(item, dict) and str(item.get('remote_document_id') or '').strip()
|
|
||||||
})
|
|
||||||
dataset_ids = sorted({
|
|
||||||
str(item.get('dataset_id') or '').strip()
|
|
||||||
for item in items
|
|
||||||
if isinstance(item, dict) and str(item.get('dataset_id') or '').strip()
|
|
||||||
})
|
|
||||||
if not remote_ids:
|
if not remote_ids:
|
||||||
return jsonify({'data': []})
|
return jsonify({'data': []})
|
||||||
|
query = 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).joinedload(KbDocument.group), joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records)).filter(KbDocument.is_deleted.is_(False), KbDifySyncRecord.remote_document_id.in_(remote_ids)).order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||||
query = (
|
|
||||||
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)
|
|
||||||
.joinedload(KbDocument.group),
|
|
||||||
joinedload(KbDifySyncRecord.document_version).joinedload(KbDocumentVersion.sync_records),
|
|
||||||
)
|
|
||||||
.filter(
|
|
||||||
KbDocument.is_deleted.is_(False),
|
|
||||||
KbDifySyncRecord.remote_document_id.in_(remote_ids),
|
|
||||||
)
|
|
||||||
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
|
||||||
)
|
|
||||||
if dataset_ids:
|
if dataset_ids:
|
||||||
query = query.filter(
|
query = query.filter(KbDifySyncRecord.dataset_id.in_(dataset_ids) | KbDifySyncRecord.dataset_id.is_(None))
|
||||||
(KbDifySyncRecord.dataset_id.in_(dataset_ids)) | (KbDifySyncRecord.dataset_id.is_(None))
|
|
||||||
)
|
|
||||||
|
|
||||||
records = query.all()
|
records = query.all()
|
||||||
records_by_key: dict[tuple[str | None, str], KbDifySyncRecord] = {}
|
records_by_key: dict[tuple[str | None, str], KbDifySyncRecord] = {}
|
||||||
records_by_remote: dict[str, KbDifySyncRecord] = {}
|
records_by_remote: dict[str, KbDifySyncRecord] = {}
|
||||||
@@ -306,7 +170,6 @@ def resolve_files_by_dify():
|
|||||||
key = (record.dataset_id, record.remote_document_id)
|
key = (record.dataset_id, record.remote_document_id)
|
||||||
records_by_key.setdefault(key, record)
|
records_by_key.setdefault(key, record)
|
||||||
records_by_remote.setdefault(record.remote_document_id, record)
|
records_by_remote.setdefault(record.remote_document_id, record)
|
||||||
|
|
||||||
payload = []
|
payload = []
|
||||||
for item in items:
|
for item in items:
|
||||||
if not isinstance(item, dict):
|
if not isinstance(item, dict):
|
||||||
@@ -320,30 +183,19 @@ def resolve_files_by_dify():
|
|||||||
record = records_by_remote.get(requested_remote_document_id)
|
record = records_by_remote.get(requested_remote_document_id)
|
||||||
version = record.document_version if record else None
|
version = record.document_version if record else None
|
||||||
document = version.document if version else None
|
document = version.document if version else None
|
||||||
payload.append({
|
payload.append({'request': {'dataset_id': requested_dataset_id, 'remote_document_id': requested_remote_document_id}, 'found': bool(document), 'document': _serialize_integration_document(document, version=version, sync_record=record) if document else None})
|
||||||
'request': {
|
|
||||||
'dataset_id': requested_dataset_id,
|
|
||||||
'remote_document_id': requested_remote_document_id,
|
|
||||||
},
|
|
||||||
'found': bool(document),
|
|
||||||
'document': _serialize_integration_document(document, version=version, sync_record=record) if document else None,
|
|
||||||
})
|
|
||||||
return jsonify({'data': payload})
|
return jsonify({'data': payload})
|
||||||
|
|
||||||
|
|
||||||
@integration_bp.route('/files/<int:file_id>/download', methods=['GET'])
|
@integration_bp.route('/files/<int:file_id>/download', methods=['GET'])
|
||||||
def download_file(file_id: int):
|
def download_file(file_id: int):
|
||||||
kind = str(request.args.get('kind') or 'md').strip().lower()
|
kind = str(request.args.get('kind') or 'md').strip().lower()
|
||||||
document = _document_query().filter(KbDocument.id == file_id).first()
|
document = _document_query().filter(KbDocument.id == file_id).first()
|
||||||
if not document:
|
if not document:
|
||||||
return jsonify({'error': 'Document not found.'}), 404
|
raise NotFoundError('Document not found.')
|
||||||
|
|
||||||
version = _current_version(document)
|
version = _current_version(document)
|
||||||
if not version:
|
if not version:
|
||||||
return jsonify({'error': 'No version found.'}), 404
|
raise NotFoundError('No version found.')
|
||||||
|
|
||||||
path, filename = _resolve_download_path(version, kind)
|
path, filename = _resolve_download_path(version, kind)
|
||||||
if not path.exists():
|
if not path.exists():
|
||||||
return jsonify({'error': 'File not found on disk.'}), 404
|
raise NotFoundError('File not found on disk.')
|
||||||
|
return send_file(path, as_attachment=True, download_name=filename)
|
||||||
return send_file(path, as_attachment=True, download_name=filename)
|
|
||||||
@@ -1,71 +1,49 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import traceback
|
import traceback
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from flask import Blueprint, jsonify, request
|
from flask import Blueprint, jsonify, request
|
||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
from app.models import ScheduleRun, ScheduleTask
|
from app.models import ScheduleRun, ScheduleTask
|
||||||
from app.services.schedule import _run_generic_check_job
|
from app.services.schedule import _run_generic_check_job
|
||||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||||
|
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||||
internal_jobs_bp = Blueprint('internal_jobs', __name__)
|
internal_jobs_bp = Blueprint('internal_jobs', __name__)
|
||||||
|
|
||||||
|
|
||||||
@internal_jobs_bp.route('/<name>', methods=['POST'])
|
@internal_jobs_bp.route('/<name>', methods=['POST'])
|
||||||
def run_internal_job(name: str):
|
def run_internal_job(name: str):
|
||||||
key = name.strip().lower()
|
key = name.strip().lower()
|
||||||
|
|
||||||
data = request.get_json(silent=True) or {}
|
data = request.get_json(silent=True) or {}
|
||||||
run_no = str(data.get("run_no") or "").strip()
|
run_no = str(data.get('run_no') or '').strip()
|
||||||
schedule_task_id = data.get("schedule_task_id")
|
schedule_task_id = data.get('schedule_task_id')
|
||||||
|
|
||||||
task = None
|
task = None
|
||||||
if schedule_task_id:
|
if schedule_task_id:
|
||||||
task = db.session.get(ScheduleTask, int(schedule_task_id))
|
task = db.session.get(ScheduleTask, int(schedule_task_id))
|
||||||
if not task and key.isdigit():
|
if not task and key.isdigit():
|
||||||
task = db.session.get(ScheduleTask, int(key))
|
task = db.session.get(ScheduleTask, int(key))
|
||||||
if not task:
|
if not task:
|
||||||
task = ScheduleTask.query.filter(
|
task = ScheduleTask.query.filter(ScheduleTask.platform_api_path.ilike(f'%{key}%')).first()
|
||||||
ScheduleTask.platform_api_path.ilike(f"%{key}%")
|
|
||||||
).first()
|
|
||||||
if not task:
|
if not task:
|
||||||
return jsonify({"error": f"No schedule task found for '{name}'"}), 404
|
raise NotFoundError(f"No schedule task found for '{name}'")
|
||||||
|
|
||||||
run = None
|
run = None
|
||||||
if run_no:
|
if run_no:
|
||||||
run = ScheduleRun.query.filter_by(run_no=run_no).first()
|
run = ScheduleRun.query.filter_by(run_no=run_no).first()
|
||||||
if not run:
|
if not run:
|
||||||
from app.services.schedule.scheduler_service import _generate_run_no
|
from app.services.schedule.scheduler_service import _generate_run_no
|
||||||
run = ScheduleRun(
|
run = ScheduleRun(run_no=run_no or _generate_run_no(), schedule_task_id=task.id, trigger_type='api', started_at=datetime.utcnow(), status='running')
|
||||||
run_no=run_no or _generate_run_no(),
|
|
||||||
schedule_task_id=task.id,
|
|
||||||
trigger_type='api',
|
|
||||||
started_at=datetime.utcnow(),
|
|
||||||
status='running',
|
|
||||||
)
|
|
||||||
db.session.add(run)
|
db.session.add(run)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
if not run.dify_execution_snapshot:
|
if not run.dify_execution_snapshot:
|
||||||
capture_dify_execution_snapshot(run, task)
|
capture_dify_execution_snapshot(run, task)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_generic_check_job(task, run)
|
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_generic_check_job(task, run)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
run.status = "failed"
|
run.status = 'failed'
|
||||||
run.error_message = str(exc)
|
run.error_message = str(exc)
|
||||||
run.finished_at = datetime.utcnow()
|
run.finished_at = datetime.utcnow()
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return jsonify({
|
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(exc), http_status=500, details={'traceback': traceback.format_exc(), 'summary': {'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 0}})
|
||||||
"error": str(exc),
|
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
|
||||||
"traceback": traceback.format_exc(),
|
|
||||||
"summary": {"total_count": 0, "success_count": 0, "failed_count": 0, "skipped_count": 0},
|
|
||||||
}), 500
|
|
||||||
|
|
||||||
run.status = "success" if failed_count == 0 else ("failed" if success_count == 0 else "partial_failed")
|
|
||||||
run.total_count = total_count
|
run.total_count = total_count
|
||||||
run.success_count = success_count
|
run.success_count = success_count
|
||||||
run.failed_count = failed_count
|
run.failed_count = failed_count
|
||||||
@@ -75,15 +53,4 @@ def run_internal_job(name: str):
|
|||||||
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
|
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000)
|
||||||
run.step_logs = step_logs if step_logs else None
|
run.step_logs = step_logs if step_logs else None
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
return jsonify({'summary': {'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count}, 'details': details, 'errors': errors, 'step_logs': step_logs})
|
||||||
return jsonify({
|
|
||||||
"summary": {
|
|
||||||
"total_count": total_count,
|
|
||||||
"success_count": success_count,
|
|
||||||
"failed_count": failed_count,
|
|
||||||
"skipped_count": skipped_count,
|
|
||||||
},
|
|
||||||
"details": details,
|
|
||||||
"errors": errors,
|
|
||||||
"step_logs": step_logs,
|
|
||||||
})
|
|
||||||
+117
-600
File diff suppressed because it is too large.
Load diff
@@ -1,138 +1,83 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import threading
|
import threading
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||||
from flask import Response
|
from flask import Response
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
import json
|
import json
|
||||||
|
|
||||||
from app.decorators import require_admin
|
from app.decorators import require_admin
|
||||||
from app import db
|
from app import db
|
||||||
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||||
from app.auth_jwt import get_current_user
|
from app.auth_jwt import get_current_user
|
||||||
from app.services.schedule.query_service import get_run, list_runs, list_tasks, serialize_run, serialize_task
|
from app.services.schedule.query_service import get_run, list_runs, list_tasks, serialize_run, serialize_task
|
||||||
from app.services.schedule.scheduler_service import (
|
from app.services.schedule.scheduler_service import create_task, run_task_now, update_task, _generate_run_no, _generate_test_run_no, _notify_schedule_run_wecom
|
||||||
create_task,
|
|
||||||
run_task_now,
|
|
||||||
update_task,
|
|
||||||
_generate_run_no,
|
|
||||||
_generate_test_run_no,
|
|
||||||
_notify_schedule_run_wecom,
|
|
||||||
)
|
|
||||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id, upsert_schedule_task_config, _build_fetch_sql
|
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id, upsert_schedule_task_config, _build_fetch_sql
|
||||||
from app.services.schedule.srm_service import _fetch_records
|
from app.services.schedule.srm_service import _fetch_records
|
||||||
|
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||||
schedule_admin_bp = Blueprint('schedule_admin', __name__)
|
schedule_admin_bp = Blueprint('schedule_admin', __name__)
|
||||||
|
|
||||||
|
|
||||||
def _serialize_task_for_export(task: ScheduleTask, cfg_model: ScheduleTaskConfig | None) -> dict:
|
def _serialize_task_for_export(task: ScheduleTask, cfg_model: ScheduleTaskConfig | None) -> dict:
|
||||||
payload = serialize_task(task)
|
payload = serialize_task(task)
|
||||||
payload['config'] = _serialize_task_config(cfg_model) if cfg_model else None
|
payload['config'] = _serialize_task_config(cfg_model) if cfg_model else None
|
||||||
return payload
|
return payload
|
||||||
|
|
||||||
|
|
||||||
def _serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict:
|
def _serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict:
|
||||||
return {
|
return {'row_id_key': cfg_model.row_id_key or 'id', 'log_prefix': cfg_model.log_prefix or '', 'base_fetch_sql': cfg_model.base_fetch_sql or '', 'fetch_where_conditions': cfg_model.fetch_where_conditions or '', 'fetch_order_by': cfg_model.fetch_order_by or '', 'writeback_sql': cfg_model.writeback_sql or '', 'detail_sql': cfg_model.detail_sql or '', 'alias_order': cfg_model.alias_order or [], 'detail_alias_order': cfg_model.detail_alias_order or [], 'header_labels': cfg_model.header_labels or {}, 'data_source': {'db_type': cfg_model.ds_db_type or 'sqlserver', 'host': cfg_model.ds_host or '', 'port': cfg_model.ds_port or '', 'database': cfg_model.ds_database or '', 'username': cfg_model.ds_username or '', 'password': cfg_model.ds_password or '', 'driver': cfg_model.ds_driver or '', 'encrypt': cfg_model.ds_encrypt or '', 'trust_cert': cfg_model.ds_trust_cert or ''}, 'external_api': {'url': cfg_model.api_url or '', 'method': cfg_model.api_method or 'POST', 'headers': cfg_model.api_headers or {}, 'body_template': cfg_model.api_body_template or ''}, 'dify_system_prompt': cfg_model.dify_system_prompt or ''}
|
||||||
"row_id_key": cfg_model.row_id_key or "id",
|
|
||||||
"log_prefix": cfg_model.log_prefix or "",
|
|
||||||
"base_fetch_sql": cfg_model.base_fetch_sql or "",
|
|
||||||
"fetch_where_conditions": cfg_model.fetch_where_conditions or "",
|
|
||||||
"fetch_order_by": cfg_model.fetch_order_by or "",
|
|
||||||
"writeback_sql": cfg_model.writeback_sql or "",
|
|
||||||
"detail_sql": cfg_model.detail_sql or "",
|
|
||||||
"alias_order": cfg_model.alias_order or [],
|
|
||||||
"detail_alias_order": cfg_model.detail_alias_order or [],
|
|
||||||
"header_labels": cfg_model.header_labels or {},
|
|
||||||
"data_source": {
|
|
||||||
"db_type": cfg_model.ds_db_type or "sqlserver",
|
|
||||||
"host": cfg_model.ds_host or "",
|
|
||||||
"port": cfg_model.ds_port or "",
|
|
||||||
"database": cfg_model.ds_database or "",
|
|
||||||
"username": cfg_model.ds_username or "",
|
|
||||||
"password": cfg_model.ds_password or "",
|
|
||||||
"driver": cfg_model.ds_driver or "",
|
|
||||||
"encrypt": cfg_model.ds_encrypt or "",
|
|
||||||
"trust_cert": cfg_model.ds_trust_cert or "",
|
|
||||||
},
|
|
||||||
"external_api": {
|
|
||||||
"url": cfg_model.api_url or "",
|
|
||||||
"method": cfg_model.api_method or "POST",
|
|
||||||
"headers": cfg_model.api_headers or {},
|
|
||||||
"body_template": cfg_model.api_body_template or "",
|
|
||||||
},
|
|
||||||
"dify_system_prompt": cfg_model.dify_system_prompt or "",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['GET'])
|
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['GET'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def get_schedule_task_config(task_id: int):
|
def get_schedule_task_config(task_id: int):
|
||||||
task = db.session.get(ScheduleTask, task_id)
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
if not task:
|
if not task:
|
||||||
return jsonify({'error': 'Not found'}), 404
|
raise NotFoundError('Not found')
|
||||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||||
if not cfg_model:
|
if not cfg_model:
|
||||||
return jsonify({
|
return jsonify({'data_source_type': task.data_source_type, 'config': None})
|
||||||
"data_source_type": task.data_source_type,
|
return jsonify({'data_source_type': task.data_source_type, 'config': _serialize_task_config(cfg_model)})
|
||||||
"config": None,
|
|
||||||
})
|
|
||||||
return jsonify({
|
|
||||||
"data_source_type": task.data_source_type,
|
|
||||||
"config": _serialize_task_config(cfg_model),
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['PUT'])
|
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['PUT'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def update_schedule_task_config(task_id: int):
|
def update_schedule_task_config(task_id: int):
|
||||||
task = db.session.get(ScheduleTask, task_id)
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
if not task:
|
if not task:
|
||||||
return jsonify({'error': 'Not found'}), 404
|
raise NotFoundError('Not found')
|
||||||
data = request.get_json(silent=True) or {}
|
data = request.get_json(silent=True) or {}
|
||||||
try:
|
try:
|
||||||
if "data_source_type" in data:
|
if 'data_source_type' in data:
|
||||||
task.data_source_type = str(data["data_source_type"])
|
task.data_source_type = str(data['data_source_type'])
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
config_data = data.get("config", data)
|
config_data = data.get('config', data)
|
||||||
cfg = upsert_schedule_task_config(task_id, config_data)
|
cfg = upsert_schedule_task_config(task_id, config_data)
|
||||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||||
return jsonify({
|
return jsonify({'data_source_type': task.data_source_type, 'config': _serialize_task_config(cfg_model) if cfg_model else None})
|
||||||
"data_source_type": task.data_source_type,
|
|
||||||
"config": _serialize_task_config(cfg_model) if cfg_model else None,
|
|
||||||
})
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
return jsonify({"error": str(e)}), 400
|
raise ValidationError(str(e))
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-sql', methods=['POST'])
|
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-sql', methods=['POST'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def test_schedule_sql(task_id: int):
|
def test_schedule_sql(task_id: int):
|
||||||
cfg = get_schedule_sql_config_by_task_id(task_id)
|
cfg = get_schedule_sql_config_by_task_id(task_id)
|
||||||
if not cfg:
|
if not cfg:
|
||||||
return jsonify({"error": f"Config for task {task_id} not found"}), 404
|
raise NotFoundError(f'Config for task {task_id} not found')
|
||||||
|
|
||||||
data = request.get_json(silent=True) or {}
|
data = request.get_json(silent=True) or {}
|
||||||
custom_where = str(data.get("fetch_where_conditions") or cfg.fetch_where_conditions).strip()
|
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
|
||||||
custom_order_by = str(data.get("fetch_order_by") or cfg.fetch_order_by).strip()
|
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
|
||||||
limit = min(int(data.get("limit") or 10), 100)
|
limit = min(int(data.get('limit') or 10), 100)
|
||||||
|
|
||||||
base = cfg.base_fetch_sql or cfg.fetch_sql
|
base = cfg.base_fetch_sql or cfg.fetch_sql
|
||||||
if cfg.base_fetch_sql:
|
if cfg.base_fetch_sql:
|
||||||
sql = _build_fetch_sql(base, custom_where, custom_order_by)
|
sql = _build_fetch_sql(base, custom_where, custom_order_by)
|
||||||
else:
|
else:
|
||||||
sql = base
|
sql = base
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from app.services.schedule import _build_srm_conn_str
|
from app.services.schedule import _build_srm_conn_str
|
||||||
import decimal, datetime
|
import decimal, datetime
|
||||||
if cfg.data_source and not cfg.data_source.is_empty():
|
if cfg.data_source and (not cfg.data_source.is_empty()):
|
||||||
conn_str = cfg.data_source.build_connection_string()
|
conn_str = cfg.data_source.build_connection_string()
|
||||||
else:
|
else:
|
||||||
conn_str = _build_srm_conn_str()
|
conn_str = _build_srm_conn_str()
|
||||||
rows = _fetch_records(conn_str, sql)
|
rows = _fetch_records(conn_str, sql)
|
||||||
|
|
||||||
def _safe(v):
|
def _safe(v):
|
||||||
if isinstance(v, decimal.Decimal):
|
if isinstance(v, decimal.Decimal):
|
||||||
return float(v)
|
return float(v)
|
||||||
@@ -142,75 +87,46 @@ def test_schedule_sql(task_id: int):
|
|||||||
return str(v)
|
return str(v)
|
||||||
return v
|
return v
|
||||||
result_rows = [{k: _safe(v) for k, v in r.items()} for r in rows[:limit]]
|
result_rows = [{k: _safe(v) for k, v in r.items()} for r in rows[:limit]]
|
||||||
return jsonify({
|
return jsonify({'total': len(rows), 'showing': len(result_rows), 'limit': limit, 'sql': sql, 'columns': list(result_rows[0].keys()) if result_rows else [], 'rows': result_rows})
|
||||||
"total": len(rows),
|
|
||||||
"showing": len(result_rows),
|
|
||||||
"limit": limit,
|
|
||||||
"sql": sql,
|
|
||||||
"columns": list(result_rows[0].keys()) if result_rows else [],
|
|
||||||
"rows": result_rows,
|
|
||||||
})
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return jsonify({"error": str(e), "sql": sql}), 400
|
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(e), http_status=400, details={'sql': sql})
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-run', methods=['POST'])
|
@schedule_admin_bp.route('/schedule-config/<int:task_id>/test-run', methods=['POST'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def test_schedule_run(task_id: int):
|
def test_schedule_run(task_id: int):
|
||||||
import time as _time
|
import time as _time
|
||||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||||
|
|
||||||
task = db.session.get(ScheduleTask, task_id)
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
if not task:
|
if not task:
|
||||||
return jsonify({'error': 'Not found'}), 404
|
raise NotFoundError('Not found')
|
||||||
cfg = get_schedule_sql_config_by_task_id(task_id)
|
cfg = get_schedule_sql_config_by_task_id(task_id)
|
||||||
if not cfg:
|
if not cfg:
|
||||||
return jsonify({"error": f"Config for task {task_id} not found"}), 404
|
raise NotFoundError(f'Config for task {task_id} not found')
|
||||||
|
|
||||||
data = request.get_json(silent=True) or {}
|
data = request.get_json(silent=True) or {}
|
||||||
custom_where = str(data.get("fetch_where_conditions") or cfg.fetch_where_conditions).strip()
|
custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip()
|
||||||
custom_order_by = str(data.get("fetch_order_by") or cfg.fetch_order_by).strip()
|
custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip()
|
||||||
limit = min(int(data.get("limit") or 3), 10)
|
limit = min(int(data.get('limit') or 3), 10)
|
||||||
|
|
||||||
base = cfg.base_fetch_sql or cfg.fetch_sql
|
base = cfg.base_fetch_sql or cfg.fetch_sql
|
||||||
if cfg.base_fetch_sql:
|
if cfg.base_fetch_sql:
|
||||||
test_sql = _build_fetch_sql(base, custom_where, custom_order_by)
|
test_sql = _build_fetch_sql(base, custom_where, custom_order_by)
|
||||||
else:
|
else:
|
||||||
test_sql = base
|
test_sql = base
|
||||||
|
|
||||||
from app.services.schedule import _build_srm_conn_str, _resolve_dify_agent, _resolve_schedule_user
|
from app.services.schedule import _build_srm_conn_str, _resolve_dify_agent, _resolve_schedule_user
|
||||||
from app.services.schedule.srm_service import (
|
from app.services.schedule.srm_service import _fetch_records, _run_check_job_loop, _build_record_text, _execute_writeback
|
||||||
_fetch_records,
|
if cfg.data_source and (not cfg.data_source.is_empty()):
|
||||||
_run_check_job_loop,
|
|
||||||
_build_record_text,
|
|
||||||
_execute_writeback,
|
|
||||||
)
|
|
||||||
|
|
||||||
if cfg.data_source and not cfg.data_source.is_empty():
|
|
||||||
conn_str = cfg.data_source.build_connection_string()
|
conn_str = cfg.data_source.build_connection_string()
|
||||||
else:
|
else:
|
||||||
conn_str = _build_srm_conn_str()
|
conn_str = _build_srm_conn_str()
|
||||||
|
|
||||||
agent = _resolve_dify_agent(task) if task else None
|
agent = _resolve_dify_agent(task) if task else None
|
||||||
user = _resolve_schedule_user(task) if task else "test_user"
|
user = _resolve_schedule_user(task) if task else 'test_user'
|
||||||
wait_seconds = task.wait_seconds if task else 120
|
wait_seconds = task.wait_seconds if task else 120
|
||||||
dify_agent_id = task.dify_agent_id if task else None
|
dify_agent_id = task.dify_agent_id if task else None
|
||||||
|
run = ScheduleRun(run_no=_generate_test_run_no(), schedule_task_id=task_id, trigger_type='test', triggered_by_user_id=getattr(get_current_user(), 'id', None), started_at=datetime.utcnow(), status='running')
|
||||||
run = ScheduleRun(
|
|
||||||
run_no=_generate_test_run_no(),
|
|
||||||
schedule_task_id=task_id,
|
|
||||||
trigger_type='test',
|
|
||||||
triggered_by_user_id=getattr(get_current_user(), 'id', None),
|
|
||||||
started_at=datetime.utcnow(),
|
|
||||||
status='running',
|
|
||||||
)
|
|
||||||
db.session.add(run)
|
db.session.add(run)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||||
capture_dify_execution_snapshot(run, task)
|
capture_dify_execution_snapshot(run, task)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
if not cfg.fetch_sql:
|
if not cfg.fetch_sql:
|
||||||
run.status = 'success'
|
run.status = 'success'
|
||||||
run.finished_at = datetime.utcnow()
|
run.finished_at = datetime.utcnow()
|
||||||
@@ -219,86 +135,49 @@ def test_schedule_run(task_id: int):
|
|||||||
if task.notify_enabled:
|
if task.notify_enabled:
|
||||||
_notify_schedule_run_wecom(task, run)
|
_notify_schedule_run_wecom(task, run)
|
||||||
except Exception as wecom_exc:
|
except Exception as wecom_exc:
|
||||||
current_app.logger.error("[schedule-test-run] wecom notify failed: %s", wecom_exc)
|
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return jsonify({
|
return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': '', 'limit': 0, 'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 0, 'details': [], 'errors': [], 'step_logs': [{'step': 'no_fetch_sql', 'status': 'skipped', 'detail': '无抓取SQL,跳过外部系统数据抓取'}], 'dify_agent_id': dify_agent_id})
|
||||||
"run_no": run.run_no,
|
|
||||||
"run_id": run.id,
|
|
||||||
"sql": "",
|
|
||||||
"limit": 0,
|
|
||||||
"total_count": 0,
|
|
||||||
"success_count": 0,
|
|
||||||
"failed_count": 0,
|
|
||||||
"skipped_count": 0,
|
|
||||||
"details": [],
|
|
||||||
"errors": [],
|
|
||||||
"step_logs": [{"step": "no_fetch_sql", "status": "skipped", "detail": "无抓取SQL,跳过外部系统数据抓取"}],
|
|
||||||
"dify_agent_id": dify_agent_id,
|
|
||||||
})
|
|
||||||
|
|
||||||
def _test_fetch_fn(conn_str_arg):
|
def _test_fetch_fn(conn_str_arg):
|
||||||
return _fetch_records(conn_str_arg, test_sql)
|
return _fetch_records(conn_str_arg, test_sql)
|
||||||
|
|
||||||
def _test_writeback_fn(conn_str_arg, *, row_id, run_no, dify_result, dify_message):
|
def _test_writeback_fn(conn_str_arg, *, row_id, run_no, dify_result, dify_message):
|
||||||
_execute_writeback(conn_str_arg, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id)))
|
_execute_writeback(conn_str_arg, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id)))
|
||||||
|
|
||||||
test_pre_dify = None
|
test_pre_dify = None
|
||||||
test_build_record = None
|
test_build_record = None
|
||||||
|
|
||||||
if cfg.detail_sql:
|
if cfg.detail_sql:
|
||||||
|
|
||||||
def _test_pre_dify(conn_str_arg, item, row_id_value):
|
def _test_pre_dify(conn_str_arg, item, row_id_value):
|
||||||
try:
|
try:
|
||||||
detail_rows = _fetch_records(conn_str_arg, cfg.detail_sql, params=(str(row_id_value),))
|
detail_rows = _fetch_records(conn_str_arg, cfg.detail_sql, params=(str(row_id_value),))
|
||||||
except Exception as detail_exc:
|
except Exception as detail_exc:
|
||||||
return {
|
return {'dify_result': '人工判定', 'dify_message': f'查询成分明细失败:{detail_exc}', 'writeback_srm': False, 'writeback_err': str(detail_exc)}
|
||||||
"dify_result": "人工判定",
|
|
||||||
"dify_message": f"查询成分明细失败:{detail_exc}",
|
|
||||||
"writeback_srm": False,
|
|
||||||
"writeback_err": str(detail_exc),
|
|
||||||
}
|
|
||||||
detail_lines = []
|
detail_lines = []
|
||||||
for dr in detail_rows:
|
for dr in detail_rows:
|
||||||
parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order]
|
parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order]
|
||||||
detail_lines.append(", ".join(parts))
|
detail_lines.append(', '.join(parts))
|
||||||
item["detail_text"] = "; ".join(detail_lines) if detail_lines else ""
|
item['detail_text'] = '; '.join(detail_lines) if detail_lines else ''
|
||||||
item["_detail_rows"] = detail_rows
|
item['_detail_rows'] = detail_rows
|
||||||
return None
|
return None
|
||||||
test_pre_dify = _test_pre_dify
|
test_pre_dify = _test_pre_dify
|
||||||
|
|
||||||
def _test_build_with_detail(conn_str_arg, item, row_id_value):
|
def _test_build_with_detail(conn_str_arg, item, row_id_value):
|
||||||
detail_rows = item.get("_detail_rows", [])
|
detail_rows = item.get('_detail_rows', [])
|
||||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order)
|
text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order)
|
||||||
return text, item.get("attachment")
|
return (text, item.get('attachment'))
|
||||||
test_build_record = _test_build_with_detail
|
test_build_record = _test_build_with_detail
|
||||||
else:
|
else:
|
||||||
|
|
||||||
def _test_build_simple(conn_str_arg, item, row_id_value):
|
def _test_build_simple(conn_str_arg, item, row_id_value):
|
||||||
text = _build_record_text(item, cfg.alias_order, cfg.header_labels)
|
text = _build_record_text(item, cfg.alias_order, cfg.header_labels)
|
||||||
return text, item.get("attachment")
|
return (text, item.get('attachment'))
|
||||||
test_build_record = _test_build_simple
|
test_build_record = _test_build_simple
|
||||||
|
|
||||||
start_ts = _time.time()
|
start_ts = _time.time()
|
||||||
try:
|
try:
|
||||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop(
|
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop(conn_str=conn_str, run_no=run.run_no, agent=agent, user=user, wait_seconds=wait_seconds, run_id=run.id, fetch_fn=_test_fetch_fn, build_record_fn=test_build_record, writeback_fn=_test_writeback_fn, writeback_sql=cfg.writeback_sql, row_id_key=cfg.row_id_key, log_prefix=cfg.log_prefix, fetch_sql=test_sql, max_rows=limit, pre_dify_fn=test_pre_dify, dify_system_prompt=cfg.dify_system_prompt)
|
||||||
conn_str=conn_str,
|
|
||||||
run_no=run.run_no,
|
|
||||||
agent=agent,
|
|
||||||
user=user,
|
|
||||||
wait_seconds=wait_seconds,
|
|
||||||
run_id=run.id,
|
|
||||||
fetch_fn=_test_fetch_fn,
|
|
||||||
build_record_fn=test_build_record,
|
|
||||||
writeback_fn=_test_writeback_fn,
|
|
||||||
writeback_sql=cfg.writeback_sql,
|
|
||||||
row_id_key=cfg.row_id_key,
|
|
||||||
log_prefix=cfg.log_prefix,
|
|
||||||
fetch_sql=test_sql,
|
|
||||||
max_rows=limit,
|
|
||||||
pre_dify_fn=test_pre_dify,
|
|
||||||
dify_system_prompt=cfg.dify_system_prompt,
|
|
||||||
)
|
|
||||||
|
|
||||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||||
if total_count == 0 and not errors:
|
if total_count == 0 and (not errors):
|
||||||
status = 'success'
|
status = 'success'
|
||||||
elif failed_count == 0:
|
elif failed_count == 0:
|
||||||
status = 'success'
|
status = 'success'
|
||||||
@@ -306,22 +185,13 @@ def test_schedule_run(task_id: int):
|
|||||||
status = 'failed'
|
status = 'failed'
|
||||||
else:
|
else:
|
||||||
status = 'partial_failed'
|
status = 'partial_failed'
|
||||||
|
|
||||||
header_order = cfg.alias_order if cfg.alias_order else None
|
header_order = cfg.alias_order if cfg.alias_order else None
|
||||||
header_labels = cfg.header_labels if cfg.header_labels else None
|
header_labels = cfg.header_labels if cfg.header_labels else None
|
||||||
detail_alias_order = cfg.detail_alias_order or []
|
detail_alias_order = cfg.detail_alias_order or []
|
||||||
try:
|
try:
|
||||||
file_data, file_name, file_size = export_schedule_result_excel(
|
file_data, file_name, file_size = export_schedule_result_excel(run_no=run.run_no, summary={'status': status, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'duration_ms': duration_ms}, details=details, header_order=header_order, header_labels=header_labels, detail_alias_order=detail_alias_order)
|
||||||
run_no=run.run_no,
|
|
||||||
summary={"status": status, "total_count": total_count, "success_count": success_count, "failed_count": failed_count, "duration_ms": duration_ms},
|
|
||||||
details=details,
|
|
||||||
header_order=header_order,
|
|
||||||
header_labels=header_labels,
|
|
||||||
detail_alias_order=detail_alias_order,
|
|
||||||
)
|
|
||||||
except Exception:
|
except Exception:
|
||||||
file_data, file_name, file_size = None, None, 0
|
file_data, file_name, file_size = (None, None, 0)
|
||||||
|
|
||||||
run.finished_at = datetime.utcnow()
|
run.finished_at = datetime.utcnow()
|
||||||
run.duration_ms = duration_ms
|
run.duration_ms = duration_ms
|
||||||
run.status = status
|
run.status = status
|
||||||
@@ -330,7 +200,7 @@ def test_schedule_run(task_id: int):
|
|||||||
run.failed_count = failed_count
|
run.failed_count = failed_count
|
||||||
run.skipped_count = skipped_count
|
run.skipped_count = skipped_count
|
||||||
run.step_logs = step_logs if step_logs else None
|
run.step_logs = step_logs if step_logs else None
|
||||||
run.error_message = "; ".join(errors[:3]) if errors else None
|
run.error_message = '; '.join(errors[:3]) if errors else None
|
||||||
run.excel_file_data = file_data
|
run.excel_file_data = file_data
|
||||||
run.excel_file_name = file_name
|
run.excel_file_name = file_name
|
||||||
run.excel_file_size = file_size or 0
|
run.excel_file_size = file_size or 0
|
||||||
@@ -338,10 +208,10 @@ def test_schedule_run(task_id: int):
|
|||||||
if task.notify_enabled:
|
if task.notify_enabled:
|
||||||
_notify_schedule_run_wecom(task, run)
|
_notify_schedule_run_wecom(task, run)
|
||||||
except Exception as wecom_exc:
|
except Exception as wecom_exc:
|
||||||
current_app.logger.error("[schedule-test-run] wecom notify failed: %s", wecom_exc)
|
current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
import decimal, datetime as dt
|
import decimal, datetime as dt
|
||||||
|
|
||||||
def _safe(v):
|
def _safe(v):
|
||||||
if isinstance(v, decimal.Decimal):
|
if isinstance(v, decimal.Decimal):
|
||||||
return float(v)
|
return float(v)
|
||||||
@@ -350,27 +220,11 @@ def test_schedule_run(task_id: int):
|
|||||||
if isinstance(v, dt.timedelta):
|
if isinstance(v, dt.timedelta):
|
||||||
return str(v)
|
return str(v)
|
||||||
return v
|
return v
|
||||||
|
|
||||||
safe_details = []
|
safe_details = []
|
||||||
for item in details:
|
for item in details:
|
||||||
safe_item = {k: _safe(v) for k, v in item.items()}
|
safe_item = {k: _safe(v) for k, v in item.items()}
|
||||||
safe_details.append(safe_item)
|
safe_details.append(safe_item)
|
||||||
|
return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': test_sql, 'limit': limit, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count, 'details': safe_details, 'errors': errors, 'step_logs': step_logs, 'dify_agent_id': dify_agent_id, 'dify_execution_snapshot': run.dify_execution_snapshot})
|
||||||
return jsonify({
|
|
||||||
"run_no": run.run_no,
|
|
||||||
"run_id": run.id,
|
|
||||||
"sql": test_sql,
|
|
||||||
"limit": limit,
|
|
||||||
"total_count": total_count,
|
|
||||||
"success_count": success_count,
|
|
||||||
"failed_count": failed_count,
|
|
||||||
"skipped_count": skipped_count,
|
|
||||||
"details": safe_details,
|
|
||||||
"errors": errors,
|
|
||||||
"step_logs": step_logs,
|
|
||||||
"dify_agent_id": dify_agent_id,
|
|
||||||
"dify_execution_snapshot": run.dify_execution_snapshot,
|
|
||||||
})
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||||
run.finished_at = datetime.utcnow()
|
run.finished_at = datetime.utcnow()
|
||||||
@@ -379,35 +233,24 @@ def test_schedule_run(task_id: int):
|
|||||||
run.error_message = str(e)
|
run.error_message = str(e)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
import traceback
|
import traceback
|
||||||
return jsonify({"error": str(e), "sql": test_sql, "traceback": traceback.format_exc()}), 400
|
raise AppError(code='SYSTEM.HTTP_ERROR', message=str(e), http_status=400, details={'sql': test_sql, 'traceback': traceback.format_exc()})
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedules', methods=['GET'])
|
@schedule_admin_bp.route('/schedules', methods=['GET'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def get_schedules():
|
def get_schedules():
|
||||||
return jsonify(list_tasks())
|
return jsonify(list_tasks())
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedules/<int:task_id>/export', methods=['GET'])
|
@schedule_admin_bp.route('/schedules/<int:task_id>/export', methods=['GET'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def export_schedule(task_id: int):
|
def export_schedule(task_id: int):
|
||||||
task = db.session.get(ScheduleTask, task_id)
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
if not task:
|
if not task:
|
||||||
return jsonify({'error': 'Not found'}), 404
|
raise NotFoundError('Not found')
|
||||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||||
payload = {
|
payload = {'schema_version': 1, 'exported_at': datetime.utcnow().isoformat(), 'schedules': [_serialize_task_for_export(task, cfg_model)]}
|
||||||
"schema_version": 1,
|
|
||||||
"exported_at": datetime.utcnow().isoformat(),
|
|
||||||
"schedules": [_serialize_task_for_export(task, cfg_model)],
|
|
||||||
}
|
|
||||||
body = json.dumps(payload, ensure_ascii=False, indent=2)
|
body = json.dumps(payload, ensure_ascii=False, indent=2)
|
||||||
filename = f"{(task.schedule_no or f'schedule_{task.id}')}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
|
filename = f"{task.schedule_no or f'schedule_{task.id}'}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
|
||||||
return Response(
|
return Response(body, mimetype='application/json; charset=utf-8', headers={'Content-Disposition': f'attachment; filename="{filename}"'})
|
||||||
body,
|
|
||||||
mimetype='application/json; charset=utf-8',
|
|
||||||
headers={'Content-Disposition': f'attachment; filename="{filename}"'},
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedules/import', methods=['POST'])
|
@schedule_admin_bp.route('/schedules/import', methods=['POST'])
|
||||||
@require_admin
|
@require_admin
|
||||||
@@ -415,13 +258,11 @@ def import_schedules():
|
|||||||
data = request.get_json(silent=True) or {}
|
data = request.get_json(silent=True) or {}
|
||||||
schedules = data.get('schedules')
|
schedules = data.get('schedules')
|
||||||
if not isinstance(schedules, list):
|
if not isinstance(schedules, list):
|
||||||
return jsonify({'error': 'Invalid import file: schedules missing'}), 400
|
raise ValidationError('Invalid import file: schedules missing')
|
||||||
|
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
imported = 0
|
imported = 0
|
||||||
skipped = 0
|
skipped = 0
|
||||||
errors: list[str] = []
|
errors: list[str] = []
|
||||||
|
|
||||||
for item in schedules:
|
for item in schedules:
|
||||||
if not isinstance(item, dict):
|
if not isinstance(item, dict):
|
||||||
skipped += 1
|
skipped += 1
|
||||||
@@ -432,46 +273,19 @@ def import_schedules():
|
|||||||
owner_user_id = int(item.get('owner_user_id'))
|
owner_user_id = int(item.get('owner_user_id'))
|
||||||
if not name or not cron_expr:
|
if not name or not cron_expr:
|
||||||
raise ValueError('name or cron_expr missing')
|
raise ValueError('name or cron_expr missing')
|
||||||
|
|
||||||
existing = None
|
existing = None
|
||||||
schedule_no = str(item.get('schedule_no') or '').strip()
|
schedule_no = str(item.get('schedule_no') or '').strip()
|
||||||
if schedule_no:
|
if schedule_no:
|
||||||
existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first()
|
existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first()
|
||||||
|
task_payload = {'name': name, 'schedule_type': str(item.get('schedule_type') or 'platform_app'), 'owner_user_id': owner_user_id, 'cron_expr': cron_expr, 'wait_seconds': int(item.get('wait_seconds') or 0), 'dify_agent_id': item.get('dify_agent_id'), 'platform_api_path': item.get('platform_api_path'), 'notify_user_ids_json': item.get('notify_user_ids_json') if isinstance(item.get('notify_user_ids_json'), list) else [], 'notify_enabled': bool(item.get('notify_enabled', True)), 'enabled': bool(item.get('enabled', True)), 'data_source_type': str(item.get('data_source_type') or 'database')}
|
||||||
task_payload = {
|
|
||||||
'name': name,
|
|
||||||
'schedule_type': str(item.get('schedule_type') or 'platform_app'),
|
|
||||||
'owner_user_id': owner_user_id,
|
|
||||||
'cron_expr': cron_expr,
|
|
||||||
'wait_seconds': int(item.get('wait_seconds') or 0),
|
|
||||||
'dify_agent_id': item.get('dify_agent_id'),
|
|
||||||
'platform_api_path': item.get('platform_api_path'),
|
|
||||||
'notify_user_ids_json': item.get('notify_user_ids_json') if isinstance(item.get('notify_user_ids_json'), list) else [],
|
|
||||||
'notify_enabled': bool(item.get('notify_enabled', True)),
|
|
||||||
'enabled': bool(item.get('enabled', True)),
|
|
||||||
'data_source_type': str(item.get('data_source_type') or 'database'),
|
|
||||||
}
|
|
||||||
cfg = item.get('config') if isinstance(item.get('config'), dict) else None
|
cfg = item.get('config') if isinstance(item.get('config'), dict) else None
|
||||||
|
|
||||||
if existing:
|
if existing:
|
||||||
update_task(existing, payload=task_payload, actor_id=getattr(user, 'id', None))
|
update_task(existing, payload=task_payload, actor_id=getattr(user, 'id', None))
|
||||||
existing.data_source_type = task_payload['data_source_type']
|
existing.data_source_type = task_payload['data_source_type']
|
||||||
if cfg:
|
if cfg:
|
||||||
upsert_schedule_task_config(existing.id, cfg)
|
upsert_schedule_task_config(existing.id, cfg)
|
||||||
else:
|
else:
|
||||||
task = create_task(
|
task = create_task(name=name, schedule_type=task_payload['schedule_type'], owner_user_id=owner_user_id, cron_expr=cron_expr, wait_seconds=task_payload['wait_seconds'], dify_agent_id=task_payload['dify_agent_id'], platform_api_path=task_payload['platform_api_path'], notify_user_ids_json=task_payload['notify_user_ids_json'], notify_enabled=task_payload['notify_enabled'], enabled=task_payload['enabled'], actor_id=getattr(user, 'id', None))
|
||||||
name=name,
|
|
||||||
schedule_type=task_payload['schedule_type'],
|
|
||||||
owner_user_id=owner_user_id,
|
|
||||||
cron_expr=cron_expr,
|
|
||||||
wait_seconds=task_payload['wait_seconds'],
|
|
||||||
dify_agent_id=task_payload['dify_agent_id'],
|
|
||||||
platform_api_path=task_payload['platform_api_path'],
|
|
||||||
notify_user_ids_json=task_payload['notify_user_ids_json'],
|
|
||||||
notify_enabled=task_payload['notify_enabled'],
|
|
||||||
enabled=task_payload['enabled'],
|
|
||||||
actor_id=getattr(user, 'id', None),
|
|
||||||
)
|
|
||||||
task.data_source_type = task_payload['data_source_type']
|
task.data_source_type = task_payload['data_source_type']
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
if cfg:
|
if cfg:
|
||||||
@@ -480,15 +294,8 @@ def import_schedules():
|
|||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
errors.append(str(exc))
|
errors.append(str(exc))
|
||||||
skipped += 1
|
skipped += 1
|
||||||
|
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return jsonify({
|
return jsonify({'ok': True, 'imported': imported, 'skipped': skipped, 'errors': errors[:20]})
|
||||||
'ok': True,
|
|
||||||
'imported': imported,
|
|
||||||
'skipped': skipped,
|
|
||||||
'errors': errors[:20],
|
|
||||||
})
|
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedules', methods=['POST'])
|
@schedule_admin_bp.route('/schedules', methods=['POST'])
|
||||||
@require_admin
|
@require_admin
|
||||||
@@ -496,24 +303,11 @@ def post_schedule():
|
|||||||
data = request.get_json(silent=True) or {}
|
data = request.get_json(silent=True) or {}
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
data_source_type = str(data.get('data_source_type') or 'database')
|
data_source_type = str(data.get('data_source_type') or 'database')
|
||||||
task = create_task(
|
task = create_task(name=str(data.get('name') or '').strip(), schedule_type='platform_app', owner_user_id=int(data.get('owner_user_id')), cron_expr=str(data.get('cron_expr') or '').strip(), wait_seconds=int(data.get('wait_seconds') or 0), dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None, platform_api_path=str(data.get('platform_api_path') or '').strip() or None, notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [], notify_enabled=bool(data.get('notify_enabled', True)), enabled=bool(data.get('enabled', True)), actor_id=getattr(user, 'id', None))
|
||||||
name=str(data.get('name') or '').strip(),
|
|
||||||
schedule_type='platform_app',
|
|
||||||
owner_user_id=int(data.get('owner_user_id')),
|
|
||||||
cron_expr=str(data.get('cron_expr') or '').strip(),
|
|
||||||
wait_seconds=int(data.get('wait_seconds') or 0),
|
|
||||||
dify_agent_id=(int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None),
|
|
||||||
platform_api_path=str(data.get('platform_api_path') or '').strip() or None,
|
|
||||||
notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [],
|
|
||||||
notify_enabled=bool(data.get('notify_enabled', True)),
|
|
||||||
enabled=bool(data.get('enabled', True)),
|
|
||||||
actor_id=getattr(user, 'id', None),
|
|
||||||
)
|
|
||||||
task.data_source_type = data_source_type
|
task.data_source_type = data_source_type
|
||||||
task.platform_api_path = f"/{task.id}"
|
task.platform_api_path = f'/{task.id}'
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
db.session.refresh(task)
|
db.session.refresh(task)
|
||||||
|
|
||||||
config_data = data.get('config')
|
config_data = data.get('config')
|
||||||
if config_data:
|
if config_data:
|
||||||
upsert_schedule_task_config(task.id, config_data)
|
upsert_schedule_task_config(task.id, config_data)
|
||||||
@@ -522,79 +316,64 @@ def post_schedule():
|
|||||||
if cfg_model and cfg_model.dify_system_prompt:
|
if cfg_model and cfg_model.dify_system_prompt:
|
||||||
cfg_model.dify_system_prompt = None
|
cfg_model.dify_system_prompt = None
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
return (jsonify(serialize_task(task)), 201)
|
||||||
return jsonify(serialize_task(task)), 201
|
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['GET'])
|
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['GET'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def get_schedule(task_id: int):
|
def get_schedule(task_id: int):
|
||||||
task = db.session.get(ScheduleTask, task_id)
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
if not task:
|
if not task:
|
||||||
return jsonify({'error': 'Not found'}), 404
|
raise NotFoundError('Not found')
|
||||||
return jsonify(serialize_task(task))
|
return jsonify(serialize_task(task))
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['PATCH'])
|
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['PATCH'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def patch_schedule(task_id: int):
|
def patch_schedule(task_id: int):
|
||||||
task = db.session.get(ScheduleTask, task_id)
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
if not task:
|
if not task:
|
||||||
return jsonify({'error': 'Not found'}), 404
|
raise NotFoundError('Not found')
|
||||||
data = request.get_json(silent=True) or {}
|
data = request.get_json(silent=True) or {}
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
|
if 'data_source_type' in data:
|
||||||
if "data_source_type" in data:
|
task.data_source_type = str(data['data_source_type'])
|
||||||
task.data_source_type = str(data["data_source_type"])
|
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
config_data = data.get('config')
|
config_data = data.get('config')
|
||||||
if config_data:
|
if config_data:
|
||||||
upsert_schedule_task_config(task_id, config_data)
|
upsert_schedule_task_config(task_id, config_data)
|
||||||
|
|
||||||
task = update_task(task, payload=data, actor_id=getattr(user, 'id', None))
|
task = update_task(task, payload=data, actor_id=getattr(user, 'id', None))
|
||||||
|
|
||||||
if not task.dify_agent_id:
|
if not task.dify_agent_id:
|
||||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||||
if cfg_model and cfg_model.dify_system_prompt:
|
if cfg_model and cfg_model.dify_system_prompt:
|
||||||
cfg_model.dify_system_prompt = None
|
cfg_model.dify_system_prompt = None
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
return jsonify(serialize_task(task))
|
return jsonify(serialize_task(task))
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['DELETE'])
|
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['DELETE'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def delete_schedule(task_id: int):
|
def delete_schedule(task_id: int):
|
||||||
task = db.session.get(ScheduleTask, task_id)
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
if not task:
|
if not task:
|
||||||
return jsonify({'error': 'Not found'}), 404
|
raise NotFoundError('Not found')
|
||||||
|
|
||||||
from app.services.schedule.scheduler_service import request_cancel_run
|
from app.services.schedule.scheduler_service import request_cancel_run
|
||||||
running_runs = db.session.query(ScheduleRun).filter(
|
running_runs = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status == 'running').all()
|
||||||
ScheduleRun.schedule_task_id == task_id,
|
|
||||||
ScheduleRun.status == "running",
|
|
||||||
).all()
|
|
||||||
for rr in running_runs:
|
for rr in running_runs:
|
||||||
request_cancel_run(rr.id)
|
request_cancel_run(rr.id)
|
||||||
rr.status = "failed"
|
rr.status = 'failed'
|
||||||
rr.error_message = "排程已被删除,执行中断"
|
rr.error_message = '排程已被删除,执行中断'
|
||||||
rr.finished_at = datetime.utcnow()
|
rr.finished_at = datetime.utcnow()
|
||||||
if running_runs:
|
if running_runs:
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
|
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
|
||||||
db.session.delete(task)
|
db.session.delete(task)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return jsonify({'ok': True})
|
return jsonify({'ok': True})
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
|
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def enable_schedule(task_id: int):
|
def enable_schedule(task_id: int):
|
||||||
task = db.session.get(ScheduleTask, task_id)
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
if not task:
|
if not task:
|
||||||
return jsonify({'error': 'Not found'}), 404
|
raise NotFoundError('Not found')
|
||||||
task.enabled = True
|
task.enabled = True
|
||||||
if task.cron_expr:
|
if task.cron_expr:
|
||||||
try:
|
try:
|
||||||
@@ -606,44 +385,29 @@ def enable_schedule(task_id: int):
|
|||||||
db.session.commit()
|
db.session.commit()
|
||||||
return jsonify({'ok': True})
|
return jsonify({'ok': True})
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
|
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def disable_schedule(task_id: int):
|
def disable_schedule(task_id: int):
|
||||||
task = db.session.get(ScheduleTask, task_id)
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
if not task:
|
if not task:
|
||||||
return jsonify({'error': 'Not found'}), 404
|
raise NotFoundError('Not found')
|
||||||
task.enabled = False
|
task.enabled = False
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return jsonify({'ok': True})
|
return jsonify({'ok': True})
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def run_schedule(task_id: int):
|
def run_schedule(task_id: int):
|
||||||
task = db.session.get(ScheduleTask, task_id)
|
task = db.session.get(ScheduleTask, task_id)
|
||||||
if not task:
|
if not task:
|
||||||
return jsonify({'error': 'Not found'}), 404
|
raise NotFoundError('Not found')
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
|
existing = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task.id, ScheduleRun.status == 'running').first()
|
||||||
existing = db.session.query(ScheduleRun).filter(
|
|
||||||
ScheduleRun.schedule_task_id == task.id,
|
|
||||||
ScheduleRun.status == "running",
|
|
||||||
).first()
|
|
||||||
if existing:
|
if existing:
|
||||||
return jsonify({'error': '该排程正在执行中,请等待完成后再试', 'run_id': existing.id}), 409
|
raise ConflictError('该排程正在执行中,请等待完成后再试', details={'run_id': existing.id})
|
||||||
|
run = ScheduleRun(run_no=_generate_run_no(), schedule_task_id=task.id, trigger_type='manual', triggered_by_user_id=getattr(user, 'id', None), started_at=datetime.utcnow(), status='running')
|
||||||
run = ScheduleRun(
|
|
||||||
run_no=_generate_run_no(),
|
|
||||||
schedule_task_id=task.id,
|
|
||||||
trigger_type='manual',
|
|
||||||
triggered_by_user_id=getattr(user, 'id', None),
|
|
||||||
started_at=datetime.utcnow(),
|
|
||||||
status='running',
|
|
||||||
)
|
|
||||||
db.session.add(run)
|
db.session.add(run)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
app = current_app._get_current_object()
|
app = current_app._get_current_object()
|
||||||
run_id = run.id
|
run_id = run.id
|
||||||
|
|
||||||
@@ -665,15 +429,12 @@ def run_schedule(task_id: int):
|
|||||||
db.session.commit()
|
db.session.commit()
|
||||||
except Exception:
|
except Exception:
|
||||||
db.session.rollback()
|
db.session.rollback()
|
||||||
current_app.logger.error("[schedule-run] run_id=%s failed: %s", run_id, exc, exc_info=True)
|
current_app.logger.error('[schedule-run] run_id=%s failed: %s', run_id, exc, exc_info=True)
|
||||||
|
t = threading.Thread(target=_background, daemon=True, name=f'schedule-run-{run_id}')
|
||||||
t = threading.Thread(target=_background, daemon=True, name=f"schedule-run-{run_id}")
|
|
||||||
t.start()
|
t.start()
|
||||||
|
|
||||||
fresh = db.session.get(ScheduleRun, run_id)
|
fresh = db.session.get(ScheduleRun, run_id)
|
||||||
return jsonify(serialize_run(fresh))
|
return jsonify(serialize_run(fresh))
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedules/<int:task_id>/runs', methods=['GET'])
|
@schedule_admin_bp.route('/schedules/<int:task_id>/runs', methods=['GET'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def get_schedule_runs(task_id: int):
|
def get_schedule_runs(task_id: int):
|
||||||
@@ -695,24 +456,22 @@ def get_schedule_runs(task_id: int):
|
|||||||
pass
|
pass
|
||||||
return jsonify(list_runs(task_id=task_id, status=status, started_after=started_after, started_before=started_before, limit=limit))
|
return jsonify(list_runs(task_id=task_id, status=status, started_after=started_after, started_before=started_before, limit=limit))
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
@schedule_admin_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def get_schedule_run(run_id: int):
|
def get_schedule_run(run_id: int):
|
||||||
run = get_run(run_id)
|
run = get_run(run_id)
|
||||||
if not run:
|
if not run:
|
||||||
return jsonify({'error': 'Not found'}), 404
|
raise NotFoundError('Not found')
|
||||||
return jsonify(serialize_run(run))
|
return jsonify(serialize_run(run))
|
||||||
|
|
||||||
|
|
||||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||||
@require_admin
|
@require_admin
|
||||||
def get_schedule_run_excel(run_id: int):
|
def get_schedule_run_excel(run_id: int):
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
run = get_run(run_id)
|
run = get_run(run_id)
|
||||||
if not run:
|
if not run:
|
||||||
return jsonify({'error': 'Not found'}), 404
|
raise NotFoundError('Not found')
|
||||||
if not run.excel_file_data:
|
if not run.excel_file_data:
|
||||||
return jsonify({'error': 'Excel not found'}), 404
|
raise NotFoundError('Excel not found')
|
||||||
buf = BytesIO(run.excel_file_data)
|
buf = BytesIO(run.excel_file_data)
|
||||||
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||||
+266
-1043
File diff suppressed because it is too large.
Load diff
@@ -1,27 +1,20 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from flask import Blueprint, jsonify, request, send_file
|
from flask import Blueprint, jsonify, request, send_file
|
||||||
|
|
||||||
from app.auth_jwt import get_current_user
|
from app.auth_jwt import get_current_user
|
||||||
from app.services.schedule.query_service import can_view_run, get_run, list_runs, serialize_run
|
from app.services.schedule.query_service import can_view_run, get_run, list_runs, serialize_run
|
||||||
|
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||||
workspace_schedule_bp = Blueprint('workspace_schedule', __name__)
|
workspace_schedule_bp = Blueprint('workspace_schedule', __name__)
|
||||||
|
|
||||||
|
|
||||||
def _require_user():
|
def _require_user():
|
||||||
user = get_current_user()
|
user = get_current_user()
|
||||||
if not user:
|
if not user:
|
||||||
return None, (jsonify({'error': 'Unauthorized'}), 401)
|
raise UnauthorizedError()
|
||||||
return user, None
|
return user
|
||||||
|
|
||||||
|
|
||||||
@workspace_schedule_bp.route('/schedule-runs', methods=['GET'])
|
@workspace_schedule_bp.route('/schedule-runs', methods=['GET'])
|
||||||
def workspace_schedule_runs():
|
def workspace_schedule_runs():
|
||||||
user, err = _require_user()
|
user = _require_user()
|
||||||
if err:
|
|
||||||
return err
|
|
||||||
status = str(request.args.get('status') or '').strip() or None
|
status = str(request.args.get('status') or '').strip() or None
|
||||||
schedule_name = str(request.args.get('schedule_name') or '').strip() or None
|
schedule_name = str(request.args.get('schedule_name') or '').strip() or None
|
||||||
started_after_str = request.args.get('started_after')
|
started_after_str = request.args.get('started_after')
|
||||||
@@ -29,41 +22,28 @@ def workspace_schedule_runs():
|
|||||||
started_after = datetime.fromisoformat(started_after_str) if started_after_str else None
|
started_after = datetime.fromisoformat(started_after_str) if started_after_str else None
|
||||||
started_before = datetime.fromisoformat(started_before_str) if started_before_str else None
|
started_before = datetime.fromisoformat(started_before_str) if started_before_str else None
|
||||||
limit = int(request.args.get('limit') or 100)
|
limit = int(request.args.get('limit') or 100)
|
||||||
return jsonify(list_runs(
|
return jsonify(list_runs(notify_user_id=user.id, schedule_name=schedule_name, status=status, started_after=started_after, started_before=started_before, limit=limit))
|
||||||
notify_user_id=user.id,
|
|
||||||
schedule_name=schedule_name,
|
|
||||||
status=status,
|
|
||||||
started_after=started_after,
|
|
||||||
started_before=started_before,
|
|
||||||
limit=limit,
|
|
||||||
))
|
|
||||||
|
|
||||||
|
|
||||||
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
||||||
def workspace_schedule_run_detail(run_id: int):
|
def workspace_schedule_run_detail(run_id: int):
|
||||||
user, err = _require_user()
|
user = _require_user()
|
||||||
if err:
|
|
||||||
return err
|
|
||||||
run = get_run(run_id)
|
run = get_run(run_id)
|
||||||
if not run:
|
if not run:
|
||||||
return jsonify({'error': 'Not found'}), 404
|
raise NotFoundError('Not found')
|
||||||
if not can_view_run(run, user.id):
|
if not can_view_run(run, user.id):
|
||||||
return jsonify({'error': 'Forbidden'}), 403
|
raise ForbiddenError('Forbidden')
|
||||||
return jsonify(serialize_run(run))
|
return jsonify(serialize_run(run))
|
||||||
|
|
||||||
|
|
||||||
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||||
def workspace_schedule_run_excel(run_id: int):
|
def workspace_schedule_run_excel(run_id: int):
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
user, err = _require_user()
|
user = _require_user()
|
||||||
if err:
|
|
||||||
return err
|
|
||||||
run = get_run(run_id)
|
run = get_run(run_id)
|
||||||
if not run:
|
if not run:
|
||||||
return jsonify({'error': 'Not found'}), 404
|
raise NotFoundError('Not found')
|
||||||
if not can_view_run(run, user.id):
|
if not can_view_run(run, user.id):
|
||||||
return jsonify({'error': 'Forbidden'}), 403
|
raise ForbiddenError('Forbidden')
|
||||||
if not run.excel_file_data:
|
if not run.excel_file_data:
|
||||||
return jsonify({'error': 'Excel not found'}), 404
|
raise NotFoundError('Excel not found')
|
||||||
buf = BytesIO(run.excel_file_data)
|
buf = BytesIO(run.excel_file_data)
|
||||||
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
|
||||||
+10
-34
@@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
backend/app/decorators.py
|
backend/app/decorators.py
|
||||||
文件用途:权限控制装饰器集合
|
文件用途:权限控制装饰器集合
|
||||||
@@ -9,7 +8,7 @@ from functools import wraps
|
|||||||
from flask import request, jsonify, g, current_app
|
from flask import request, jsonify, g, current_app
|
||||||
from app.models import Agent, User
|
from app.models import Agent, User
|
||||||
from app.auth_jwt import get_current_user as _auth_current_user
|
from app.auth_jwt import get_current_user as _auth_current_user
|
||||||
|
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||||
|
|
||||||
def _get_current_user() -> User:
|
def _get_current_user() -> User:
|
||||||
"""Resolve current user via JWT auth flow (legacy headers optional via config)."""
|
"""Resolve current user via JWT auth flow (legacy headers optional via config)."""
|
||||||
@@ -18,7 +17,6 @@ def _get_current_user() -> User:
|
|||||||
g.current_user = user
|
g.current_user = user
|
||||||
return user
|
return user
|
||||||
|
|
||||||
|
|
||||||
def require_agent_permission(f):
|
def require_agent_permission(f):
|
||||||
"""
|
"""
|
||||||
装饰器:检查当前用户是否有指定 Agent 的访问权限
|
装饰器:检查当前用户是否有指定 Agent 的访问权限
|
||||||
@@ -35,42 +33,24 @@ def require_agent_permission(f):
|
|||||||
|
|
||||||
@wraps(f)
|
@wraps(f)
|
||||||
def decorated_function(*args, **kwargs):
|
def decorated_function(*args, **kwargs):
|
||||||
# 从 JSON 请求体中解析数据
|
|
||||||
data = request.get_json(silent=True) or {}
|
data = request.get_json(silent=True) or {}
|
||||||
# 获取 agent_id (优先从 Body,其次从 Query)
|
|
||||||
agent_id = data.get('agent_id') or request.args.get('agent_id')
|
agent_id = data.get('agent_id') or request.args.get('agent_id')
|
||||||
|
|
||||||
# 如果未提供 agent_id,则返回 400 错误
|
|
||||||
if not agent_id:
|
if not agent_id:
|
||||||
return jsonify({'error': 'agent_id is required'}), 400
|
raise ValidationError('agent_id is required')
|
||||||
|
|
||||||
# 获取当前用户
|
|
||||||
user = _get_current_user()
|
user = _get_current_user()
|
||||||
if not user:
|
if not user:
|
||||||
return jsonify({'error': 'Unauthorized'}), 401
|
raise UnauthorizedError('Unauthorized')
|
||||||
|
|
||||||
# 查询目标 Agent 是否存在
|
|
||||||
agent = Agent.query.get(agent_id)
|
agent = Agent.query.get(agent_id)
|
||||||
if not agent:
|
if not agent:
|
||||||
return jsonify({'error': 'Agent not found'}), 404
|
raise NotFoundError('Agent not found')
|
||||||
|
|
||||||
# 将 agent 对象挂在 g 上,方便下游使用
|
|
||||||
g.current_agent = agent
|
g.current_agent = agent
|
||||||
|
|
||||||
# 如果用户是管理员,跳过权限检查直接放行
|
|
||||||
if user.role == 'admin':
|
if user.role == 'admin':
|
||||||
return f(*args, **kwargs)
|
return f(*args, **kwargs)
|
||||||
|
|
||||||
# 非管理员:检查多对多关联表中是否存在权限
|
|
||||||
if agent not in user.agents:
|
if agent not in user.agents:
|
||||||
return jsonify({'error': 'Permission denied for this agent'}), 403
|
raise ForbiddenError('Permission denied for this agent')
|
||||||
|
|
||||||
# 鉴权通过,调用原始视图函数
|
|
||||||
return f(*args, **kwargs)
|
return f(*args, **kwargs)
|
||||||
|
|
||||||
return decorated_function
|
return decorated_function
|
||||||
|
|
||||||
|
|
||||||
def require_admin(f):
|
def require_admin(f):
|
||||||
"""
|
"""
|
||||||
装饰器:限制只有管理员角色才能访问的接口
|
装饰器:限制只有管理员角色才能访问的接口
|
||||||
@@ -81,16 +61,12 @@ def require_admin(f):
|
|||||||
|
|
||||||
@wraps(f)
|
@wraps(f)
|
||||||
def decorated_function(*args, **kwargs):
|
def decorated_function(*args, **kwargs):
|
||||||
# 获取当前用户
|
|
||||||
user = _get_current_user()
|
user = _get_current_user()
|
||||||
if not user:
|
if not user:
|
||||||
return jsonify({'error': 'Unauthorized'}), 401
|
raise UnauthorizedError('Unauthorized')
|
||||||
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and not request.headers.get('Authorization'):
|
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and (not request.headers.get('Authorization')):
|
||||||
return jsonify({'error': 'JWT token is required'}), 401
|
raise UnauthorizedError('JWT token is required')
|
||||||
# 如果不是管理员,则返回 403
|
|
||||||
if user.role != 'admin':
|
if user.role != 'admin':
|
||||||
return jsonify({'error': 'Admin privilege required'}), 403
|
raise ForbiddenError('Admin privilege required')
|
||||||
# 是管理员则放行
|
|
||||||
return f(*args, **kwargs)
|
return f(*args, **kwargs)
|
||||||
|
return decorated_function
|
||||||
return decorated_function
|
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
"""
|
||||||
|
backend/app/errors.py
|
||||||
|
用途:定义后端统一业务异常类型,供全局异常处理器识别并输出标准错误响应。
|
||||||
|
说明:
|
||||||
|
1. AppError 作为基础异常,包含 code/message/http_status/details/retryable。
|
||||||
|
2. 各子类用于表达常见语义(参数错误、未授权、无权限、资源不存在)。
|
||||||
|
3. 业务层可直接 raise 这些异常,避免到处手写 jsonify(error)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class AppError(Exception):
|
||||||
|
code: str
|
||||||
|
message: str
|
||||||
|
http_status: int = 400
|
||||||
|
details: dict[str, Any] = field(default_factory=dict)
|
||||||
|
retryable: bool = False
|
||||||
|
|
||||||
|
|
||||||
|
class ValidationError(AppError):
|
||||||
|
def __init__(self, message: str = "Invalid request parameters", *, details: dict[str, Any] | None = None):
|
||||||
|
super().__init__(
|
||||||
|
code="VALIDATION.INVALID_PARAM",
|
||||||
|
message=message,
|
||||||
|
http_status=400,
|
||||||
|
details=details or {},
|
||||||
|
retryable=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class UnauthorizedError(AppError):
|
||||||
|
def __init__(self, message: str = "Unauthorized"):
|
||||||
|
super().__init__(code="AUTH.UNAUTHORIZED", message=message, http_status=401, retryable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class ForbiddenError(AppError):
|
||||||
|
def __init__(self, message: str = "Forbidden"):
|
||||||
|
super().__init__(code="AUTH.FORBIDDEN", message=message, http_status=403, retryable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class NotFoundError(AppError):
|
||||||
|
def __init__(self, message: str = "Resource not found"):
|
||||||
|
super().__init__(code="RESOURCE.NOT_FOUND", message=message, http_status=404, retryable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class ConflictError(AppError):
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
message: str = "Resource conflict",
|
||||||
|
*,
|
||||||
|
code: str = "RESOURCE.CONFLICT",
|
||||||
|
details: dict[str, Any] | None = None,
|
||||||
|
):
|
||||||
|
super().__init__(
|
||||||
|
code=code,
|
||||||
|
message=message,
|
||||||
|
http_status=409,
|
||||||
|
details=details or {},
|
||||||
|
retryable=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ServiceUnavailableError(AppError):
|
||||||
|
def __init__(self, message: str = "Service unavailable", *, code: str = "SYSTEM.SERVICE_UNAVAILABLE"):
|
||||||
|
super().__init__(code=code, message=message, http_status=503, retryable=True)
|
||||||
|
|
||||||
|
|
||||||
|
def raise_for_status(message: str, status: int, *, code: str | None = None, details: dict[str, Any] | None = None) -> None:
|
||||||
|
if status == 401:
|
||||||
|
raise UnauthorizedError(message)
|
||||||
|
if status == 403:
|
||||||
|
raise ForbiddenError(message)
|
||||||
|
if status == 404:
|
||||||
|
raise NotFoundError(message)
|
||||||
|
if status == 409:
|
||||||
|
raise ConflictError(message, code=code or "RESOURCE.CONFLICT", details=details)
|
||||||
|
if status == 503:
|
||||||
|
raise ServiceUnavailableError(message, code=code or "SYSTEM.SERVICE_UNAVAILABLE")
|
||||||
|
if status >= 500:
|
||||||
|
raise AppError(
|
||||||
|
code=code or "SYSTEM.INTERNAL_ERROR",
|
||||||
|
message=message,
|
||||||
|
http_status=status,
|
||||||
|
details=details or {},
|
||||||
|
)
|
||||||
|
raise AppError(
|
||||||
|
code=code or "VALIDATION.INVALID_PARAM",
|
||||||
|
message=message,
|
||||||
|
http_status=status,
|
||||||
|
details=details or {},
|
||||||
|
)
|
||||||
@@ -178,6 +178,27 @@ class Agent(Base):
|
|||||||
back_populates="agents"
|
back_populates="agents"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
class ChatSession(Base):
|
||||||
|
"""
|
||||||
|
聊天会话表
|
||||||
|
用途:独立持久化会话元数据,使生成中会话也能立即出现在历史记录中
|
||||||
|
"""
|
||||||
|
__tablename__ = 'chat_sessions'
|
||||||
|
__table_args__ = (
|
||||||
|
Index('ix_chat_sessions_user_agent_last_active', 'user_id', 'agent_id', 'last_active_at'),
|
||||||
|
)
|
||||||
|
|
||||||
|
id: Mapped[int] = mapped_column(primary_key=True)
|
||||||
|
session_id: Mapped[str] = mapped_column(String(100), unique=True, index=True)
|
||||||
|
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True)
|
||||||
|
agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True)
|
||||||
|
title: Mapped[str] = mapped_column(String(255), default='')
|
||||||
|
status: Mapped[str] = mapped_column(String(20), default='running')
|
||||||
|
external_conversation_id: Mapped[Optional[str]] = mapped_column(String(100), index=True, nullable=True)
|
||||||
|
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||||
|
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||||
|
last_active_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||||
|
|
||||||
class ChatLog(Base):
|
class ChatLog(Base):
|
||||||
"""
|
"""
|
||||||
对话日志表
|
对话日志表
|
||||||
@@ -192,6 +213,7 @@ class ChatLog(Base):
|
|||||||
answer: Mapped[str] = mapped_column(Text)
|
answer: Mapped[str] = mapped_column(Text)
|
||||||
latency: Mapped[int] = mapped_column(default=0)
|
latency: Mapped[int] = mapped_column(default=0)
|
||||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100))
|
conversation_id: Mapped[Optional[str]] = mapped_column(String(100))
|
||||||
|
session_id: Mapped[Optional[str]] = mapped_column(String(100), index=True, nullable=True)
|
||||||
message_type: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
message_type: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
|
||||||
payload: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
payload: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||||
tokens_used: Mapped[int] = mapped_column(default=0)
|
tokens_used: Mapped[int] = mapped_column(default=0)
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
"""
|
||||||
|
backend/app/response_utils.py
|
||||||
|
用途:提供统一响应结构的工具函数(成功与失败)。
|
||||||
|
说明:
|
||||||
|
1. ok:构造 success=true 的响应体,数据统一放在 data 字段。
|
||||||
|
2. error_payload:构造 success=false 的响应体,包含错误码、文案和可选详情。
|
||||||
|
3. utc_iso_now:统一生成 UTC 时间戳,便于前后端与日志对齐。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from flask import jsonify
|
||||||
|
|
||||||
|
|
||||||
|
def utc_iso_now() -> str:
|
||||||
|
return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
|
||||||
|
|
||||||
|
|
||||||
|
def ok(data: Any, *, request_id: str | None = None, status: int = 200):
|
||||||
|
payload: dict[str, Any] = {
|
||||||
|
"success": True,
|
||||||
|
"data": data,
|
||||||
|
"timestamp": utc_iso_now(),
|
||||||
|
}
|
||||||
|
if request_id:
|
||||||
|
payload["request_id"] = request_id
|
||||||
|
return jsonify(payload), status
|
||||||
|
|
||||||
|
|
||||||
|
def error_payload(
|
||||||
|
*,
|
||||||
|
code: str,
|
||||||
|
message: str,
|
||||||
|
request_id: str | None = None,
|
||||||
|
details: dict[str, Any] | None = None,
|
||||||
|
retryable: bool = False,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
payload: dict[str, Any] = {
|
||||||
|
"success": False,
|
||||||
|
"error": {
|
||||||
|
"code": code,
|
||||||
|
"message": message,
|
||||||
|
"details": details or {},
|
||||||
|
"retryable": retryable,
|
||||||
|
},
|
||||||
|
"timestamp": utc_iso_now(),
|
||||||
|
}
|
||||||
|
if request_id:
|
||||||
|
payload["request_id"] = request_id
|
||||||
|
return payload
|
||||||
@@ -26,6 +26,8 @@ import json
|
|||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from threading import Lock
|
||||||
from typing import Any, List, Optional
|
from typing import Any, List, Optional
|
||||||
|
|
||||||
import requests
|
import requests
|
||||||
@@ -39,6 +41,119 @@ from app.services.integration_api import IntegrationApiService
|
|||||||
class DifyService:
|
class DifyService:
|
||||||
"""Dify service wrapper."""
|
"""Dify service wrapper."""
|
||||||
VERBOSE_STREAM_LOG = str(os.getenv("CHAT_STREAM_VERBOSE", "0")).strip().lower() in ("1", "true", "yes", "on")
|
VERBOSE_STREAM_LOG = str(os.getenv("CHAT_STREAM_VERBOSE", "0")).strip().lower() in ("1", "true", "yes", "on")
|
||||||
|
SUPPORTED_FILE_EXTS: dict[str, set[str]] = {
|
||||||
|
"document": {
|
||||||
|
"txt",
|
||||||
|
"md",
|
||||||
|
"markdown",
|
||||||
|
"mdx",
|
||||||
|
"pdf",
|
||||||
|
"html",
|
||||||
|
"htm",
|
||||||
|
"xlsx",
|
||||||
|
"xls",
|
||||||
|
"vtt",
|
||||||
|
"properties",
|
||||||
|
"doc",
|
||||||
|
"docx",
|
||||||
|
"csv",
|
||||||
|
"eml",
|
||||||
|
"msg",
|
||||||
|
"pptx",
|
||||||
|
"ppt",
|
||||||
|
"xml",
|
||||||
|
"epub",
|
||||||
|
},
|
||||||
|
"image": {"jpg", "jpeg", "png", "gif", "webp", "svg"},
|
||||||
|
"audio": {"mp3", "m4a", "wav", "webm", "mpga"},
|
||||||
|
"video": {"mp4", "mov", "mpeg", "webm"},
|
||||||
|
}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _normalize_parameters_payload(data: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
return None
|
||||||
|
file_upload = data.get("file_upload")
|
||||||
|
if not isinstance(file_upload, dict):
|
||||||
|
return data
|
||||||
|
|
||||||
|
allowed_types = file_upload.get("allowed_file_types") or []
|
||||||
|
allowed_types_set = set(
|
||||||
|
str(v or "").strip().lower()
|
||||||
|
for v in (allowed_types if isinstance(allowed_types, list) else [])
|
||||||
|
if str(v or "").strip()
|
||||||
|
)
|
||||||
|
allowed_exts = file_upload.get("allowed_file_extensions") or []
|
||||||
|
normalized_exts = []
|
||||||
|
for v in (allowed_exts if isinstance(allowed_exts, list) else []):
|
||||||
|
s = str(v or "").strip()
|
||||||
|
if not s:
|
||||||
|
continue
|
||||||
|
if s.startswith("."):
|
||||||
|
s = s[1:]
|
||||||
|
s = s.strip()
|
||||||
|
if not s:
|
||||||
|
continue
|
||||||
|
normalized_exts.append(s.lower())
|
||||||
|
normalized_exts_set = set(normalized_exts)
|
||||||
|
|
||||||
|
has_doc_ext = any(DifyService.detect_file_type(f"file.{e}", None)[0] == "document" for e in normalized_exts_set)
|
||||||
|
doc_cfg = file_upload.get("document") if isinstance(file_upload, dict) else None
|
||||||
|
doc_enabled = None
|
||||||
|
if isinstance(doc_cfg, dict) and isinstance(doc_cfg.get("enabled"), bool):
|
||||||
|
doc_enabled = bool(doc_cfg.get("enabled"))
|
||||||
|
|
||||||
|
if "document" in allowed_types_set and doc_enabled is not False and not has_doc_ext:
|
||||||
|
add_exts = sorted(DifyService.SUPPORTED_FILE_EXTS.get("document") or [])
|
||||||
|
use_upper = any(str(v or "").strip().startswith(".") and str(v or "").strip().upper() == str(v or "").strip() for v in allowed_exts)
|
||||||
|
expanded = list(allowed_exts) if isinstance(allowed_exts, list) else []
|
||||||
|
for e in add_exts:
|
||||||
|
if e in normalized_exts_set:
|
||||||
|
continue
|
||||||
|
expanded.append(f".{e.upper()}" if use_upper else f".{e}")
|
||||||
|
normalized_exts_set.add(e)
|
||||||
|
file_upload = dict(file_upload)
|
||||||
|
file_upload["allowed_file_extensions"] = expanded
|
||||||
|
data = dict(data)
|
||||||
|
data["file_upload"] = file_upload
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def is_known_file_extension(ext: str | None) -> bool:
|
||||||
|
value = str(ext or "").strip().lower()
|
||||||
|
if not value:
|
||||||
|
return False
|
||||||
|
return any(value in s for s in DifyService.SUPPORTED_FILE_EXTS.values())
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def detect_file_type(filename: str | None, mimetype: str | None) -> tuple[str | None, str]:
|
||||||
|
name = str(filename or "").strip()
|
||||||
|
mime = str(mimetype or "").strip().lower()
|
||||||
|
ext = ""
|
||||||
|
if "." in name:
|
||||||
|
ext = name.rsplit(".", 1)[-1].lower().strip()
|
||||||
|
|
||||||
|
if mime.startswith("image/"):
|
||||||
|
return "image", ext
|
||||||
|
if mime.startswith("audio/"):
|
||||||
|
return "audio", ext
|
||||||
|
if mime.startswith("video/"):
|
||||||
|
return "video", ext
|
||||||
|
|
||||||
|
if ext in DifyService.SUPPORTED_FILE_EXTS["image"]:
|
||||||
|
return "image", ext
|
||||||
|
if ext in DifyService.SUPPORTED_FILE_EXTS["document"]:
|
||||||
|
return "document", ext
|
||||||
|
|
||||||
|
in_audio = ext in DifyService.SUPPORTED_FILE_EXTS["audio"]
|
||||||
|
in_video = ext in DifyService.SUPPORTED_FILE_EXTS["video"]
|
||||||
|
if in_audio and not in_video:
|
||||||
|
return "audio", ext
|
||||||
|
if in_video:
|
||||||
|
return "video", ext
|
||||||
|
|
||||||
|
return None, ext
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _normalize_dify_conversation_id(conversation_id: str | None) -> str:
|
def _normalize_dify_conversation_id(conversation_id: str | None) -> str:
|
||||||
@@ -114,6 +229,83 @@ class DifyService:
|
|||||||
return f"{base}/workflows/run"
|
return f"{base}/workflows/run"
|
||||||
return f"{base}/v1/workflows/run"
|
return f"{base}/v1/workflows/run"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _build_parameters_url(base_url: str) -> str:
|
||||||
|
base = str(base_url or "").strip().rstrip("/")
|
||||||
|
if not base:
|
||||||
|
return "/v1/parameters"
|
||||||
|
if base.endswith("/v1/parameters"):
|
||||||
|
base = base[: -len("/v1/parameters")].rstrip("/")
|
||||||
|
elif base.endswith("/parameters"):
|
||||||
|
base = base[: -len("/parameters")].rstrip("/")
|
||||||
|
if base.endswith("/v1"):
|
||||||
|
return f"{base}/parameters"
|
||||||
|
return f"{base}/v1/parameters"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _build_files_upload_url(base_url: str) -> str:
|
||||||
|
base = str(base_url or "").strip().rstrip("/")
|
||||||
|
if not base:
|
||||||
|
return "/v1/files/upload"
|
||||||
|
if base.endswith("/v1/files/upload"):
|
||||||
|
base = base[: -len("/v1/files/upload")].rstrip("/")
|
||||||
|
elif base.endswith("/files/upload"):
|
||||||
|
base = base[: -len("/files/upload")].rstrip("/")
|
||||||
|
if base.endswith("/v1"):
|
||||||
|
return f"{base}/files/upload"
|
||||||
|
return f"{base}/v1/files/upload"
|
||||||
|
|
||||||
|
_PARAMETERS_CACHE: dict[str, dict[str, Any]] = {}
|
||||||
|
_PARAMETERS_CACHE_LOCK = Lock()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_app_parameters(agent, *, ttl_seconds: int = 300, timeout: int = 8, force_refresh: bool = False) -> dict[str, Any] | None:
|
||||||
|
agent_id = str(getattr(agent, "id", "") or "")
|
||||||
|
api_key = str(getattr(agent, "dify_api_key", "") or "").strip()
|
||||||
|
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
|
||||||
|
url = DifyService._build_parameters_url(base_url)
|
||||||
|
cache_key = f"{agent_id}:{url}"
|
||||||
|
now = datetime.utcnow()
|
||||||
|
stale_data: dict[str, Any] | None = None
|
||||||
|
|
||||||
|
with DifyService._PARAMETERS_CACHE_LOCK:
|
||||||
|
cached = DifyService._PARAMETERS_CACHE.get(cache_key)
|
||||||
|
if cached and isinstance(cached.get("data"), dict):
|
||||||
|
stale_data = cached.get("data")
|
||||||
|
if (not force_refresh) and cached and isinstance(cached.get("_expires_at"), datetime) and cached["_expires_at"] > now:
|
||||||
|
return cached.get("data")
|
||||||
|
|
||||||
|
if not api_key:
|
||||||
|
return stale_data
|
||||||
|
|
||||||
|
headers = {"Authorization": f"Bearer {api_key}"}
|
||||||
|
try:
|
||||||
|
resp = requests.get(url, headers=headers, timeout=timeout)
|
||||||
|
if not resp.ok:
|
||||||
|
if current_app:
|
||||||
|
current_app.logger.warning(
|
||||||
|
"[dify] get parameters failed agent_id=%s status=%s url=%s body=%s",
|
||||||
|
agent_id,
|
||||||
|
resp.status_code,
|
||||||
|
url,
|
||||||
|
(resp.text or "")[:500],
|
||||||
|
)
|
||||||
|
return DifyService._normalize_parameters_payload(stale_data) or stale_data
|
||||||
|
data = resp.json() if resp.content else {}
|
||||||
|
except Exception as exc:
|
||||||
|
if current_app:
|
||||||
|
current_app.logger.warning("[dify] get parameters exception agent_id=%s url=%s err=%s", agent_id, url, exc)
|
||||||
|
return DifyService._normalize_parameters_payload(stale_data) or stale_data
|
||||||
|
|
||||||
|
data = DifyService._normalize_parameters_payload(data) or data
|
||||||
|
|
||||||
|
with DifyService._PARAMETERS_CACHE_LOCK:
|
||||||
|
DifyService._PARAMETERS_CACHE[cache_key] = {
|
||||||
|
"_expires_at": now + timedelta(seconds=ttl_seconds),
|
||||||
|
"data": data,
|
||||||
|
}
|
||||||
|
return data
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def run_workflow_streaming(
|
def run_workflow_streaming(
|
||||||
*,
|
*,
|
||||||
@@ -292,7 +484,15 @@ class DifyService:
|
|||||||
return {}
|
return {}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None, request_id: str | None = None):
|
def stream_chat(
|
||||||
|
query: str,
|
||||||
|
user_id: int,
|
||||||
|
agent,
|
||||||
|
conversation_id: str = None,
|
||||||
|
request_id: str | None = None,
|
||||||
|
session_id: str | None = None,
|
||||||
|
files: list[dict[str, Any]] | None = None,
|
||||||
|
):
|
||||||
"""
|
"""
|
||||||
主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
|
主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
|
||||||
Stream chat completion from Dify and relay SSE events to caller.
|
Stream chat completion from Dify and relay SSE events to caller.
|
||||||
@@ -328,6 +528,8 @@ class DifyService:
|
|||||||
'conversation_id': normalized_conversation_id,
|
'conversation_id': normalized_conversation_id,
|
||||||
'user': str(user_id),
|
'user': str(user_id),
|
||||||
}
|
}
|
||||||
|
if files:
|
||||||
|
payload['files'] = files
|
||||||
|
|
||||||
if current_app:
|
if current_app:
|
||||||
current_app.logger.info(
|
current_app.logger.info(
|
||||||
@@ -450,6 +652,7 @@ class DifyService:
|
|||||||
chat_log_id = DifyService._log_chat(
|
chat_log_id = DifyService._log_chat(
|
||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
agent_id=agent.id,
|
agent_id=agent.id,
|
||||||
|
session_id=session_id,
|
||||||
conversation_id=data.get('conversation_id') or normalized_conversation_id,
|
conversation_id=data.get('conversation_id') or normalized_conversation_id,
|
||||||
query=query,
|
query=query,
|
||||||
answer=''.join(full_answer),
|
answer=''.join(full_answer),
|
||||||
@@ -494,6 +697,7 @@ class DifyService:
|
|||||||
def _log_chat(
|
def _log_chat(
|
||||||
user_id,
|
user_id,
|
||||||
agent_id,
|
agent_id,
|
||||||
|
session_id,
|
||||||
conversation_id,
|
conversation_id,
|
||||||
query,
|
query,
|
||||||
answer,
|
answer,
|
||||||
@@ -520,6 +724,7 @@ class DifyService:
|
|||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
agent_id=agent_id,
|
agent_id=agent_id,
|
||||||
conversation_id=conversation_id,
|
conversation_id=conversation_id,
|
||||||
|
session_id=session_id,
|
||||||
query=query,
|
query=query,
|
||||||
answer=answer,
|
answer=answer,
|
||||||
tokens_used=tokens or 0,
|
tokens_used=tokens or 0,
|
||||||
|
|||||||
@@ -263,7 +263,7 @@ WHERE c002001 = ?
|
|||||||
return "\n".join(sections)
|
return "\n".join(sections)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def stream_chat(cls, query: str, user, agent, conversation_id: str = None):
|
def stream_chat(cls, query: str, user, agent, conversation_id: str = None, session_id: str | None = None):
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
final_conversation_id = conversation_id or f"hr_{int(time.time())}"
|
final_conversation_id = conversation_id or f"hr_{int(time.time())}"
|
||||||
try:
|
try:
|
||||||
@@ -319,6 +319,7 @@ WHERE c002001 = ?
|
|||||||
user_id=user.id,
|
user_id=user.id,
|
||||||
agent_id=agent.id,
|
agent_id=agent.id,
|
||||||
conversation_id=final_conversation_id,
|
conversation_id=final_conversation_id,
|
||||||
|
session_id=session_id,
|
||||||
query=query,
|
query=query,
|
||||||
answer=result_text,
|
answer=result_text,
|
||||||
tokens_used=0,
|
tokens_used=0,
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
Integration API client for resolving original source-file download links.
|
Integration API client for resolving original source-file download links.
|
||||||
"""
|
"""
|
||||||
from datetime import datetime
|
from datetime import datetime, timedelta, timezone
|
||||||
from typing import Any, Dict, List, Optional, Tuple
|
from typing import Any, Dict, List, Optional, Tuple
|
||||||
from urllib.parse import urlparse
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
@@ -14,6 +14,88 @@ from app.config import Config
|
|||||||
class IntegrationApiService:
|
class IntegrationApiService:
|
||||||
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _lookup_from_dify_document_api(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||||
|
"""
|
||||||
|
当集成映射服务缺失时,直接调用 Dify 数据集文档下载接口兜底。
|
||||||
|
适用于“检索已返回 document_id,但 8891 没有同步 source file mapping”的场景。
|
||||||
|
"""
|
||||||
|
if not dataset_id or not remote_document_id:
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
service = KbDifySyncService()
|
||||||
|
if not service.base_url or not service.api_key:
|
||||||
|
return None
|
||||||
|
|
||||||
|
document_payload = service.get_document(
|
||||||
|
dataset_id=str(dataset_id),
|
||||||
|
document_id=str(remote_document_id),
|
||||||
|
)
|
||||||
|
if not isinstance(document_payload, dict):
|
||||||
|
return None
|
||||||
|
|
||||||
|
download_resp = requests.get(
|
||||||
|
f"{service.base_url.rstrip('/')}/datasets/{dataset_id}/documents/{remote_document_id}/download",
|
||||||
|
headers=service._headers(),
|
||||||
|
timeout=(5, 15),
|
||||||
|
)
|
||||||
|
if download_resp.status_code != 200:
|
||||||
|
if has_app_context():
|
||||||
|
current_app.logger.info(
|
||||||
|
"Dify document download lookup missed: dataset_id=%s remote_document_id=%s status=%s",
|
||||||
|
dataset_id,
|
||||||
|
remote_document_id,
|
||||||
|
download_resp.status_code,
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
|
||||||
|
download_payload = download_resp.json() if download_resp.content else {}
|
||||||
|
source_url = str((download_payload or {}).get("url") or "").strip()
|
||||||
|
if not source_url:
|
||||||
|
return None
|
||||||
|
|
||||||
|
upload_info = (
|
||||||
|
((document_payload.get("data_source_info") or {}).get("upload_file"))
|
||||||
|
if isinstance(document_payload.get("data_source_info"), dict)
|
||||||
|
else {}
|
||||||
|
) or {}
|
||||||
|
source_filename = str(
|
||||||
|
upload_info.get("name")
|
||||||
|
or document_payload.get("name")
|
||||||
|
or ""
|
||||||
|
).strip() or None
|
||||||
|
source_ext = str(
|
||||||
|
upload_info.get("extension")
|
||||||
|
or (source_filename.rsplit(".", 1)[-1] if source_filename and "." in source_filename else "")
|
||||||
|
).strip().lower() or None
|
||||||
|
|
||||||
|
# Dify 返回的签名下载地址通常是短效的,这里主动给缓存一个较短 TTL,避免长期复用旧链接。
|
||||||
|
expires_at = (datetime.now(timezone.utc) + timedelta(minutes=10)).isoformat()
|
||||||
|
|
||||||
|
return {
|
||||||
|
"source_download_url": source_url,
|
||||||
|
"source_filename": source_filename,
|
||||||
|
"source_ext": source_ext,
|
||||||
|
"download_url_expires_at": expires_at,
|
||||||
|
"version_id": None,
|
||||||
|
"document_id": remote_document_id,
|
||||||
|
}
|
||||||
|
except Exception as e:
|
||||||
|
if has_app_context():
|
||||||
|
current_app.logger.warning(
|
||||||
|
"Dify document API fallback lookup failed: dataset_id=%s remote_document_id=%s err=%s",
|
||||||
|
dataset_id,
|
||||||
|
remote_document_id,
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]:
|
def _normalize_batch_row(row: Dict[str, Any]) -> Optional[Tuple[Tuple[str, str], Dict[str, Any]]]:
|
||||||
if not isinstance(row, dict):
|
if not isinstance(row, dict):
|
||||||
@@ -114,6 +196,63 @@ class IntegrationApiService:
|
|||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _lookup_local_db(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||||
|
if not has_app_context():
|
||||||
|
return None
|
||||||
|
from app import db
|
||||||
|
from app.models import KbDifySyncRecord, KbDocumentVersion, KbDocument
|
||||||
|
|
||||||
|
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,
|
||||||
|
)
|
||||||
|
.order_by(KbDifySyncRecord.updated_at.desc(), KbDifySyncRecord.id.desc())
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if not record or not record.document_version or not record.document_version.document:
|
||||||
|
return None
|
||||||
|
|
||||||
|
version = record.document_version
|
||||||
|
document = version.document
|
||||||
|
|
||||||
|
explicit = str(current_app.config.get('WECOM_PUBLIC_BASE_URL') or '').strip().rstrip('/')
|
||||||
|
if explicit:
|
||||||
|
base_url = explicit
|
||||||
|
elif has_request_context():
|
||||||
|
base_url = request.host_url.rstrip('/')
|
||||||
|
else:
|
||||||
|
base_url = ''
|
||||||
|
|
||||||
|
import time
|
||||||
|
import jwt
|
||||||
|
|
||||||
|
secret = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||||||
|
if not secret:
|
||||||
|
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,
|
||||||
|
'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}'
|
||||||
|
|
||||||
|
return {
|
||||||
|
"source_download_url": source_download_url,
|
||||||
|
"source_filename": version.source_file_name,
|
||||||
|
"source_ext": version.source_file_ext,
|
||||||
|
"download_url_expires_at": None,
|
||||||
|
"version_id": version.id,
|
||||||
|
"document_id": document.id,
|
||||||
|
}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def lookup_file_by_dify(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
def lookup_file_by_dify(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||||
if not dataset_id or not remote_document_id:
|
if not dataset_id or not remote_document_id:
|
||||||
@@ -169,25 +308,35 @@ class IntegrationApiService:
|
|||||||
}
|
}
|
||||||
try:
|
try:
|
||||||
resp = requests.post(batch_url, headers=batch_headers, json=batch_body, timeout=(5, 12))
|
resp = requests.post(batch_url, headers=batch_headers, json=batch_body, timeout=(5, 12))
|
||||||
if resp.status_code != 200:
|
if resp.status_code == 200:
|
||||||
return None
|
payload = resp.json()
|
||||||
payload = resp.json()
|
data = payload.get("data") if isinstance(payload, dict) else None
|
||||||
data = payload.get("data") if isinstance(payload, dict) else None
|
if isinstance(data, list):
|
||||||
if not isinstance(data, list):
|
for row in data:
|
||||||
return None
|
normalized_row = IntegrationApiService._normalize_batch_row(row)
|
||||||
for row in data:
|
if not normalized_row:
|
||||||
normalized_row = IntegrationApiService._normalize_batch_row(row)
|
continue
|
||||||
if not normalized_row:
|
key, normalized = normalized_row
|
||||||
continue
|
IntegrationApiService._cache[key] = normalized
|
||||||
key, normalized = normalized_row
|
if key == cache_key:
|
||||||
IntegrationApiService._cache[key] = normalized
|
return normalized
|
||||||
if key == cache_key:
|
|
||||||
return normalized
|
|
||||||
return None
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if has_app_context():
|
if has_app_context():
|
||||||
current_app.logger.warning(f"Integration API batch fallback lookup failed: {e}")
|
current_app.logger.warning(f"Integration API batch fallback lookup failed: {e}")
|
||||||
return None
|
|
||||||
|
# Fallback to local database if remote integration API fails or misses
|
||||||
|
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
|
||||||
|
if local_result:
|
||||||
|
IntegrationApiService._cache[cache_key] = local_result
|
||||||
|
return local_result
|
||||||
|
|
||||||
|
# Last fallback: query Dify document API directly and request a signed download URL.
|
||||||
|
dify_result = IntegrationApiService._lookup_from_dify_document_api(dataset_id, remote_document_id)
|
||||||
|
if dify_result:
|
||||||
|
IntegrationApiService._cache[cache_key] = dify_result
|
||||||
|
return dify_result
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def lookup_files_by_dify(items: List[Dict[str, str]]) -> Dict[Tuple[str, str], Dict[str, Any]]:
|
def lookup_files_by_dify(items: List[Dict[str, str]]) -> Dict[Tuple[str, str], Dict[str, Any]]:
|
||||||
@@ -243,45 +392,42 @@ class IntegrationApiService:
|
|||||||
current_app.logger.warning(
|
current_app.logger.warning(
|
||||||
"Integration API batch lookup failed: status=%s", resp.status_code
|
"Integration API batch lookup failed: status=%s", resp.status_code
|
||||||
)
|
)
|
||||||
# Fallback to single lookup for reliability.
|
else:
|
||||||
for item in unresolved:
|
payload = resp.json()
|
||||||
payload = IntegrationApiService.lookup_file_by_dify(
|
data = payload.get("data") if isinstance(payload, dict) else None
|
||||||
item["dataset_id"], item["remote_document_id"]
|
if isinstance(data, list):
|
||||||
)
|
for row in data:
|
||||||
if payload:
|
if not isinstance(row, dict):
|
||||||
key = IntegrationApiService._cache_key(
|
continue
|
||||||
item["dataset_id"], item["remote_document_id"]
|
normalized_row = IntegrationApiService._normalize_batch_row(row)
|
||||||
)
|
if not normalized_row:
|
||||||
results[key] = payload
|
continue
|
||||||
return results
|
key, normalized = normalized_row
|
||||||
|
IntegrationApiService._cache[key] = normalized
|
||||||
payload = resp.json()
|
results[key] = normalized
|
||||||
data = payload.get("data") if isinstance(payload, dict) else None
|
|
||||||
if not isinstance(data, list):
|
|
||||||
return results
|
|
||||||
|
|
||||||
for row in data:
|
|
||||||
if not isinstance(row, dict):
|
|
||||||
continue
|
|
||||||
normalized_row = IntegrationApiService._normalize_batch_row(row)
|
|
||||||
if not normalized_row:
|
|
||||||
continue
|
|
||||||
key, normalized = normalized_row
|
|
||||||
IntegrationApiService._cache[key] = normalized
|
|
||||||
results[key] = normalized
|
|
||||||
|
|
||||||
return results
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if has_app_context():
|
if has_app_context():
|
||||||
current_app.logger.warning(f"Integration API batch lookup exception: {e}")
|
current_app.logger.warning(f"Integration API batch lookup exception: {e}")
|
||||||
# Fallback to single lookup when batch call errors.
|
|
||||||
for item in unresolved:
|
# Fallback to single lookup or local DB for unresolved items
|
||||||
payload = IntegrationApiService.lookup_file_by_dify(
|
for item in unresolved:
|
||||||
item["dataset_id"], item["remote_document_id"]
|
dataset_id = item["dataset_id"]
|
||||||
)
|
remote_document_id = item["remote_document_id"]
|
||||||
if payload:
|
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||||
key = IntegrationApiService._cache_key(
|
if key in results:
|
||||||
item["dataset_id"], item["remote_document_id"]
|
continue
|
||||||
)
|
|
||||||
results[key] = payload
|
# Check if single lookup was not called already (if it was, it might be cached)
|
||||||
return results
|
# Actually, `_lookup_local_db` should be checked directly since remote batch failed to find it.
|
||||||
|
local_result = IntegrationApiService._lookup_local_db(dataset_id, remote_document_id)
|
||||||
|
if local_result:
|
||||||
|
IntegrationApiService._cache[key] = local_result
|
||||||
|
results[key] = local_result
|
||||||
|
continue
|
||||||
|
|
||||||
|
# As a last resort, try remote single lookup if batch missed it
|
||||||
|
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
|
||||||
|
if payload:
|
||||||
|
results[key] = payload
|
||||||
|
|
||||||
|
return results
|
||||||
@@ -319,7 +319,7 @@ select *
|
|||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def stream_chat(cls, query: str, user, agent, conversation_id: str | None = None):
|
def stream_chat(cls, query: str, user, agent, conversation_id: str | None = None, session_id: str | None = None):
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
final_conversation_id = conversation_id or f"plm_{int(time.time())}"
|
final_conversation_id = conversation_id or f"plm_{int(time.time())}"
|
||||||
material_no = cls.extract_material_no(query)
|
material_no = cls.extract_material_no(query)
|
||||||
@@ -340,6 +340,7 @@ select *
|
|||||||
user_id=user.id,
|
user_id=user.id,
|
||||||
agent_id=agent.id,
|
agent_id=agent.id,
|
||||||
conversation_id=final_conversation_id,
|
conversation_id=final_conversation_id,
|
||||||
|
session_id=session_id,
|
||||||
query=query,
|
query=query,
|
||||||
answer=answer,
|
answer=answer,
|
||||||
tokens_used=0,
|
tokens_used=0,
|
||||||
|
|||||||
@@ -379,6 +379,7 @@ class Text2SQLService:
|
|||||||
- 严禁生成任何 INSERT、UPDATE、DELETE、MERGE、ALTER、DROP、TRUNCATE、CREATE 语句。
|
- 严禁生成任何 INSERT、UPDATE、DELETE、MERGE、ALTER、DROP、TRUNCATE、CREATE 语句。
|
||||||
- 仅允许输出单条 SELECT 或 WITH 开头的查询。
|
- 仅允许输出单条 SELECT 或 WITH 开头的查询。
|
||||||
- 必须使用 Schema 中出现的精确表名,包含完整前缀,如 ERP_VIEW_USER.ERP_FAJ_FILE_V。
|
- 必须使用 Schema 中出现的精确表名,包含完整前缀,如 ERP_VIEW_USER.ERP_FAJ_FILE_V。
|
||||||
|
- 如果用户查询的是列表明细而非聚合总数(如“列出...”、“有哪些...”),你必须强制在 SQL 结尾添加 FETCH FIRST 50 ROWS ONLY,避免一次性返回几十万条数据导致系统崩溃。
|
||||||
- 必须只使用 Schema 中明确出现过的字段名,禁止臆造通用字段名,例如 FILE_TYPE、STATUS_NAME、AMOUNT 等。
|
- 必须只使用 Schema 中明确出现过的字段名,禁止臆造通用字段名,例如 FILE_TYPE、STATUS_NAME、AMOUNT 等。
|
||||||
- 优先选择最相关字段,避免 SELECT *。
|
- 优先选择最相关字段,避免 SELECT *。
|
||||||
- 当问题涉及“多少、总额、平均值、数量、占比、排名”时,请使用清晰的聚合逻辑与英文别名。
|
- 当问题涉及“多少、总额、平均值、数量、占比、排名”时,请使用清晰的聚合逻辑与英文别名。
|
||||||
@@ -494,13 +495,13 @@ class Text2SQLService:
|
|||||||
return f"{summary_text}\n\n**查询结果如下:**\n\n{table_str}\n\n{sql_details}"
|
return f"{summary_text}\n\n**查询结果如下:**\n\n{table_str}\n\n{sql_details}"
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
|
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None, session_id: str | None = None):
|
||||||
"""Yields SSE events to frontend just like DifyService"""
|
"""Yields SSE events to frontend just like DifyService"""
|
||||||
start_time = time.time()
|
start_time = time.time()
|
||||||
final_conversation_id = conversation_id or f"erp_{int(time.time())}"
|
final_conversation_id = conversation_id or f"erp_{int(time.time())}"
|
||||||
try:
|
try:
|
||||||
# 1. Generate SQL
|
# 1. Generate SQL
|
||||||
yield f"data: {json.dumps({'event': 'message', 'answer': '正在分析问题并生成 SQL...\n'})}\n\n"
|
yield f"data: {json.dumps({'event': 'message', 'answer': '🧠 正在理解您的问题并生成底层查询代码 (SQL)...\n'})}\n\n"
|
||||||
stage_start = time.time()
|
stage_start = time.time()
|
||||||
sql = Text2SQLService.generate_sql(query)
|
sql = Text2SQLService.generate_sql(query)
|
||||||
generate_sql_ms = int((time.time() - stage_start) * 1000)
|
generate_sql_ms = int((time.time() - stage_start) * 1000)
|
||||||
@@ -511,7 +512,7 @@ class Text2SQLService:
|
|||||||
generate_sql_ms,
|
generate_sql_ms,
|
||||||
(sql or "")[:300],
|
(sql or "")[:300],
|
||||||
)
|
)
|
||||||
yield f"data: {json.dumps({'event': 'message', 'answer': '已完成查询口径分析,正在查询数据库...\n'})}\n\n"
|
yield f"data: {json.dumps({'event': 'message', 'answer': '🔍 已完成查询口径分析,正在数据库中检索海量数据,请稍候...\n'})}\n\n"
|
||||||
|
|
||||||
# 2. Execute SQL
|
# 2. Execute SQL
|
||||||
stage_start = time.time()
|
stage_start = time.time()
|
||||||
@@ -554,7 +555,7 @@ class Text2SQLService:
|
|||||||
)
|
)
|
||||||
|
|
||||||
# 3. Format result
|
# 3. Format result
|
||||||
yield f"data: {json.dumps({'event': 'message', 'answer': '正在整理结果并生成业务汇总...\n'})}\n\n"
|
yield f"data: {json.dumps({'event': 'message', 'answer': '📝 数据检索完成,正在生成最终业务报告...\n'})}\n\n"
|
||||||
stage_start = time.time()
|
stage_start = time.time()
|
||||||
result_text = Text2SQLService.format_result(columns, rows, sql, query)
|
result_text = Text2SQLService.format_result(columns, rows, sql, query)
|
||||||
format_result_ms = int((time.time() - stage_start) * 1000)
|
format_result_ms = int((time.time() - stage_start) * 1000)
|
||||||
@@ -589,6 +590,7 @@ class Text2SQLService:
|
|||||||
user_id=user_id,
|
user_id=user_id,
|
||||||
agent_id=agent.id,
|
agent_id=agent.id,
|
||||||
conversation_id=final_conversation_id,
|
conversation_id=final_conversation_id,
|
||||||
|
session_id=session_id,
|
||||||
query=query,
|
query=query,
|
||||||
answer=result_text,
|
answer=result_text,
|
||||||
tokens_used=0,
|
tokens_used=0,
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
"""add chat_sessions table and session_id to chat_logs
|
||||||
|
|
||||||
|
Revision ID: c9d8e7f6a5b4
|
||||||
|
Revises: e3f4a5b6c7d8
|
||||||
|
Create Date: 2026-06-01 16:30:00.000000
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'c9d8e7f6a5b4'
|
||||||
|
down_revision = 'e3f4a5b6c7d8'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
op.create_table(
|
||||||
|
'chat_sessions',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('session_id', sa.String(length=100), nullable=False),
|
||||||
|
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('agent_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('title', sa.String(length=255), nullable=False, server_default=''),
|
||||||
|
sa.Column('status', sa.String(length=20), nullable=False, server_default='running'),
|
||||||
|
sa.Column('external_conversation_id', sa.String(length=100), nullable=True),
|
||||||
|
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||||
|
sa.Column('last_active_at', sa.DateTime(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['agent_id'], ['agents.id']),
|
||||||
|
sa.ForeignKeyConstraint(['user_id'], ['users.id']),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
)
|
||||||
|
op.create_index('ix_chat_sessions_session_id', 'chat_sessions', ['session_id'], unique=True)
|
||||||
|
op.create_index('ix_chat_sessions_user_id', 'chat_sessions', ['user_id'], unique=False)
|
||||||
|
op.create_index('ix_chat_sessions_agent_id', 'chat_sessions', ['agent_id'], unique=False)
|
||||||
|
op.create_index('ix_chat_sessions_external_conversation_id', 'chat_sessions', ['external_conversation_id'], unique=False)
|
||||||
|
op.create_index('ix_chat_sessions_created_at', 'chat_sessions', ['created_at'], unique=False)
|
||||||
|
op.create_index('ix_chat_sessions_last_active_at', 'chat_sessions', ['last_active_at'], unique=False)
|
||||||
|
op.create_index(
|
||||||
|
'ix_chat_sessions_user_agent_last_active',
|
||||||
|
'chat_sessions',
|
||||||
|
['user_id', 'agent_id', 'last_active_at'],
|
||||||
|
unique=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
op.add_column('chat_logs', sa.Column('session_id', sa.String(length=100), nullable=True))
|
||||||
|
op.create_index('ix_chat_logs_session_id', 'chat_logs', ['session_id'], unique=False)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
op.drop_index('ix_chat_logs_session_id', table_name='chat_logs')
|
||||||
|
op.drop_column('chat_logs', 'session_id')
|
||||||
|
|
||||||
|
op.drop_index('ix_chat_sessions_user_agent_last_active', table_name='chat_sessions')
|
||||||
|
op.drop_index('ix_chat_sessions_last_active_at', table_name='chat_sessions')
|
||||||
|
op.drop_index('ix_chat_sessions_created_at', table_name='chat_sessions')
|
||||||
|
op.drop_index('ix_chat_sessions_external_conversation_id', table_name='chat_sessions')
|
||||||
|
op.drop_index('ix_chat_sessions_agent_id', table_name='chat_sessions')
|
||||||
|
op.drop_index('ix_chat_sessions_user_id', table_name='chat_sessions')
|
||||||
|
op.drop_index('ix_chat_sessions_session_id', table_name='chat_sessions')
|
||||||
|
op.drop_table('chat_sessions')
|
||||||
@@ -0,0 +1,200 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Codemod: jsonify({'error': ...}) -> raise AppError subclasses."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ast
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1] / "app"
|
||||||
|
TARGETS = [ROOT / "decorators.py", *sorted((ROOT / "api").glob("*.py"))]
|
||||||
|
|
||||||
|
IMPORT_LINE = (
|
||||||
|
"from app.errors import AppError, ValidationError, UnauthorizedError, "
|
||||||
|
"ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status"
|
||||||
|
)
|
||||||
|
|
||||||
|
STATUS_TO_EXCEPTION = {
|
||||||
|
401: "UnauthorizedError",
|
||||||
|
403: "ForbiddenError",
|
||||||
|
404: "NotFoundError",
|
||||||
|
409: "ConflictError",
|
||||||
|
503: "ServiceUnavailableError",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_message(node: ast.AST) -> str | None:
|
||||||
|
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
||||||
|
return node.value
|
||||||
|
if isinstance(node, ast.JoinedStr):
|
||||||
|
parts = []
|
||||||
|
for value in node.values:
|
||||||
|
if isinstance(value, ast.Constant) and isinstance(value.value, str):
|
||||||
|
parts.append(value.value)
|
||||||
|
else:
|
||||||
|
return None
|
||||||
|
return "".join(parts)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _segment(source: str, node: ast.AST) -> str:
|
||||||
|
return ast.get_source_segment(source, node) or ""
|
||||||
|
|
||||||
|
|
||||||
|
def _build_raise(source: str, node: ast.Return, indent: str) -> str | None:
|
||||||
|
if not isinstance(node.value, ast.Tuple) or len(node.value.elts) != 2:
|
||||||
|
return None
|
||||||
|
call, status_node = node.value.elts
|
||||||
|
if not isinstance(call, ast.Call):
|
||||||
|
return None
|
||||||
|
func = call.func
|
||||||
|
if not (isinstance(func, ast.Name) and func.id == "jsonify"):
|
||||||
|
return None
|
||||||
|
if len(call.args) != 1 or call.keywords:
|
||||||
|
return None
|
||||||
|
payload = call.args[0]
|
||||||
|
if not isinstance(payload, ast.Dict):
|
||||||
|
return None
|
||||||
|
|
||||||
|
error_node = None
|
||||||
|
extras: list[tuple[str, ast.AST]] = []
|
||||||
|
for key, value in zip(payload.keys, payload.values):
|
||||||
|
if key is None or value is None:
|
||||||
|
return None
|
||||||
|
if isinstance(key, ast.Constant) and key.value == "error":
|
||||||
|
error_node = value
|
||||||
|
else:
|
||||||
|
key_name = key.value if isinstance(key, ast.Constant) else _segment(source, key)
|
||||||
|
extras.append((str(key_name), value))
|
||||||
|
|
||||||
|
if error_node is None:
|
||||||
|
return None
|
||||||
|
|
||||||
|
message = _extract_message(error_node)
|
||||||
|
message_expr = repr(message) if message is not None else _segment(source, error_node).strip()
|
||||||
|
|
||||||
|
if isinstance(status_node, ast.Constant) and isinstance(status_node.value, int):
|
||||||
|
status = status_node.value
|
||||||
|
status_expr = str(status)
|
||||||
|
else:
|
||||||
|
status = None
|
||||||
|
status_expr = _segment(source, status_node).strip()
|
||||||
|
|
||||||
|
if extras:
|
||||||
|
detail_items = [f"{key!r}: {_segment(source, value).strip()}" for key, value in extras]
|
||||||
|
details_expr = "{" + ", ".join(detail_items) + "}"
|
||||||
|
if status == 409:
|
||||||
|
return f"{indent}raise ConflictError({message_expr}, details={details_expr})"
|
||||||
|
if status is not None:
|
||||||
|
return (
|
||||||
|
f"{indent}raise AppError(code='SYSTEM.HTTP_ERROR', message={message_expr}, "
|
||||||
|
f"http_status={status}, details={details_expr})"
|
||||||
|
)
|
||||||
|
return (
|
||||||
|
f"{indent}raise AppError(code='SYSTEM.HTTP_ERROR', message={message_expr}, "
|
||||||
|
f"http_status={status_expr}, details={details_expr})"
|
||||||
|
)
|
||||||
|
|
||||||
|
if status is not None:
|
||||||
|
cls = STATUS_TO_EXCEPTION.get(status)
|
||||||
|
if cls:
|
||||||
|
return f"{indent}raise {cls}({message_expr})"
|
||||||
|
if status == 400:
|
||||||
|
return f"{indent}raise ValidationError({message_expr})"
|
||||||
|
if status >= 500:
|
||||||
|
return f"{indent}raise AppError(code='SYSTEM.INTERNAL_ERROR', message={message_expr}, http_status={status})"
|
||||||
|
return f"{indent}raise_for_status({message_expr}, {status})"
|
||||||
|
|
||||||
|
return f"{indent}raise_for_status({message_expr}, {status_expr})"
|
||||||
|
|
||||||
|
|
||||||
|
class ErrorMigrator(ast.NodeTransformer):
|
||||||
|
def __init__(self, source: str):
|
||||||
|
self.source = source
|
||||||
|
self.changed = 0
|
||||||
|
|
||||||
|
def visit_Return(self, node: ast.Return):
|
||||||
|
indent = " " * (node.col_offset or 0)
|
||||||
|
new = _build_raise(self.source, node, indent)
|
||||||
|
if not new:
|
||||||
|
return node
|
||||||
|
self.changed += 1
|
||||||
|
wrapped = f"def _migrate():\n{new}\n"
|
||||||
|
return ast.parse(wrapped).body[0].body[0]
|
||||||
|
|
||||||
|
|
||||||
|
def _fix_require_user(source: str) -> str:
|
||||||
|
old = (
|
||||||
|
"def _require_user():\n"
|
||||||
|
" user = get_current_user()\n"
|
||||||
|
" if not user:\n"
|
||||||
|
" return None, (jsonify({'error': 'Unauthorized'}), 401)\n"
|
||||||
|
" return user, None\n"
|
||||||
|
)
|
||||||
|
new = (
|
||||||
|
"def _require_user():\n"
|
||||||
|
" user = get_current_user()\n"
|
||||||
|
" if not user:\n"
|
||||||
|
" raise UnauthorizedError()\n"
|
||||||
|
" return user\n"
|
||||||
|
)
|
||||||
|
source = source.replace(old, new)
|
||||||
|
source = source.replace(
|
||||||
|
" user, err = _require_user()\n if err:\n return err\n",
|
||||||
|
" user = _require_user()\n",
|
||||||
|
)
|
||||||
|
source = source.replace(
|
||||||
|
" current_user, err = _require_user()\n if err:\n return err\n",
|
||||||
|
" current_user = _require_user()\n",
|
||||||
|
)
|
||||||
|
return source
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_import(source: str) -> str:
|
||||||
|
if IMPORT_LINE in source:
|
||||||
|
return source
|
||||||
|
lines = source.splitlines(keepends=True)
|
||||||
|
insert_at = 0
|
||||||
|
for i, line in enumerate(lines):
|
||||||
|
if line.startswith("from ") or line.startswith("import "):
|
||||||
|
insert_at = i + 1
|
||||||
|
lines.insert(insert_at, IMPORT_LINE + "\n")
|
||||||
|
return "".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
def migrate_file(path: Path) -> int:
|
||||||
|
source = path.read_text(encoding="utf-8")
|
||||||
|
try:
|
||||||
|
tree = ast.parse(source)
|
||||||
|
except SyntaxError as exc:
|
||||||
|
print(f"skip {path}: {exc}", file=sys.stderr)
|
||||||
|
return 0
|
||||||
|
|
||||||
|
migrator = ErrorMigrator(source)
|
||||||
|
new_tree = migrator.visit(tree)
|
||||||
|
ast.fix_missing_locations(new_tree)
|
||||||
|
if migrator.changed == 0:
|
||||||
|
return 0
|
||||||
|
|
||||||
|
new_source = ast.unparse(new_tree)
|
||||||
|
new_source = _fix_require_user(new_source)
|
||||||
|
new_source = _ensure_import(new_source)
|
||||||
|
path.write_text(new_source, encoding="utf-8")
|
||||||
|
return migrator.changed
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
total = 0
|
||||||
|
for path in TARGETS:
|
||||||
|
if not path.exists():
|
||||||
|
continue
|
||||||
|
count = migrate_file(path)
|
||||||
|
if count:
|
||||||
|
print(f"{path.name}: {count}")
|
||||||
|
total += count
|
||||||
|
print(f"done: {total}")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -60,7 +60,8 @@ def test_user_management(client, admin_headers):
|
|||||||
"role": "user",
|
"role": "user",
|
||||||
"password": "password123",
|
"password": "password123",
|
||||||
"real_name": "Test User",
|
"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)
|
response = client.post('/api/admin/users', json=new_user, headers=admin_headers)
|
||||||
assert response.status_code == 201
|
assert response.status_code == 201
|
||||||
|
|||||||
@@ -100,8 +100,12 @@ def test_login_success(client):
|
|||||||
def test_login_fail(client):
|
def test_login_fail(client):
|
||||||
res = client.post('/api/user/login', json={'username': 'test1', 'password': 'wrongpassword'})
|
res = client.post('/api/user/login', json={'username': 'test1', 'password': 'wrongpassword'})
|
||||||
assert res.status_code == 401
|
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'})
|
res = client.post('/api/user/login', json={'username': 'nonexistent', 'password': 'password'})
|
||||||
assert res.status_code == 404
|
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']
|
||||||
@@ -52,7 +52,8 @@ def test_admin_duplicate_employee_id(client, admin_headers):
|
|||||||
"password": "pwd",
|
"password": "pwd",
|
||||||
"email": "au1@e.com",
|
"email": "au1@e.com",
|
||||||
"real_name": "Admin User 1",
|
"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)
|
response = client.post('/api/admin/users', json=u1, headers=admin_headers)
|
||||||
assert response.status_code == 201
|
assert response.status_code == 201
|
||||||
@@ -63,7 +64,8 @@ def test_admin_duplicate_employee_id(client, admin_headers):
|
|||||||
"password": "pwd",
|
"password": "pwd",
|
||||||
"email": "au2@e.com",
|
"email": "au2@e.com",
|
||||||
"real_name": "Admin User 2",
|
"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)
|
response = client.post('/api/admin/users', json=u2, headers=admin_headers)
|
||||||
assert response.status_code == 400
|
assert response.status_code == 400
|
||||||
@@ -76,7 +78,8 @@ def test_admin_duplicate_employee_id(client, admin_headers):
|
|||||||
"password": "pwd",
|
"password": "pwd",
|
||||||
"email": "au3@e.com",
|
"email": "au3@e.com",
|
||||||
"real_name": "Admin User 3",
|
"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)
|
res = client.post('/api/admin/users', json=u3, headers=admin_headers)
|
||||||
u3_id = res.json['id']
|
u3_id = res.json['id']
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
import { getAuthHeaders } from '../utils/auth';
|
||||||
|
import { requestJson } from './client';
|
||||||
|
|
||||||
|
const auth = () => ({ headers: getAuthHeaders() });
|
||||||
|
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||||
|
|
||||||
|
// Users
|
||||||
|
export const listAdminUsers = () => requestJson<any[]>('/api/admin/users', auth());
|
||||||
|
export const createAdminUser = (payload: Record<string, unknown>) =>
|
||||||
|
requestJson('/api/admin/users', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||||
|
export const updateAdminUser = (id: number, payload: Record<string, unknown>) =>
|
||||||
|
requestJson(`/api/admin/users/${id}`, { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||||
|
export const approveAdminUser = (id: number) =>
|
||||||
|
requestJson(`/api/admin/users/${id}/approve`, { method: 'POST', ...auth() });
|
||||||
|
export const rejectAdminUser = (id: number) =>
|
||||||
|
requestJson(`/api/admin/users/${id}/reject`, { method: 'POST', ...auth() });
|
||||||
|
export const cleanupRejectedAdminUsers = () =>
|
||||||
|
requestJson<{ deleted_count: number }>('/api/admin/users/cleanup-rejected', { method: 'POST', ...auth() });
|
||||||
|
export const batchDeleteAdminUsers = (userIds: number[]) =>
|
||||||
|
requestJson<{ deleted_count: number }>('/api/admin/users/batch-delete', {
|
||||||
|
method: 'POST',
|
||||||
|
...jsonAuth(),
|
||||||
|
body: JSON.stringify({ user_ids: userIds }),
|
||||||
|
});
|
||||||
|
export const batchUpdateAdminUsers = (userIds: number[], data: Record<string, unknown>) =>
|
||||||
|
requestJson('/api/admin/users/batch', {
|
||||||
|
method: 'PUT',
|
||||||
|
...jsonAuth(),
|
||||||
|
body: JSON.stringify({ user_ids: userIds, data }),
|
||||||
|
});
|
||||||
|
export const updateAdminUserPermissions = (userId: number, agentIds: number[]) =>
|
||||||
|
requestJson(`/api/admin/users/${userId}/permissions`, {
|
||||||
|
method: 'POST',
|
||||||
|
...jsonAuth(),
|
||||||
|
body: JSON.stringify({ agent_ids: agentIds }),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Departments
|
||||||
|
export const listAdminDepartments = () => requestJson<any[]>('/api/admin/departments', auth());
|
||||||
|
export const createAdminDepartment = (payload: Record<string, unknown>) =>
|
||||||
|
requestJson('/api/admin/departments', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||||
|
export const updateAdminDepartment = (id: number, payload: Record<string, unknown>) =>
|
||||||
|
requestJson(`/api/admin/departments/${id}`, { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||||
|
export const deleteAdminDepartment = (id: number) =>
|
||||||
|
requestJson(`/api/admin/departments/${id}`, { method: 'DELETE', ...auth() });
|
||||||
|
|
||||||
|
// Agents
|
||||||
|
export const listAdminAgents = () => requestJson<any[]>('/api/admin/agents', auth());
|
||||||
|
export const createAdminAgent = (payload: Record<string, unknown>) =>
|
||||||
|
requestJson('/api/admin/agents', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||||
|
export const updateAdminAgent = (id: number, payload: Record<string, unknown>) =>
|
||||||
|
requestJson(`/api/admin/agents/${id}`, { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||||
|
export const deleteAdminAgent = (id: number) =>
|
||||||
|
requestJson(`/api/admin/agents/${id}`, { method: 'DELETE', ...auth() });
|
||||||
|
export const testAdminAgent = (id: number) =>
|
||||||
|
requestJson<any>(`/api/admin/agents/${id}/test`, { method: 'POST', ...auth() });
|
||||||
|
export const saveAdminAgentPermissions = (agentId: number, userIds: number[]) =>
|
||||||
|
requestJson(`/api/admin/agents/${agentId}/permissions`, {
|
||||||
|
method: 'POST',
|
||||||
|
...jsonAuth(),
|
||||||
|
body: JSON.stringify({ user_ids: userIds }),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Permission requests
|
||||||
|
export const listAdminPermissionRequests = () =>
|
||||||
|
requestJson<any[]>('/api/admin/permission-requests', auth());
|
||||||
|
export const approveAdminPermissionRequest = (id: number) =>
|
||||||
|
requestJson(`/api/admin/permission-requests/${id}/approve`, { method: 'POST', ...auth() });
|
||||||
|
export const rejectAdminPermissionRequest = (id: number) =>
|
||||||
|
requestJson(`/api/admin/permission-requests/${id}/reject`, { method: 'POST', ...auth() });
|
||||||
|
export const batchUpdateAdminPermissions = (payload: Record<string, unknown>) =>
|
||||||
|
requestJson('/api/admin/permissions/batch', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||||
|
export const importAdminPermissions = (formData: FormData) =>
|
||||||
|
requestJson('/api/admin/permissions/import', { method: 'POST', ...auth(), body: formData });
|
||||||
|
|
||||||
|
// Reports
|
||||||
|
export const getAdminUsageReport = () => requestJson<any>('/api/admin/reports/usage', auth());
|
||||||
|
export const getAdminFeedbackReport = () => requestJson<any>('/api/admin/reports/feedback', auth());
|
||||||
|
export const getAdminReportTable = (url: string) => requestJson<any[]>(url, auth());
|
||||||
|
export const getAdminReportTableCount = (url: string) => requestJson<{ total: number }>(url, auth());
|
||||||
|
export const batchDeleteAdminChatLogs = (ids: number[]) =>
|
||||||
|
requestJson<{ deleted_count: number }>('/api/admin/database/chat_logs/batch-delete', {
|
||||||
|
method: 'POST',
|
||||||
|
...jsonAuth(),
|
||||||
|
body: JSON.stringify({ ids }),
|
||||||
|
});
|
||||||
|
|
||||||
|
// WeCom admin
|
||||||
|
export const listAdminWecomBindings = (boundOnly: boolean) =>
|
||||||
|
requestJson<any[]>(`/api/admin/wecom/bindings?bound_only=${boundOnly ? 'true' : 'false'}`, auth());
|
||||||
|
export const listAdminWecomLoginAudits = (query: string) =>
|
||||||
|
requestJson<any[]>(`/api/admin/wecom/login-audits?${query}`, auth());
|
||||||
|
export const getAdminWecomSystemSettings = () =>
|
||||||
|
requestJson<any>('/api/admin/wecom/system-settings', auth());
|
||||||
|
export const getAdminWecomIntegrationManifest = () =>
|
||||||
|
requestJson<any>('/api/admin/wecom/integration-manifest', auth());
|
||||||
|
export const saveAdminWecomSystemSettings = (payload: Record<string, unknown>) =>
|
||||||
|
requestJson<any>('/api/admin/wecom/system-settings', {
|
||||||
|
method: 'PUT',
|
||||||
|
...jsonAuth(),
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
export const getAdminWecomNotifySettings = () =>
|
||||||
|
requestJson<any>('/api/admin/wecom/notify-settings', auth());
|
||||||
|
export const saveAdminWecomNotifySettings = (payload: Record<string, unknown>) =>
|
||||||
|
requestJson<any>('/api/admin/wecom/notify-settings', {
|
||||||
|
method: 'PUT',
|
||||||
|
...jsonAuth(),
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
export const getAdminWecomNotifyMetrics = () =>
|
||||||
|
requestJson<any>('/api/admin/wecom/notify-metrics', auth());
|
||||||
|
export const bindAdminWecomUser = (payload: Record<string, unknown>) =>
|
||||||
|
requestJson('/api/admin/wecom/bind', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||||
|
export const unbindAdminWecomUser = (userId: number) =>
|
||||||
|
requestJson('/api/admin/wecom/unbind', {
|
||||||
|
method: 'POST',
|
||||||
|
...jsonAuth(),
|
||||||
|
body: JSON.stringify({ user_id: userId }),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Announcements (admin module uses user endpoints)
|
||||||
|
export const listAnnouncements = () => requestJson<any[]>('/api/user/announcements', auth());
|
||||||
|
export const createAnnouncement = (payload: Record<string, unknown>) =>
|
||||||
|
requestJson('/api/user/announcements', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) });
|
||||||
|
export const deleteAnnouncement = (id: number) =>
|
||||||
|
requestJson(`/api/user/announcements/${id}`, { method: 'DELETE', ...auth() });
|
||||||
|
|
||||||
|
// Quick questions
|
||||||
|
export const listAdminQuickQuestions = () => requestJson<any[]>('/api/admin/quick-questions', auth());
|
||||||
|
export const saveAdminQuickQuestion = (url: string, method: string, payload: Record<string, unknown>) =>
|
||||||
|
requestJson(url, { method, ...jsonAuth(), body: JSON.stringify(payload) });
|
||||||
|
export const deleteAdminQuickQuestion = (id: number) =>
|
||||||
|
requestJson(`/api/admin/quick-questions/${id}`, { method: 'DELETE', ...auth() });
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import { getAuthHeaders } from '../utils/auth';
|
||||||
|
import { requestJson } from './client';
|
||||||
|
|
||||||
|
const auth = () => ({ headers: getAuthHeaders() });
|
||||||
|
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||||
|
|
||||||
|
export interface ChatSessionItem {
|
||||||
|
id: number;
|
||||||
|
conversation_id: string;
|
||||||
|
title: string;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LeaveAgentOption {
|
||||||
|
uid: string;
|
||||||
|
employeeId: string;
|
||||||
|
name: string;
|
||||||
|
jobtitle?: string;
|
||||||
|
jobtitleName?: string;
|
||||||
|
departmentid?: string;
|
||||||
|
subcompanyid1?: string;
|
||||||
|
departmentName?: string;
|
||||||
|
subcompanyName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OaEmployeesResponse {
|
||||||
|
items: LeaveAgentOption[];
|
||||||
|
total: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChatSourceFileResult {
|
||||||
|
source_download_url?: string;
|
||||||
|
source_filename?: string;
|
||||||
|
source_ext?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChatUploadResult {
|
||||||
|
id: string;
|
||||||
|
name?: string;
|
||||||
|
size?: number;
|
||||||
|
extension?: string;
|
||||||
|
mime_type?: string;
|
||||||
|
type?: 'image' | 'document' | 'audio' | 'video' | 'custom';
|
||||||
|
}
|
||||||
|
|
||||||
|
export const listChatSessions = (agentId: number) =>
|
||||||
|
requestJson<ChatSessionItem[]>(`/api/chat/sessions?agent_id=${agentId}`, auth());
|
||||||
|
|
||||||
|
export const deleteAllChatSessions = (agentId: number) =>
|
||||||
|
requestJson(`/api/chat/sessions?agent_id=${agentId}`, { method: 'DELETE', ...auth() });
|
||||||
|
|
||||||
|
export const deleteChatSession = (conversationId: string, agentId: number) =>
|
||||||
|
requestJson(`/api/chat/sessions/${conversationId}?agent_id=${agentId}`, { method: 'DELETE', ...auth() });
|
||||||
|
|
||||||
|
export const listChatMessages = (conversationId: string, agentId: number) =>
|
||||||
|
requestJson<any[]>(`/api/chat/messages?conversation_id=${conversationId}&agent_id=${agentId}`, auth());
|
||||||
|
|
||||||
|
export const saveLocalChatMessage = (payload: Record<string, unknown>) =>
|
||||||
|
requestJson<{ conversation_id?: string; chat_log_id?: number }>('/api/chat/messages/local', {
|
||||||
|
method: 'POST',
|
||||||
|
...jsonAuth(),
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const resolveChatSourceFile = (params: {
|
||||||
|
agent_id: number;
|
||||||
|
dataset_id: string;
|
||||||
|
remote_document_id: string;
|
||||||
|
}) => {
|
||||||
|
const qs = new URLSearchParams({
|
||||||
|
agent_id: String(params.agent_id),
|
||||||
|
dataset_id: params.dataset_id,
|
||||||
|
remote_document_id: params.remote_document_id,
|
||||||
|
});
|
||||||
|
return requestJson<ChatSourceFileResult>(`/api/chat/source-file?${qs.toString()}`, auth());
|
||||||
|
};
|
||||||
|
|
||||||
|
export const listOaEmployees = (
|
||||||
|
agentId: number,
|
||||||
|
query: { keyword?: string; page?: number; page_size?: number },
|
||||||
|
) => {
|
||||||
|
const qs = new URLSearchParams({
|
||||||
|
agent_id: String(agentId),
|
||||||
|
keyword: query.keyword || '',
|
||||||
|
page: String(query.page ?? 1),
|
||||||
|
page_size: String(query.page_size ?? 20),
|
||||||
|
});
|
||||||
|
return requestJson<OaEmployeesResponse>(`/api/chat/oa/employees?${qs.toString()}`, auth());
|
||||||
|
};
|
||||||
|
|
||||||
|
export const uploadChatFile = (agentId: number, file: File) => {
|
||||||
|
const qs = new URLSearchParams({ agent_id: String(agentId) });
|
||||||
|
const fd = new FormData();
|
||||||
|
fd.append('file', file);
|
||||||
|
return requestJson<ChatUploadResult>(`/api/chat/files/upload?${qs.toString()}`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: fd,
|
||||||
|
headers: getAuthHeaders(),
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
/**
|
||||||
|
* frontend/src/api/client.ts
|
||||||
|
* 用途:封装前端统一 API 访问与响应解析逻辑。
|
||||||
|
* 说明:
|
||||||
|
* 1. 支持两种返回格式:旧格式(直接返回数据)与新格式({ success, data/error })。
|
||||||
|
* 2. requestJson 统一处理成功/失败分支,并在失败时抛出 BusinessError。
|
||||||
|
* 3. BusinessError 提供 code/details/requestId,方便页面层做多语言与精细化提示。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { getAuthHeaders } from '../utils/auth';
|
||||||
|
import i18n from '../i18n';
|
||||||
|
|
||||||
|
export interface ApiSuccessEnvelope<T> {
|
||||||
|
success: true;
|
||||||
|
data: T;
|
||||||
|
request_id?: string;
|
||||||
|
timestamp?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiErrorBody {
|
||||||
|
code?: string;
|
||||||
|
message?: string;
|
||||||
|
details?: Record<string, any>;
|
||||||
|
retryable?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiErrorEnvelope {
|
||||||
|
success: false;
|
||||||
|
error?: ApiErrorBody;
|
||||||
|
request_id?: string;
|
||||||
|
timestamp?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BusinessError extends Error {
|
||||||
|
code: string;
|
||||||
|
details: Record<string, any>;
|
||||||
|
requestId?: string;
|
||||||
|
status?: number;
|
||||||
|
|
||||||
|
constructor(args: { message: string; code?: string; details?: Record<string, any>; requestId?: string; status?: number }) {
|
||||||
|
super(args.message);
|
||||||
|
this.name = 'BusinessError';
|
||||||
|
this.code = args.code || 'SYSTEM.UNKNOWN';
|
||||||
|
this.details = args.details || {};
|
||||||
|
this.requestId = args.requestId;
|
||||||
|
this.status = args.status;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveLocalizedErrorMessage(code?: string, fallbackMessage?: string): string {
|
||||||
|
const normalizedCode = code ? code.replace(/\./g, '_') : '';
|
||||||
|
const key = normalizedCode ? `errors.codes.${normalizedCode}` : '';
|
||||||
|
const fallback = String(fallbackMessage || '').trim();
|
||||||
|
const isGenericFallback = (msg: string) => {
|
||||||
|
const v = msg.trim().toLowerCase();
|
||||||
|
if (!v) return true;
|
||||||
|
if (v === 'invalid request parameters' || v === 'invalid request parameters.') return true;
|
||||||
|
if (v === 'request failed' || v === 'request failed.') return true;
|
||||||
|
if (v.startsWith('http ')) return true;
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
if (key && i18n.global.te(key)) {
|
||||||
|
const localized = String(i18n.global.t(key));
|
||||||
|
if (normalizedCode === 'VALIDATION_INVALID_PARAM' && fallback && !isGenericFallback(fallback) && fallback !== localized) {
|
||||||
|
return `${localized} ${fallback}`;
|
||||||
|
}
|
||||||
|
return localized;
|
||||||
|
}
|
||||||
|
if (fallback) return fallback;
|
||||||
|
if (i18n.global.te('errors.generic')) {
|
||||||
|
return String(i18n.global.t('errors.generic'));
|
||||||
|
}
|
||||||
|
return code || 'Request failed';
|
||||||
|
}
|
||||||
|
|
||||||
|
export const isEnvelope = (payload: any): payload is ApiSuccessEnvelope<any> | ApiErrorEnvelope => {
|
||||||
|
return !!payload && typeof payload === 'object' && typeof payload.success === 'boolean';
|
||||||
|
};
|
||||||
|
|
||||||
|
function pickLegacyErrorMessage(payload: any): string | undefined {
|
||||||
|
if (!payload) return undefined;
|
||||||
|
if (typeof payload.error === 'string' && payload.error.trim()) return payload.error;
|
||||||
|
if (typeof payload.message === 'string' && payload.message.trim()) return payload.message;
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function requestJson<T>(url: string, init?: RequestInit): Promise<T> {
|
||||||
|
const headers = new Headers(init?.headers || {});
|
||||||
|
const authHeaders = getAuthHeaders();
|
||||||
|
Object.entries(authHeaders).forEach(([k, v]) => headers.set(k, v as string));
|
||||||
|
const res = await fetch(url, { ...init, headers });
|
||||||
|
|
||||||
|
let data: any = null;
|
||||||
|
try {
|
||||||
|
data = await res.json();
|
||||||
|
} catch {
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new BusinessError({
|
||||||
|
message: `HTTP ${res.status}`,
|
||||||
|
code: 'SYSTEM.HTTP_ERROR',
|
||||||
|
status: res.status,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return null as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
if (isEnvelope(data) && data.success === false) {
|
||||||
|
throw new BusinessError({
|
||||||
|
message: resolveLocalizedErrorMessage(data.error?.code, data.error?.message || `HTTP ${res.status}`),
|
||||||
|
code: data.error?.code,
|
||||||
|
details: data.error?.details,
|
||||||
|
requestId: data.request_id,
|
||||||
|
status: res.status,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw new BusinessError({
|
||||||
|
message: resolveLocalizedErrorMessage(data?.code, pickLegacyErrorMessage(data) || `HTTP ${res.status}`),
|
||||||
|
code: data?.code || data?.error_code || 'SYSTEM.HTTP_ERROR',
|
||||||
|
details: data?.details || {},
|
||||||
|
requestId: data?.request_id,
|
||||||
|
status: res.status,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isEnvelope(data)) {
|
||||||
|
if (data.success === true) return data.data as T;
|
||||||
|
throw new BusinessError({
|
||||||
|
message: resolveLocalizedErrorMessage(data.error?.code, data.error?.message || 'Request failed'),
|
||||||
|
code: data.error?.code,
|
||||||
|
details: data.error?.details,
|
||||||
|
requestId: data.request_id,
|
||||||
|
status: res.status,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return data as T;
|
||||||
|
}
|
||||||
+108
-193
@@ -1,4 +1,5 @@
|
|||||||
import { getAuthHeaders } from '../utils/auth';
|
import { getAuthHeaders } from '../utils/auth';
|
||||||
|
import { BusinessError, requestJson } from './client';
|
||||||
|
|
||||||
export interface KbGroup {
|
export interface KbGroup {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -116,11 +117,14 @@ export interface KbListResponse<T> {
|
|||||||
status?: number;
|
status?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const auth = () => ({ headers: getAuthHeaders() });
|
||||||
|
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||||
|
|
||||||
|
const kbErrorMessage = (e: unknown, fallback: string) => (e as Error).message || fallback;
|
||||||
|
|
||||||
const getJson = async <T>(path: string, fallback: T): Promise<T> => {
|
const getJson = async <T>(path: string, fallback: T): Promise<T> => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(path, { headers: getAuthHeaders() });
|
return await requestJson<T>(path, auth());
|
||||||
if (!res.ok) return fallback;
|
|
||||||
return (await res.json()) as T;
|
|
||||||
} catch {
|
} catch {
|
||||||
return fallback;
|
return fallback;
|
||||||
}
|
}
|
||||||
@@ -128,19 +132,16 @@ const getJson = async <T>(path: string, fallback: T): Promise<T> => {
|
|||||||
|
|
||||||
const getJsonWithStatus = async <T>(path: string, fallback: T): Promise<KbListResponse<T>> => {
|
const getJsonWithStatus = async <T>(path: string, fallback: T): Promise<KbListResponse<T>> => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(path, { headers: getAuthHeaders() });
|
const data = await requestJson<T>(path, auth());
|
||||||
if (!res.ok) {
|
return { ok: true, data };
|
||||||
const data = await res.json().catch(() => ({}));
|
} catch (e) {
|
||||||
return {
|
const err = e as BusinessError;
|
||||||
ok: false,
|
return {
|
||||||
data: fallback,
|
ok: false,
|
||||||
error: data?.error || '知识库接口请求失败',
|
data: fallback,
|
||||||
status: res.status,
|
error: kbErrorMessage(e, '知识库接口请求失败'),
|
||||||
};
|
status: err.status,
|
||||||
}
|
};
|
||||||
return { ok: true, data: (await res.json()) as T, status: res.status };
|
|
||||||
} catch {
|
|
||||||
return { ok: false, data: fallback, error: '知识库接口暂未就绪,请稍后再试' };
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -165,21 +166,14 @@ export const createKbGroup = async (payload: {
|
|||||||
description?: string;
|
description?: string;
|
||||||
}): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
|
}): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/kb/groups', {
|
const group = await requestJson<KbGroup>('/api/kb/groups', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
...jsonAuth(),
|
||||||
'Content-Type': 'application/json',
|
|
||||||
...getAuthHeaders(),
|
|
||||||
},
|
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
return { ok: true, group };
|
||||||
const data = await res.json().catch(() => ({}));
|
} catch (e) {
|
||||||
return { ok: false, error: data?.error || '创建知识库分组失败' };
|
return { ok: false, error: kbErrorMessage(e, '创建知识库分组失败') };
|
||||||
}
|
|
||||||
return { ok: true, group: (await res.json()) as KbGroup };
|
|
||||||
} catch {
|
|
||||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -199,21 +193,14 @@ export const updateKbDifySettings = async (
|
|||||||
payload: Partial<KbDifySettings>
|
payload: Partial<KbDifySettings>
|
||||||
): Promise<{ ok: boolean; error?: string; settings?: KbDifySettings }> => {
|
): Promise<{ ok: boolean; error?: string; settings?: KbDifySettings }> => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/kb/dify/settings', {
|
const settings = await requestJson<KbDifySettings>('/api/kb/dify/settings', {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
headers: {
|
...jsonAuth(),
|
||||||
'Content-Type': 'application/json',
|
|
||||||
...getAuthHeaders(),
|
|
||||||
},
|
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
return { ok: true, settings };
|
||||||
const data = await res.json().catch(() => ({}));
|
} catch (e) {
|
||||||
return { ok: false, error: data?.error || '保存 Dify 设置失败' };
|
return { ok: false, error: kbErrorMessage(e, '保存 Dify 设置失败') };
|
||||||
}
|
|
||||||
return { ok: true, settings: (await res.json()) as KbDifySettings };
|
|
||||||
} catch {
|
|
||||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -225,18 +212,13 @@ export const runKbJob = async (
|
|||||||
jobId: number | string
|
jobId: number | string
|
||||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
|
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/kb/jobs/${jobId}/run`, {
|
const job = await requestJson<KbJob & { run_result?: string }>(`/api/kb/jobs/${jobId}/run`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: getAuthHeaders(),
|
...auth(),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
|
||||||
const data = await res.json().catch(() => ({}));
|
|
||||||
return { ok: false, error: data?.error || '执行任务失败' };
|
|
||||||
}
|
|
||||||
const job = (await res.json()) as KbJob & { run_result?: string };
|
|
||||||
return { ok: true, job, run_result: job.run_result };
|
return { ok: true, job, run_result: job.run_result };
|
||||||
} catch {
|
} catch (e) {
|
||||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
return { ok: false, error: kbErrorMessage(e, '执行任务失败') };
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -245,21 +227,14 @@ export const createKbDocument = async (
|
|||||||
payload: { title: string; description?: string }
|
payload: { title: string; description?: string }
|
||||||
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
|
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/kb/groups/${groupId}/files`, {
|
const document = await requestJson<KbDocumentItem>(`/api/kb/groups/${groupId}/files`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
...jsonAuth(),
|
||||||
'Content-Type': 'application/json',
|
|
||||||
...getAuthHeaders(),
|
|
||||||
},
|
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
return { ok: true, document };
|
||||||
const data = await res.json().catch(() => ({}));
|
} catch (e) {
|
||||||
return { ok: false, error: data?.error || '创建文档失败' };
|
return { ok: false, error: kbErrorMessage(e, '创建文档失败') };
|
||||||
}
|
|
||||||
return { ok: true, document: (await res.json()) as KbDocumentItem };
|
|
||||||
} catch {
|
|
||||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -268,21 +243,14 @@ export const updateKbDocument = async (
|
|||||||
payload: { title: string; description?: string; status?: string }
|
payload: { title: string; description?: string; status?: string }
|
||||||
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
|
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/kb/documents/${documentId}`, {
|
const document = await requestJson<KbDocumentItem>(`/api/kb/documents/${documentId}`, {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
headers: {
|
...jsonAuth(),
|
||||||
'Content-Type': 'application/json',
|
|
||||||
...getAuthHeaders(),
|
|
||||||
},
|
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
return { ok: true, document };
|
||||||
const data = await res.json().catch(() => ({}));
|
} catch (e) {
|
||||||
return { ok: false, error: data?.error || '更新文档失败' };
|
return { ok: false, error: kbErrorMessage(e, '更新文档失败') };
|
||||||
}
|
|
||||||
return { ok: true, document: (await res.json()) as KbDocumentItem };
|
|
||||||
} catch {
|
|
||||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -290,17 +258,10 @@ export const deleteKbDocument = async (
|
|||||||
documentId: number
|
documentId: number
|
||||||
): Promise<{ ok: boolean; error?: string }> => {
|
): Promise<{ ok: boolean; error?: string }> => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/kb/documents/${documentId}`, {
|
await requestJson(`/api/kb/documents/${documentId}`, { method: 'DELETE', ...auth() });
|
||||||
method: 'DELETE',
|
|
||||||
headers: getAuthHeaders(),
|
|
||||||
});
|
|
||||||
if (!res.ok) {
|
|
||||||
const data = await res.json().catch(() => ({}));
|
|
||||||
return { ok: false, error: data?.error || '删除文档失败' };
|
|
||||||
}
|
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
} catch {
|
} catch (e) {
|
||||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
return { ok: false, error: kbErrorMessage(e, '删除文档失败') };
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -318,8 +279,15 @@ export const getKbDocumentVersionSourceFile = async (
|
|||||||
headers: getAuthHeaders(),
|
headers: getAuthHeaders(),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const data = await res.json().catch(() => ({}));
|
let message = '读取原始文件失败';
|
||||||
return { ok: false, error: data?.error || '读取原始文件失败' };
|
try {
|
||||||
|
const data = await res.json();
|
||||||
|
if (typeof data?.error === 'string' && data.error.trim()) message = data.error;
|
||||||
|
else if (typeof data?.message === 'string' && data.message.trim()) message = data.message;
|
||||||
|
} catch {
|
||||||
|
// ignore non-json error body
|
||||||
|
}
|
||||||
|
return { ok: false, error: message };
|
||||||
}
|
}
|
||||||
const disposition = res.headers.get('content-disposition') || '';
|
const disposition = res.headers.get('content-disposition') || '';
|
||||||
const filenameMatch = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^"]+)"?/i);
|
const filenameMatch = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^"]+)"?/i);
|
||||||
@@ -345,16 +313,10 @@ export const getKbDocumentMarkdown = async (
|
|||||||
documentId: number
|
documentId: number
|
||||||
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
|
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/kb/documents/${documentId}/markdown`, {
|
const data = await requestJson<KbDocumentMarkdown>(`/api/kb/documents/${documentId}/markdown`, auth());
|
||||||
headers: getAuthHeaders(),
|
return { ok: true, data };
|
||||||
});
|
} catch (e) {
|
||||||
if (!res.ok) {
|
return { ok: false, error: kbErrorMessage(e, '读取清洗后的 Markdown 失败') };
|
||||||
const data = await res.json().catch(() => ({}));
|
|
||||||
return { ok: false, error: data?.error || '读取清洗后的 Markdown 失败' };
|
|
||||||
}
|
|
||||||
return { ok: true, data: (await res.json()) as KbDocumentMarkdown };
|
|
||||||
} catch {
|
|
||||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -363,21 +325,14 @@ export const updateKbDocumentMarkdown = async (
|
|||||||
payload: { content: string }
|
payload: { content: string }
|
||||||
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
|
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/kb/documents/${documentId}/markdown`, {
|
const data = await requestJson<KbDocumentMarkdown>(`/api/kb/documents/${documentId}/markdown`, {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
headers: {
|
...jsonAuth(),
|
||||||
'Content-Type': 'application/json',
|
|
||||||
...getAuthHeaders(),
|
|
||||||
},
|
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
return { ok: true, data };
|
||||||
const data = await res.json().catch(() => ({}));
|
} catch (e) {
|
||||||
return { ok: false, error: data?.error || '保存 Markdown 失败' };
|
return { ok: false, error: kbErrorMessage(e, '保存 Markdown 失败') };
|
||||||
}
|
|
||||||
return { ok: true, data: (await res.json()) as KbDocumentMarkdown };
|
|
||||||
} catch {
|
|
||||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -388,22 +343,22 @@ export const uploadKbDocumentVersion = async (
|
|||||||
try {
|
try {
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('file', file);
|
formData.append('file', file);
|
||||||
|
const version = await requestJson<KbDocumentVersionItem>(`/api/kb/documents/${documentId}/upload`, {
|
||||||
const res = await fetch(`/api/kb/documents/${documentId}/upload`, {
|
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: getAuthHeaders(),
|
...auth(),
|
||||||
body: formData,
|
body: formData,
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
return { ok: true, version };
|
||||||
if (res.status === 413) {
|
} catch (e) {
|
||||||
return { ok: false, error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试', status: res.status };
|
const err = e as BusinessError;
|
||||||
}
|
if (err.status === 413) {
|
||||||
const data = await res.json().catch(() => ({}));
|
return {
|
||||||
return { ok: false, error: data?.error || '上传文档版本失败', status: res.status };
|
ok: false,
|
||||||
|
error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试',
|
||||||
|
status: 413,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
return { ok: true, version: (await res.json()) as KbDocumentVersionItem, status: res.status };
|
return { ok: false, error: kbErrorMessage(e, '上传文档版本失败'), status: err.status };
|
||||||
} catch {
|
|
||||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -412,21 +367,15 @@ export const createKbPathUploadJob = async (
|
|||||||
payload: { total_files: number; selected_paths: string[] }
|
payload: { total_files: number; selected_paths: string[] }
|
||||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
|
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/kb/groups/${groupId}/path-upload-jobs`, {
|
const job = await requestJson<KbJob>(`/api/kb/groups/${groupId}/path-upload-jobs`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
...jsonAuth(),
|
||||||
'Content-Type': 'application/json',
|
|
||||||
...getAuthHeaders(),
|
|
||||||
},
|
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
const data = await res.json().catch(() => ({}));
|
return { ok: true, job };
|
||||||
if (!res.ok) {
|
} catch (e) {
|
||||||
return { ok: false, error: data?.error || '创建路径上传任务失败', status: res.status };
|
const err = e as BusinessError;
|
||||||
}
|
return { ok: false, error: kbErrorMessage(e, '创建路径上传任务失败'), status: err.status };
|
||||||
return { ok: true, job: data as KbJob, status: res.status };
|
|
||||||
} catch {
|
|
||||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -439,19 +388,14 @@ export const uploadKbPathJobFile = async (
|
|||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append('file', file);
|
formData.append('file', file);
|
||||||
formData.append('relative_path', relativePath);
|
formData.append('relative_path', relativePath);
|
||||||
|
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/files`, {
|
||||||
const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/files`, {
|
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: getAuthHeaders(),
|
...auth(),
|
||||||
body: formData,
|
body: formData,
|
||||||
});
|
});
|
||||||
const data = await res.json().catch(() => ({}));
|
return { ok: true, job };
|
||||||
if (!res.ok) {
|
} catch (e) {
|
||||||
return { ok: false, error: data?.error || '上传路径文件失败' };
|
return { ok: false, error: kbErrorMessage(e, '上传路径文件失败') };
|
||||||
}
|
|
||||||
return { ok: true, job: data as KbJob };
|
|
||||||
} catch {
|
|
||||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -459,17 +403,13 @@ export const finalizeKbPathUploadJob = async (
|
|||||||
jobId: number | string,
|
jobId: number | string,
|
||||||
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
|
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/finalize`, {
|
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/finalize`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: getAuthHeaders(),
|
...auth(),
|
||||||
});
|
});
|
||||||
const data = await res.json().catch(() => ({}));
|
return { ok: true, job };
|
||||||
if (!res.ok) {
|
} catch (e) {
|
||||||
return { ok: false, error: data?.error || '提交路径上传任务失败' };
|
return { ok: false, error: kbErrorMessage(e, '提交路径上传任务失败') };
|
||||||
}
|
|
||||||
return { ok: true, job: data as KbJob };
|
|
||||||
} catch {
|
|
||||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -478,21 +418,15 @@ export const retryFailedKbPathUploadJob = async (
|
|||||||
payload?: { relative_paths?: string[] },
|
payload?: { relative_paths?: string[] },
|
||||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
|
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/retry-failed`, {
|
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/retry-failed`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
...jsonAuth(),
|
||||||
'Content-Type': 'application/json',
|
|
||||||
...getAuthHeaders(),
|
|
||||||
},
|
|
||||||
body: JSON.stringify(payload || {}),
|
body: JSON.stringify(payload || {}),
|
||||||
});
|
});
|
||||||
const data = await res.json().catch(() => ({}));
|
return { ok: true, job };
|
||||||
if (!res.ok) {
|
} catch (e) {
|
||||||
return { ok: false, error: data?.error || '重试失败文件失败', status: res.status };
|
const err = e as BusinessError;
|
||||||
}
|
return { ok: false, error: kbErrorMessage(e, '重试失败文件失败'), status: err.status };
|
||||||
return { ok: true, job: data as KbJob, status: res.status };
|
|
||||||
} catch {
|
|
||||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -500,18 +434,13 @@ export const syncKbDocumentToDify = async (
|
|||||||
documentId: number
|
documentId: number
|
||||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
|
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/kb/documents/${documentId}/sync`, {
|
const job = await requestJson<KbJob & { run_result?: string }>(`/api/kb/documents/${documentId}/sync`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: getAuthHeaders(),
|
...auth(),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
|
||||||
const data = await res.json().catch(() => ({}));
|
|
||||||
return { ok: false, error: data?.error || data?.error_message || data?.run_result || '同步到 Dify 失败' };
|
|
||||||
}
|
|
||||||
const job = (await res.json()) as KbJob & { run_result?: string };
|
|
||||||
return { ok: true, job, run_result: job.run_result };
|
return { ok: true, job, run_result: job.run_result };
|
||||||
} catch {
|
} catch (e) {
|
||||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
return { ok: false, error: kbErrorMessage(e, '同步到 Dify 失败') };
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -520,21 +449,14 @@ export const updateKbGroup = async (
|
|||||||
payload: { name: string; description?: string }
|
payload: { name: string; description?: string }
|
||||||
): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
|
): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/kb/groups/${groupId}`, {
|
const group = await requestJson<KbGroup>(`/api/kb/groups/${groupId}`, {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
headers: {
|
...jsonAuth(),
|
||||||
'Content-Type': 'application/json',
|
|
||||||
...getAuthHeaders(),
|
|
||||||
},
|
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
return { ok: true, group };
|
||||||
const data = await res.json().catch(() => ({}));
|
} catch (e) {
|
||||||
return { ok: false, error: data?.error || '更新知识库分组失败' };
|
return { ok: false, error: kbErrorMessage(e, '更新知识库分组失败') };
|
||||||
}
|
|
||||||
return { ok: true, group: (await res.json()) as KbGroup };
|
|
||||||
} catch {
|
|
||||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -542,16 +464,9 @@ export const deleteKbGroup = async (
|
|||||||
groupId: number
|
groupId: number
|
||||||
): Promise<{ ok: boolean; error?: string }> => {
|
): Promise<{ ok: boolean; error?: string }> => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/kb/groups/${groupId}`, {
|
await requestJson(`/api/kb/groups/${groupId}`, { method: 'DELETE', ...auth() });
|
||||||
method: 'DELETE',
|
|
||||||
headers: getAuthHeaders(),
|
|
||||||
});
|
|
||||||
if (!res.ok) {
|
|
||||||
const data = await res.json().catch(() => ({}));
|
|
||||||
return { ok: false, error: data?.error || '删除知识库分组失败' };
|
|
||||||
}
|
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
} catch {
|
} catch (e) {
|
||||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
return { ok: false, error: kbErrorMessage(e, '删除知识库分组失败') };
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { getAuthHeaders } from '../utils/auth';
|
import { getAuthHeaders } from '../utils/auth';
|
||||||
|
import { requestJson } from './client';
|
||||||
|
|
||||||
export interface ScheduleTask {
|
export interface ScheduleTask {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -70,9 +71,7 @@ export interface DifyExecutionSnapshot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function getJson<T>(url: string): Promise<T> {
|
async function getJson<T>(url: string): Promise<T> {
|
||||||
const res = await fetch(url, { headers: getAuthHeaders() });
|
return requestJson<T>(url, { headers: getAuthHeaders() });
|
||||||
if (!res.ok) throw new Error((await res.json().catch(() => ({})))?.error || 'Request failed');
|
|
||||||
return (await res.json()) as T;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const listAdminSchedules = () =>
|
export const listAdminSchedules = () =>
|
||||||
@@ -81,39 +80,37 @@ export const listAdminSchedules = () =>
|
|||||||
export const exportAdminScheduleUrl = (taskId: number) => `/api/admin/schedules/${taskId}/export`;
|
export const exportAdminScheduleUrl = (taskId: number) => `/api/admin/schedules/${taskId}/export`;
|
||||||
|
|
||||||
export const importAdminSchedules = async (payload: any) => {
|
export const importAdminSchedules = async (payload: any) => {
|
||||||
const res = await fetch('/api/admin/schedules/import', {
|
return requestJson('/api/admin/schedules/import', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
|
||||||
const data = await res.json().catch(() => ({}));
|
|
||||||
throw new Error(data.error || 'Import failed');
|
|
||||||
}
|
|
||||||
return res.json();
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getAdminScheduleTaskConfig = (taskId: number) =>
|
export const getAdminScheduleTaskConfig = (taskId: number) =>
|
||||||
getJson<{ data_source_type: string; config: Record<string, any> | null }>(`/api/admin/schedule-config/${taskId}`);
|
getJson<{ data_source_type: string; config: Record<string, any> | null }>(`/api/admin/schedule-config/${taskId}`);
|
||||||
|
|
||||||
export const updateAdminScheduleTaskConfig = (taskId: number, payload: Record<string, any>) =>
|
export const updateAdminScheduleTaskConfig = (taskId: number, payload: Record<string, any>) =>
|
||||||
fetch(`/api/admin/schedule-config/${taskId}`, {
|
requestJson(`/api/admin/schedule-config/${taskId}`, {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
}).then(r => {
|
|
||||||
if (!r.ok) throw new Error('Update config failed');
|
|
||||||
return r.json();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export interface TestScheduleSqlResult {
|
||||||
|
total: number;
|
||||||
|
showing: number;
|
||||||
|
limit: number;
|
||||||
|
sql: string;
|
||||||
|
columns: string[];
|
||||||
|
rows: Record<string, any>[];
|
||||||
|
}
|
||||||
|
|
||||||
export const testAdminScheduleSql = (taskId: number, payload: { fetch_where_conditions?: string; fetch_order_by?: string; limit?: number }) =>
|
export const testAdminScheduleSql = (taskId: number, payload: { fetch_where_conditions?: string; fetch_order_by?: string; limit?: number }) =>
|
||||||
fetch(`/api/admin/schedule-config/${taskId}/test-sql`, {
|
requestJson<TestScheduleSqlResult>(`/api/admin/schedule-config/${taskId}/test-sql`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
}).then(r => {
|
|
||||||
if (!r.ok) return r.json().then(e => { throw new Error(e.error || 'Test failed'); });
|
|
||||||
return r.json();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export interface TestScheduleRunResult {
|
export interface TestScheduleRunResult {
|
||||||
@@ -133,38 +130,35 @@ export interface TestScheduleRunResult {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const testAdminScheduleRun = (taskId: number, payload: { fetch_where_conditions?: string; fetch_order_by?: string; limit?: number }) =>
|
export const testAdminScheduleRun = (taskId: number, payload: { fetch_where_conditions?: string; fetch_order_by?: string; limit?: number }) =>
|
||||||
fetch(`/api/admin/schedule-config/${taskId}/test-run`, {
|
requestJson<TestScheduleRunResult>(`/api/admin/schedule-config/${taskId}/test-run`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
}).then(r => {
|
|
||||||
if (!r.ok) return r.json().then(e => { throw new Error(e.error || 'Test run failed'); });
|
|
||||||
return r.json() as Promise<TestScheduleRunResult>;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export const createAdminSchedule = (payload: Partial<ScheduleTask> & { config?: Record<string, any> }) =>
|
export const createAdminSchedule = (payload: Partial<ScheduleTask> & { config?: Record<string, any> }) =>
|
||||||
fetch('/api/admin/schedules', {
|
requestJson('/api/admin/schedules', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const updateAdminSchedule = (id: number, payload: Partial<ScheduleTask> & { config?: Record<string, any> }) =>
|
export const updateAdminSchedule = (id: number, payload: Partial<ScheduleTask> & { config?: Record<string, any> }) =>
|
||||||
fetch(`/api/admin/schedules/${id}`, {
|
requestJson(`/api/admin/schedules/${id}`, {
|
||||||
method: 'PATCH',
|
method: 'PATCH',
|
||||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
|
|
||||||
export const deleteAdminSchedule = (id: number) =>
|
export const deleteAdminSchedule = (id: number) =>
|
||||||
fetch(`/api/admin/schedules/${id}`, {
|
requestJson(`/api/admin/schedules/${id}`, {
|
||||||
method: 'DELETE',
|
method: 'DELETE',
|
||||||
headers: getAuthHeaders(),
|
headers: getAuthHeaders(),
|
||||||
});
|
});
|
||||||
export const runAdminSchedule = (id: number) =>
|
export const runAdminSchedule = (id: number) =>
|
||||||
fetch(`/api/admin/schedules/${id}/run`, { method: 'POST', headers: getAuthHeaders() });
|
requestJson(`/api/admin/schedules/${id}/run`, { method: 'POST', headers: getAuthHeaders() });
|
||||||
export const toggleAdminSchedule = (id: number, enabled: boolean) =>
|
export const toggleAdminSchedule = (id: number, enabled: boolean) =>
|
||||||
fetch(`/api/admin/schedules/${id}/${enabled ? 'enable' : 'disable'}`, { method: 'POST', headers: getAuthHeaders() });
|
requestJson(`/api/admin/schedules/${id}/${enabled ? 'enable' : 'disable'}`, { method: 'POST', headers: getAuthHeaders() });
|
||||||
export const listAdminScheduleRuns = (taskId: number, params?: { status?: string; started_after?: string; started_before?: string }) => {
|
export const listAdminScheduleRuns = (taskId: number, params?: { status?: string; started_after?: string; started_before?: string }) => {
|
||||||
const sp = new URLSearchParams();
|
const sp = new URLSearchParams();
|
||||||
if (params?.status) sp.set('status', params.status);
|
if (params?.status) sp.set('status', params.status);
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { getAuthHeaders } from '../utils/auth';
|
||||||
|
import { requestJson } from './client';
|
||||||
|
|
||||||
|
const auth = () => ({ headers: getAuthHeaders() });
|
||||||
|
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||||
|
|
||||||
|
export const getUserProfile = () => requestJson<Record<string, any>>('/api/user/profile', auth());
|
||||||
|
|
||||||
|
export interface LeaveBalanceResult {
|
||||||
|
has_balance: boolean;
|
||||||
|
leave_type_label: string;
|
||||||
|
year: number;
|
||||||
|
total_hours: number | null;
|
||||||
|
used_hours: number | null;
|
||||||
|
remaining_hours: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getLeaveBalance = (leaveType: string) =>
|
||||||
|
requestJson<LeaveBalanceResult>(`/api/user/leave-balance?leave_type=${encodeURIComponent(leaveType)}`, auth());
|
||||||
|
|
||||||
|
export interface LeaveWorkflowSubmitResult {
|
||||||
|
request_id?: string;
|
||||||
|
submitted_at?: string;
|
||||||
|
request_name?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const submitLeaveWorkflow = (form: Record<string, any>) =>
|
||||||
|
requestJson<LeaveWorkflowSubmitResult>('/api/user/leave-workflow/submit', {
|
||||||
|
method: 'POST',
|
||||||
|
...jsonAuth(),
|
||||||
|
body: JSON.stringify(form),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const resetPasswordConfirm = (token: string, newPassword: string) =>
|
||||||
|
requestJson('/api/user/reset-password-confirm', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ token, new_password: newPassword }),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const getUserAgent = (agentId: number) =>
|
||||||
|
requestJson<Record<string, any>>(`/api/user/agents/${agentId}`, auth());
|
||||||
|
|
||||||
|
export const listUserAgents = () => requestJson<any[]>('/api/agents', auth());
|
||||||
@@ -12,7 +12,6 @@ import { computed, ref, watch } from 'vue';
|
|||||||
import { useI18n } from 'vue-i18n';
|
import { useI18n } from 'vue-i18n';
|
||||||
import { marked } from 'marked';
|
import { marked } from 'marked';
|
||||||
import * as XLSX from 'xlsx';
|
import * as XLSX from 'xlsx';
|
||||||
import { useMessage } from '../composables/useMessage';
|
|
||||||
import VueOfficeDocx from '@vue-office/docx';
|
import VueOfficeDocx from '@vue-office/docx';
|
||||||
import VueOfficeExcel from '@vue-office/excel';
|
import VueOfficeExcel from '@vue-office/excel';
|
||||||
import '@vue-office/docx/lib/index.css';
|
import '@vue-office/docx/lib/index.css';
|
||||||
@@ -21,6 +20,7 @@ import '@vue-office/excel/lib/index.css';
|
|||||||
interface PreviewFile {
|
interface PreviewFile {
|
||||||
name: string;
|
name: string;
|
||||||
url: string;
|
url: string;
|
||||||
|
actualExt?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ExcelPreviewData {
|
interface ExcelPreviewData {
|
||||||
@@ -33,6 +33,7 @@ interface ExcelPreviewData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type OfficeKind = 'docx' | 'excel' | null;
|
type OfficeKind = 'docx' | 'excel' | null;
|
||||||
|
type PreviewMode = 'markdown' | 'image' | 'iframe' | 'sheet' | 'office';
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
modelValue: boolean;
|
modelValue: boolean;
|
||||||
@@ -44,16 +45,17 @@ const props = defineProps<{
|
|||||||
const emit = defineEmits<{
|
const emit = defineEmits<{
|
||||||
(e: 'update:modelValue', value: boolean): void;
|
(e: 'update:modelValue', value: boolean): void;
|
||||||
}>();
|
}>();
|
||||||
const msg = useMessage();
|
|
||||||
const { t } = useI18n();
|
const { t } = useI18n();
|
||||||
|
|
||||||
const isLoading = ref(false);
|
const isLoading = ref(false);
|
||||||
|
const isDownloading = ref(false);
|
||||||
const error = ref('');
|
const error = ref('');
|
||||||
const markdownHtml = ref('');
|
const markdownHtml = ref('');
|
||||||
const excelPreview = ref<ExcelPreviewData | null>(null);
|
const excelPreview = ref<ExcelPreviewData | null>(null);
|
||||||
const officeSrc = ref<string | ArrayBuffer | Blob>('');
|
const officeSrc = ref<string | ArrayBuffer | Blob>('');
|
||||||
const officeKind = ref<OfficeKind>(null);
|
const officeKind = ref<OfficeKind>(null);
|
||||||
const officeObjectUrl = ref<string>('');
|
const officeObjectUrl = ref<string>('');
|
||||||
|
const officeRenderKey = ref(0);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 从 URL 或文件名中提取扩展名。
|
* 从 URL 或文件名中提取扩展名。
|
||||||
@@ -69,13 +71,15 @@ const getExt = (raw: string) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const ext = computed(() => {
|
const ext = computed(() => {
|
||||||
|
const actual = getExt(props.file?.actualExt || '');
|
||||||
|
if (actual) return actual;
|
||||||
// Display name extension has higher priority than URL.
|
// Display name extension has higher priority than URL.
|
||||||
const byName = getExt(props.file?.name || '');
|
const byName = getExt(props.file?.name || '');
|
||||||
if (byName) return byName;
|
if (byName) return byName;
|
||||||
return getExt(props.file?.url || '');
|
return getExt(props.file?.url || '');
|
||||||
});
|
});
|
||||||
|
|
||||||
const preferredMode = computed<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>(() => {
|
const preferredMode = computed<PreviewMode>(() => {
|
||||||
if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'].includes(ext.value)) return 'image';
|
if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'].includes(ext.value)) return 'image';
|
||||||
if (['md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'].includes(ext.value)) return 'markdown';
|
if (['md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'].includes(ext.value)) return 'markdown';
|
||||||
if (['xlsx', 'xls'].includes(ext.value)) return 'sheet';
|
if (['xlsx', 'xls'].includes(ext.value)) return 'sheet';
|
||||||
@@ -84,7 +88,7 @@ const preferredMode = computed<'markdown' | 'image' | 'iframe' | 'sheet' | 'offi
|
|||||||
return 'iframe';
|
return 'iframe';
|
||||||
});
|
});
|
||||||
|
|
||||||
const resolvedMode = ref<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>('iframe');
|
const resolvedMode = ref<PreviewMode>('iframe');
|
||||||
|
|
||||||
const needsOfficeFallback = computed(() => {
|
const needsOfficeFallback = computed(() => {
|
||||||
// We no longer need fallback for doc/ppt/pptx because they are converted to PDF by the backend
|
// We no longer need fallback for doc/ppt/pptx because they are converted to PDF by the backend
|
||||||
@@ -110,50 +114,12 @@ const iframeSrc = computed(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const imageSrc = computed(() => officeObjectUrl.value || props.file?.url || '');
|
const imageSrc = computed(() => officeObjectUrl.value || props.file?.url || '');
|
||||||
|
const officePreviewExts = new Set(['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx']);
|
||||||
|
|
||||||
const close = () => emit('update:modelValue', false);
|
const close = () => emit('update:modelValue', false);
|
||||||
|
|
||||||
const isDownloading = ref(false);
|
|
||||||
const previewTooLarge = computed(() => /file too large for online preview/i.test(error.value));
|
const previewTooLarge = computed(() => /file too large for online preview/i.test(error.value));
|
||||||
|
|
||||||
const downloadFile = async () => {
|
|
||||||
if (!props.file?.url || !props.agentId) return;
|
|
||||||
isDownloading.value = true;
|
|
||||||
try {
|
|
||||||
const params = new URLSearchParams({
|
|
||||||
agent_id: String(props.agentId),
|
|
||||||
url: props.file.url,
|
|
||||||
name: props.file.name || '',
|
|
||||||
download: '1'
|
|
||||||
});
|
|
||||||
|
|
||||||
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
|
|
||||||
headers: props.authHeaders || {},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!res.ok) {
|
|
||||||
const err = await res.json().catch(() => ({}));
|
|
||||||
throw new Error(err?.error || `HTTP ${res.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const blob = await res.blob();
|
|
||||||
const url = URL.createObjectURL(blob);
|
|
||||||
|
|
||||||
const a = document.createElement('a');
|
|
||||||
a.href = url;
|
|
||||||
a.download = props.file.name || 'download';
|
|
||||||
document.body.appendChild(a);
|
|
||||||
a.click();
|
|
||||||
document.body.removeChild(a);
|
|
||||||
URL.revokeObjectURL(url);
|
|
||||||
} catch (err: any) {
|
|
||||||
console.error('Download failed:', err);
|
|
||||||
msg.error(t('filePreview.msg.downloadFailed', { reason: err.message || t('filePreview.msg.unknownError') }));
|
|
||||||
} finally {
|
|
||||||
isDownloading.value = false;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const clearOfficeObjectUrl = () => {
|
const clearOfficeObjectUrl = () => {
|
||||||
if (officeObjectUrl.value) {
|
if (officeObjectUrl.value) {
|
||||||
URL.revokeObjectURL(officeObjectUrl.value);
|
URL.revokeObjectURL(officeObjectUrl.value);
|
||||||
@@ -163,6 +129,66 @@ const clearOfficeObjectUrl = () => {
|
|||||||
officeKind.value = null;
|
officeKind.value = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const applyExcelPreview = (buffer: ArrayBuffer) => {
|
||||||
|
const workbook = XLSX.read(buffer, { type: 'array' });
|
||||||
|
if (!workbook.SheetNames.length) {
|
||||||
|
throw new Error('workbook has no sheets');
|
||||||
|
}
|
||||||
|
const sheetName = workbook.SheetNames[0] || 'Sheet1';
|
||||||
|
const worksheet = workbook.Sheets[sheetName];
|
||||||
|
if (!worksheet) {
|
||||||
|
throw new Error(`worksheet not found: ${sheetName}`);
|
||||||
|
}
|
||||||
|
const matrix = XLSX.utils.sheet_to_json<(string | number | boolean)[]>(worksheet, {
|
||||||
|
header: 1,
|
||||||
|
raw: false,
|
||||||
|
defval: '',
|
||||||
|
});
|
||||||
|
const limit = 100;
|
||||||
|
const rows = matrix.slice(0, limit).map((row) => row.map((cell) => cell ?? ''));
|
||||||
|
const maxCols = rows.reduce((max, row) => Math.max(max, row.length), 0);
|
||||||
|
const normalizedRows = rows.map((row) =>
|
||||||
|
row.length < maxCols ? [...row, ...Array(maxCols - row.length).fill('')] : row
|
||||||
|
);
|
||||||
|
excelPreview.value = {
|
||||||
|
sheet_name: sheetName,
|
||||||
|
sheets: workbook.SheetNames,
|
||||||
|
columns: Array.from({ length: maxCols }, (_, i) => `COL_${i + 1}`),
|
||||||
|
rows: normalizedRows,
|
||||||
|
limit,
|
||||||
|
truncated: matrix.length > limit,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const tryApplyExcelPreview = (buffer: ArrayBuffer) => {
|
||||||
|
try {
|
||||||
|
applyExcelPreview(buffer);
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadSheetPreview = async () => {
|
||||||
|
if (!props.file?.url) return;
|
||||||
|
if (!props.agentId) throw new Error('agent_id is required for excel preview');
|
||||||
|
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
agent_id: String(props.agentId),
|
||||||
|
url: props.file.url,
|
||||||
|
name: props.file.name || '',
|
||||||
|
});
|
||||||
|
const res = await fetch(`/api/chat/preview-excel?${params.toString()}`, {
|
||||||
|
headers: props.authHeaders || {},
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const data = await res.json().catch(() => ({}));
|
||||||
|
throw new Error(data?.error || `HTTP ${res.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
excelPreview.value = await res.json();
|
||||||
|
};
|
||||||
|
|
||||||
const loadOfficeContent = async () => {
|
const loadOfficeContent = async () => {
|
||||||
if (!props.file?.url) return;
|
if (!props.file?.url) return;
|
||||||
if (!props.agentId) throw new Error('agent_id is required for office preview');
|
if (!props.agentId) throw new Error('agent_id is required for office preview');
|
||||||
@@ -180,20 +206,29 @@ const loadOfficeContent = async () => {
|
|||||||
throw new Error(err?.error || `HTTP ${res.status}`);
|
throw new Error(err?.error || `HTTP ${res.status}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
const blob = await res.blob();
|
const buffer = await res.arrayBuffer();
|
||||||
clearOfficeObjectUrl();
|
clearOfficeObjectUrl();
|
||||||
officeObjectUrl.value = URL.createObjectURL(blob);
|
officeSrc.value = buffer;
|
||||||
officeSrc.value = officeObjectUrl.value;
|
officeRenderKey.value += 1;
|
||||||
|
|
||||||
if (ext.value === 'docx' || ext.value === 'doc') officeKind.value = 'docx';
|
if (ext.value === 'docx' || ext.value === 'doc') officeKind.value = 'docx';
|
||||||
else if (ext.value === 'xlsx' || ext.value === 'xls') officeKind.value = 'excel';
|
else if (ext.value === 'xlsx' || ext.value === 'xls') officeKind.value = 'excel';
|
||||||
else officeKind.value = null;
|
else officeKind.value = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadPdfContent = async () => {
|
const loadPdfContent = async (): Promise<'iframe' | 'office' | 'sheet'> => {
|
||||||
if (!props.file?.url) return;
|
if (!props.file?.url) return 'iframe';
|
||||||
if (!props.agentId) throw new Error('agent_id is required for pdf preview');
|
if (!props.agentId) throw new Error('agent_id is required for pdf preview');
|
||||||
|
|
||||||
|
if (ext.value === 'doc') {
|
||||||
|
try {
|
||||||
|
await loadSheetPreview();
|
||||||
|
return 'sheet';
|
||||||
|
} catch {
|
||||||
|
// Not an excel-disguised-as-doc file, continue with the normal document preview flow.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const params = new URLSearchParams({
|
const params = new URLSearchParams({
|
||||||
agent_id: String(props.agentId),
|
agent_id: String(props.agentId),
|
||||||
url: props.file.url,
|
url: props.file.url,
|
||||||
@@ -209,11 +244,37 @@ const loadPdfContent = async () => {
|
|||||||
|
|
||||||
const blob = await res.blob();
|
const blob = await res.blob();
|
||||||
clearOfficeObjectUrl();
|
clearOfficeObjectUrl();
|
||||||
|
const buffer = await blob.arrayBuffer();
|
||||||
|
const actualExt = (res.headers.get('X-Preview-Actual-Ext') || '').toLowerCase();
|
||||||
|
const blobType = (blob.type || '').toLowerCase();
|
||||||
|
const effectiveExt = actualExt || ext.value;
|
||||||
|
const isDocxPayload = actualExt === 'docx' || blobType.includes('wordprocessingml.document');
|
||||||
|
const isExcelPayload = ['xlsx', 'xls'].includes(actualExt) || blobType.includes('spreadsheetml.sheet') || blobType.includes('application/vnd.ms-excel');
|
||||||
|
if (isExcelPayload) {
|
||||||
|
if (tryApplyExcelPreview(buffer)) {
|
||||||
|
return 'sheet';
|
||||||
|
}
|
||||||
|
await loadSheetPreview();
|
||||||
|
return 'sheet';
|
||||||
|
}
|
||||||
|
if (!blobType.includes('pdf') && tryApplyExcelPreview(buffer)) {
|
||||||
|
return 'sheet';
|
||||||
|
}
|
||||||
|
if (isDocxPayload) {
|
||||||
|
officeSrc.value = buffer;
|
||||||
|
officeRenderKey.value += 1;
|
||||||
|
officeKind.value = 'docx';
|
||||||
|
return 'office';
|
||||||
|
}
|
||||||
|
if (!blobType.includes('pdf') && officePreviewExts.has(effectiveExt)) {
|
||||||
|
throw new Error('当前原始文件暂不支持直接预览,已阻止浏览器自动下载');
|
||||||
|
}
|
||||||
let fallbackType = 'application/octet-stream';
|
let fallbackType = 'application/octet-stream';
|
||||||
if (ext.value === 'pdf' || ['doc', 'ppt', 'pptx'].includes(ext.value)) fallbackType = 'application/pdf';
|
if (ext.value === 'pdf' || ['doc', 'ppt', 'pptx'].includes(ext.value)) fallbackType = 'application/pdf';
|
||||||
else if (ext.value === 'docx') fallbackType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
|
else if (ext.value === 'docx') fallbackType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
|
||||||
const effectiveBlob = blob.type ? blob : new Blob([blob], { type: fallbackType });
|
const effectiveBlob = blob.type ? blob : new Blob([blob], { type: fallbackType });
|
||||||
officeObjectUrl.value = URL.createObjectURL(effectiveBlob);
|
officeObjectUrl.value = URL.createObjectURL(effectiveBlob);
|
||||||
|
return 'iframe';
|
||||||
};
|
};
|
||||||
|
|
||||||
const loadBinaryContent = async () => {
|
const loadBinaryContent = async () => {
|
||||||
@@ -238,6 +299,43 @@ const loadBinaryContent = async () => {
|
|||||||
officeObjectUrl.value = URL.createObjectURL(blob);
|
officeObjectUrl.value = URL.createObjectURL(blob);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const downloadFile = async () => {
|
||||||
|
if (!props.file?.url || !props.agentId || isDownloading.value) return;
|
||||||
|
|
||||||
|
isDownloading.value = true;
|
||||||
|
try {
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
agent_id: String(props.agentId),
|
||||||
|
url: props.file.url,
|
||||||
|
name: props.file.name || '',
|
||||||
|
download: '1',
|
||||||
|
});
|
||||||
|
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
|
||||||
|
headers: props.authHeaders || {},
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
const err = await res.json().catch(() => ({}));
|
||||||
|
throw new Error(err?.error || `HTTP ${res.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const blob = await res.blob();
|
||||||
|
const downloadUrl = URL.createObjectURL(blob);
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = downloadUrl;
|
||||||
|
link.download = props.file.name || 'download';
|
||||||
|
document.body.appendChild(link);
|
||||||
|
link.click();
|
||||||
|
link.remove();
|
||||||
|
window.setTimeout(() => URL.revokeObjectURL(downloadUrl), 1000);
|
||||||
|
} catch (e: any) {
|
||||||
|
error.value = t('filePreview.msg.downloadFailed', {
|
||||||
|
reason: e?.message || t('filePreview.msg.unknownError'),
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
isDownloading.value = false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 在弹窗/文件变化时加载预览内容。
|
* 在弹窗/文件变化时加载预览内容。
|
||||||
* 流程:
|
* 流程:
|
||||||
@@ -263,8 +361,7 @@ const loadContent = async () => {
|
|||||||
}
|
}
|
||||||
isLoading.value = true;
|
isLoading.value = true;
|
||||||
try {
|
try {
|
||||||
await loadPdfContent(); // This fetches as Blob, and sets officeObjectUrl which will be used in iframeSrc
|
resolvedMode.value = await loadPdfContent();
|
||||||
resolvedMode.value = 'iframe';
|
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
error.value = e?.message || `Failed to preview ${ext.value}`;
|
error.value = e?.message || `Failed to preview ${ext.value}`;
|
||||||
resolvedMode.value = 'iframe';
|
resolvedMode.value = 'iframe';
|
||||||
@@ -291,54 +388,9 @@ const loadContent = async () => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (preferredMode.value === 'sheet') {
|
if (preferredMode.value === 'sheet') {
|
||||||
if (!props.agentId) {
|
|
||||||
error.value = 'agent_id is required for excel preview';
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
isLoading.value = true;
|
isLoading.value = true;
|
||||||
try {
|
try {
|
||||||
const params = new URLSearchParams({
|
await loadSheetPreview();
|
||||||
agent_id: String(props.agentId),
|
|
||||||
url: props.file.url,
|
|
||||||
name: props.file.name || '',
|
|
||||||
});
|
|
||||||
const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, {
|
|
||||||
headers: props.authHeaders || {},
|
|
||||||
});
|
|
||||||
if (!res.ok) {
|
|
||||||
const data = await res.json().catch(() => ({}));
|
|
||||||
throw new Error(data?.error || `HTTP ${res.status}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const buffer = await res.arrayBuffer();
|
|
||||||
const workbook = XLSX.read(buffer, { type: 'array' });
|
|
||||||
if (!workbook.SheetNames.length) {
|
|
||||||
throw new Error('workbook has no sheets');
|
|
||||||
}
|
|
||||||
const sheetName = workbook.SheetNames[0] || 'Sheet1';
|
|
||||||
const worksheet = workbook.Sheets[sheetName];
|
|
||||||
if (!worksheet) {
|
|
||||||
throw new Error(`worksheet not found: ${sheetName}`);
|
|
||||||
}
|
|
||||||
const matrix = XLSX.utils.sheet_to_json<(string | number | boolean)[]>(worksheet, {
|
|
||||||
header: 1,
|
|
||||||
raw: false,
|
|
||||||
defval: '',
|
|
||||||
});
|
|
||||||
const limit = 100;
|
|
||||||
const rows = matrix.slice(0, limit).map((row) => row.map((cell) => cell ?? ''));
|
|
||||||
const maxCols = rows.reduce((max, row) => Math.max(max, row.length), 0);
|
|
||||||
const normalizedRows = rows.map((row) =>
|
|
||||||
row.length < maxCols ? [...row, ...Array(maxCols - row.length).fill('')] : row
|
|
||||||
);
|
|
||||||
excelPreview.value = {
|
|
||||||
sheet_name: sheetName,
|
|
||||||
sheets: workbook.SheetNames,
|
|
||||||
columns: Array.from({ length: maxCols }, (_, i) => `COL_${i + 1}`),
|
|
||||||
rows: normalizedRows,
|
|
||||||
limit,
|
|
||||||
truncated: matrix.length > limit,
|
|
||||||
};
|
|
||||||
resolvedMode.value = 'sheet';
|
resolvedMode.value = 'sheet';
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
error.value = e?.message || 'Failed to preview excel';
|
error.value = e?.message || 'Failed to preview excel';
|
||||||
@@ -374,6 +426,7 @@ const loadContent = async () => {
|
|||||||
agent_id: String(props.agentId),
|
agent_id: String(props.agentId),
|
||||||
url: props.file.url,
|
url: props.file.url,
|
||||||
name: props.file.name || '',
|
name: props.file.name || '',
|
||||||
|
ext: ext.value || '',
|
||||||
});
|
});
|
||||||
const res = await fetch(`/api/chat/preview-text?${params.toString()}`, {
|
const res = await fetch(`/api/chat/preview-text?${params.toString()}`, {
|
||||||
headers: props.authHeaders || {},
|
headers: props.authHeaders || {},
|
||||||
@@ -421,13 +474,13 @@ watch(
|
|||||||
<div class="dialog-panel max-w-5xl h-[85vh] overflow-hidden">
|
<div class="dialog-panel max-w-5xl h-[85vh] overflow-hidden">
|
||||||
<div class="dialog-header dialog-header--compact items-start">
|
<div class="dialog-header dialog-header--compact items-start">
|
||||||
<div class="min-w-0">
|
<div class="min-w-0">
|
||||||
<div class="label-field tracking-wide">{{ t('filePreview.title') }}</div>
|
<div class="text-sm font-medium text-slate-500 dark:text-slate-400 tracking-wide">{{ t('filePreview.title') }}</div>
|
||||||
<div class="mt-1 font-semibold text-primary break-words">{{ file.name }}</div>
|
<div class="mt-1 font-semibold text-slate-900 dark:text-slate-100 break-words">{{ file.name }}</div>
|
||||||
<button type="button" @click="downloadFile" :disabled="isDownloading" class="btn-secondary btn-sm mt-2 inline-flex border-brand-200 text-brand-700 hover:bg-brand-50 disabled:opacity-50 disabled:cursor-not-allowed">
|
<button type="button" @click="downloadFile" :disabled="isDownloading" class="mt-2 inline-flex items-center justify-center px-3 py-1.5 text-xs font-medium rounded-lg bg-brand-50 text-brand-700 hover:bg-brand-100 border border-brand-200 dark:bg-brand-900/30 dark:text-brand-300 dark:border-brand-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
|
||||||
<svg v-if="!isDownloading" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
<svg v-if="!isDownloading" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
|
||||||
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
||||||
</svg>
|
</svg>
|
||||||
<svg v-else class="animate-spin -ml-1 mr-2 h-4 w-4 text-brand-700" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
<svg v-else class="animate-spin -ml-1 mr-2 h-4 w-4 text-brand-700 dark:text-brand-300" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||||
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
||||||
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||||
</svg>
|
</svg>
|
||||||
@@ -491,11 +544,15 @@ watch(
|
|||||||
>
|
>
|
||||||
<VueOfficeDocx
|
<VueOfficeDocx
|
||||||
v-if="officeKind === 'docx'"
|
v-if="officeKind === 'docx'"
|
||||||
|
:key="`docx-${officeRenderKey}`"
|
||||||
:src="officeSrc"
|
:src="officeSrc"
|
||||||
|
@rendered="error = ''"
|
||||||
|
@error="error = 'DOCX render failed'"
|
||||||
style="height: 100%; width: 100%;"
|
style="height: 100%; width: 100%;"
|
||||||
/>
|
/>
|
||||||
<VueOfficeExcel
|
<VueOfficeExcel
|
||||||
v-else-if="officeKind === 'excel'"
|
v-else-if="officeKind === 'excel'"
|
||||||
|
:key="`excel-${officeRenderKey}`"
|
||||||
:src="officeSrc"
|
:src="officeSrc"
|
||||||
style="height: 100%; width: 100%;"
|
style="height: 100%; width: 100%;"
|
||||||
/>
|
/>
|
||||||
@@ -528,7 +585,7 @@ watch(
|
|||||||
type="button"
|
type="button"
|
||||||
@click="downloadFile"
|
@click="downloadFile"
|
||||||
:disabled="isDownloading"
|
:disabled="isDownloading"
|
||||||
class="btn-primary btn-sm inline-flex"
|
class="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center"
|
||||||
>
|
>
|
||||||
<svg v-if="isDownloading" class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
<svg v-if="isDownloading" class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
|
||||||
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
|
||||||
|
|||||||
@@ -32,6 +32,18 @@ interface ChatMessage {
|
|||||||
rated?: boolean;
|
rated?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type RunStatus = 'running' | 'done' | 'error';
|
||||||
|
|
||||||
|
interface ChatRun {
|
||||||
|
runId: number;
|
||||||
|
viewId: number;
|
||||||
|
query: string;
|
||||||
|
messages: ChatMessage[];
|
||||||
|
conversationId: string | null;
|
||||||
|
status: RunStatus;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
// 统一资源格式为数组,兼容 list 或 { data: list } 两种结构
|
// 统一资源格式为数组,兼容 list 或 { data: list } 两种结构
|
||||||
const normalizeResources = (resources: any): RetrieverResource[] => {
|
const normalizeResources = (resources: any): RetrieverResource[] => {
|
||||||
if (!resources) return [];
|
if (!resources) return [];
|
||||||
@@ -125,12 +137,35 @@ export function useChat() {
|
|||||||
*/
|
*/
|
||||||
const isThinking = ref(false);
|
const isThinking = ref(false);
|
||||||
|
|
||||||
|
const viewId = ref(0);
|
||||||
|
|
||||||
|
const runs = ref<ChatRun[]>([]);
|
||||||
|
const activeRunId = ref<number | null>(null);
|
||||||
|
let runSeq = 0;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* conversationId: 当前会话 ID
|
* conversationId: 当前会话 ID
|
||||||
* 用于在多轮对话中关联上下文,并在反馈时找到对应 ChatLog
|
* 用于在多轮对话中关联上下文,并在反馈时找到对应 ChatLog
|
||||||
*/
|
*/
|
||||||
const conversationId = ref<string | null>(null);
|
const conversationId = ref<string | null>(null);
|
||||||
|
|
||||||
|
const activateRun = (runId: number) => {
|
||||||
|
const run = runs.value.find((r) => r.runId === runId);
|
||||||
|
if (!run) return;
|
||||||
|
messages.value = run.messages;
|
||||||
|
conversationId.value = run.conversationId;
|
||||||
|
isThinking.value = run.status === 'running';
|
||||||
|
activeRunId.value = runId;
|
||||||
|
};
|
||||||
|
|
||||||
|
const createNewChatView = () => {
|
||||||
|
viewId.value += 1;
|
||||||
|
messages.value = [];
|
||||||
|
conversationId.value = null;
|
||||||
|
isThinking.value = false;
|
||||||
|
activeRunId.value = null;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* sendMessage
|
* sendMessage
|
||||||
* 用途:发送消息并处理 SSE 流式响应
|
* 用途:发送消息并处理 SSE 流式响应
|
||||||
@@ -144,7 +179,29 @@ export function useChat() {
|
|||||||
* query: 用户输入文本
|
* query: 用户输入文本
|
||||||
* agentId: 目标 Agent ID
|
* agentId: 目标 Agent ID
|
||||||
*/
|
*/
|
||||||
const sendMessage = async (query: string, agentId: number, kbType: string = '企业知识库') => {
|
const sendMessage = async (
|
||||||
|
query: string,
|
||||||
|
agentId: number,
|
||||||
|
kbType: string = '企业知识库',
|
||||||
|
files?: Array<
|
||||||
|
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'local_file'; upload_file_id: string }
|
||||||
|
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: string }
|
||||||
|
>,
|
||||||
|
) => {
|
||||||
|
const runViewId = viewId.value;
|
||||||
|
const runMessages = messages.value;
|
||||||
|
const run: ChatRun = {
|
||||||
|
runId: ++runSeq,
|
||||||
|
viewId: runViewId,
|
||||||
|
query,
|
||||||
|
messages: runMessages,
|
||||||
|
conversationId: conversationId.value,
|
||||||
|
status: 'running',
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
runs.value.unshift(run);
|
||||||
|
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
|
||||||
|
activeRunId.value = run.runId;
|
||||||
console.info('[chat][send] start', {
|
console.info('[chat][send] start', {
|
||||||
agentId,
|
agentId,
|
||||||
kbType,
|
kbType,
|
||||||
@@ -152,19 +209,19 @@ export function useChat() {
|
|||||||
conversationId: conversationId.value,
|
conversationId: conversationId.value,
|
||||||
});
|
});
|
||||||
// 1. 乐观 UI 更新:立即将用户消息推入列表
|
// 1. 乐观 UI 更新:立即将用户消息推入列表
|
||||||
messages.value.push({ role: 'user', content: query });
|
runMessages.push({ role: 'user', content: query });
|
||||||
// Lazily create assistant message only when answer/error arrives.
|
// Lazily create assistant message only when answer/error arrives.
|
||||||
let botMsgIndex: number | null = null;
|
let botMsgIndex: number | null = null;
|
||||||
const ensureBotMessage = () => {
|
const ensureBotMessage = () => {
|
||||||
if (botMsgIndex === null) {
|
if (botMsgIndex === null) {
|
||||||
botMsgIndex = messages.value.push({
|
botMsgIndex = runMessages.push({
|
||||||
role: 'assistant',
|
role: 'assistant',
|
||||||
content: '',
|
content: '',
|
||||||
retriever_resources: [],
|
retriever_resources: [],
|
||||||
attribution_parts: []
|
attribution_parts: []
|
||||||
}) - 1;
|
}) - 1;
|
||||||
}
|
}
|
||||||
return messages.value[botMsgIndex] || null;
|
return runMessages[botMsgIndex] || null;
|
||||||
};
|
};
|
||||||
|
|
||||||
isThinking.value = true;
|
isThinking.value = true;
|
||||||
@@ -178,7 +235,8 @@ export function useChat() {
|
|||||||
query,
|
query,
|
||||||
agent_id: agentId,
|
agent_id: agentId,
|
||||||
conversation_id: conversationId.value,
|
conversation_id: conversationId.value,
|
||||||
kb_type: kbType
|
kb_type: kbType,
|
||||||
|
files: files && files.length > 0 ? files : undefined,
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -234,7 +292,14 @@ export function useChat() {
|
|||||||
conversationId: data?.conversation_id || conversationId.value,
|
conversationId: data?.conversation_id || conversationId.value,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (data.event === 'message') {
|
if (data?.conversation_id) {
|
||||||
|
const cid = String(data.conversation_id);
|
||||||
|
if (!run.conversationId) run.conversationId = cid;
|
||||||
|
if (messages.value === runMessages) conversationId.value = cid;
|
||||||
|
}
|
||||||
|
|
||||||
|
const eventName = String(data.event || '');
|
||||||
|
if (eventName === 'message' || eventName === 'agent_message') {
|
||||||
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||||||
const botMsg = ensureBotMessage();
|
const botMsg = ensureBotMessage();
|
||||||
if (!botMsg) continue;
|
if (!botMsg) continue;
|
||||||
@@ -246,21 +311,20 @@ export function useChat() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (botMsgIndex !== null) {
|
if (botMsgIndex !== null) {
|
||||||
const currentBotMsg = messages.value[botMsgIndex];
|
const currentBotMsg = runMessages[botMsgIndex];
|
||||||
if (currentBotMsg) {
|
if (currentBotMsg) {
|
||||||
applyEventMetadata(currentBotMsg, data);
|
applyEventMetadata(currentBotMsg, data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (data.event === 'message_end') {
|
} else if (eventName === 'message_end' || eventName === 'workflow_finished') {
|
||||||
|
run.status = 'done';
|
||||||
|
if (messages.value === runMessages) isThinking.value = false;
|
||||||
if (botMsgIndex !== null && Number.isInteger(data.chat_log_id)) {
|
if (botMsgIndex !== null && Number.isInteger(data.chat_log_id)) {
|
||||||
const currentBotMsg = messages.value[botMsgIndex];
|
const currentBotMsg = runMessages[botMsgIndex];
|
||||||
if (currentBotMsg) {
|
if (currentBotMsg) {
|
||||||
currentBotMsg.chat_log_id = Number(data.chat_log_id);
|
currentBotMsg.chat_log_id = Number(data.chat_log_id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (data.conversation_id) {
|
|
||||||
conversationId.value = data.conversation_id;
|
|
||||||
}
|
|
||||||
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||||||
const botMsg = ensureBotMessage();
|
const botMsg = ensureBotMessage();
|
||||||
if (!botMsg) continue;
|
if (!botMsg) continue;
|
||||||
@@ -278,16 +342,22 @@ export function useChat() {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (botMsgIndex !== null) {
|
if (botMsgIndex !== null) {
|
||||||
const currentBotMsg = messages.value[botMsgIndex];
|
const currentBotMsg = runMessages[botMsgIndex];
|
||||||
if (currentBotMsg) {
|
if (currentBotMsg) {
|
||||||
applyEventMetadata(currentBotMsg, data);
|
applyEventMetadata(currentBotMsg, data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (data.event === 'error') {
|
} else if (eventName === 'error') {
|
||||||
const botMsg = ensureBotMessage();
|
const botMsg = ensureBotMessage();
|
||||||
if (!botMsg) continue;
|
if (!botMsg) continue;
|
||||||
botMsg.content += `\n[Error: ${data.message}]`;
|
botMsg.content += `\n[Error: ${data.message}]`;
|
||||||
console.error('[chat][sse] backend error event', data);
|
console.error('[chat][sse] backend error event', data);
|
||||||
|
run.status = 'error';
|
||||||
|
if (messages.value === runMessages) isThinking.value = false;
|
||||||
|
} else if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||||||
|
const botMsg = ensureBotMessage();
|
||||||
|
if (!botMsg) continue;
|
||||||
|
botMsg.content += normalizeStreamText(data.answer);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// Ignore malformed or partial payload fragments.
|
// Ignore malformed or partial payload fragments.
|
||||||
@@ -297,16 +367,24 @@ export function useChat() {
|
|||||||
}
|
}
|
||||||
} catch (e: any) {
|
} catch (e: any) {
|
||||||
console.error('[chat][send] failed', e);
|
console.error('[chat][send] failed', e);
|
||||||
|
run.status = 'error';
|
||||||
const botMsg = ensureBotMessage();
|
const botMsg = ensureBotMessage();
|
||||||
if (botMsg) {
|
if (botMsg) {
|
||||||
botMsg.content += `\n[Error: ${e.message || 'Network Issue'}]`;
|
botMsg.content += `\n[Error: ${e.message || 'Network Issue'}]`;
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
isThinking.value = false;
|
if (messages.value === runMessages) {
|
||||||
console.info('[chat][send] end', {
|
isThinking.value = false;
|
||||||
messages: messages.value.length,
|
console.info('[chat][send] end', {
|
||||||
conversationId: conversationId.value,
|
messages: messages.value.length,
|
||||||
});
|
conversationId: conversationId.value,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.info('[chat][send] end (detached)', {
|
||||||
|
activeConversationId: conversationId.value,
|
||||||
|
runViewId,
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -315,5 +393,5 @@ export function useChat() {
|
|||||||
return text.replace(/\\n/g, '\n');
|
return text.replace(/\\n/g, '\n');
|
||||||
};
|
};
|
||||||
|
|
||||||
return { messages, isThinking, conversationId, sendMessage };
|
return { messages, isThinking, conversationId, runs, activeRunId, activateRun, createNewChatView, sendMessage };
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
import { ref, computed, onBeforeUnmount, type Ref } from 'vue';
|
||||||
|
|
||||||
|
export type SpeechRecognitionErrorKey =
|
||||||
|
| 'chat.voiceNotSupported'
|
||||||
|
| 'chat.voiceRequiresHttps'
|
||||||
|
| 'chat.voicePermissionDenied'
|
||||||
|
| 'chat.voiceNoSpeech'
|
||||||
|
| 'chat.voiceAudioCapture'
|
||||||
|
| 'chat.voiceNetworkError'
|
||||||
|
| 'chat.voiceServiceNotAllowed'
|
||||||
|
| 'chat.voiceRecognitionFailed';
|
||||||
|
|
||||||
|
type SpeechRecognitionCtor = new () => SpeechRecognition;
|
||||||
|
|
||||||
|
const getSpeechRecognitionCtor = (): SpeechRecognitionCtor | null => {
|
||||||
|
if (typeof window === 'undefined') return null;
|
||||||
|
const w = window as Window & {
|
||||||
|
SpeechRecognition?: SpeechRecognitionCtor;
|
||||||
|
webkitSpeechRecognition?: SpeechRecognitionCtor;
|
||||||
|
};
|
||||||
|
return w.SpeechRecognition || w.webkitSpeechRecognition || null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const mapLocaleToSpeechLang = (locale: string): string => {
|
||||||
|
const map: Record<string, string> = {
|
||||||
|
'zh-CN': 'zh-CN',
|
||||||
|
'zh-TW': 'zh-TW',
|
||||||
|
en: 'en-US',
|
||||||
|
th: 'th-TH',
|
||||||
|
};
|
||||||
|
return map[locale] || 'zh-CN';
|
||||||
|
};
|
||||||
|
|
||||||
|
const isSecureContextForSpeech = (): boolean => {
|
||||||
|
if (typeof window === 'undefined') return false;
|
||||||
|
if (window.isSecureContext) return true;
|
||||||
|
const host = window.location.hostname;
|
||||||
|
return host === 'localhost' || host === '127.0.0.1';
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 语音不可用时的提示 key;HTTPS/localhost 且浏览器有 API 时返回 null */
|
||||||
|
export const getVoiceUnavailableErrorKey = (): SpeechRecognitionErrorKey | null => {
|
||||||
|
if (!isSecureContextForSpeech()) return 'chat.voiceRequiresHttps';
|
||||||
|
if (!getSpeechRecognitionCtor()) return 'chat.voiceNotSupported';
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const mapErrorToKey = (error: string): SpeechRecognitionErrorKey => {
|
||||||
|
switch (error) {
|
||||||
|
case 'not-allowed':
|
||||||
|
return 'chat.voicePermissionDenied';
|
||||||
|
case 'service-not-allowed':
|
||||||
|
return 'chat.voiceServiceNotAllowed';
|
||||||
|
case 'no-speech':
|
||||||
|
return 'chat.voiceNoSpeech';
|
||||||
|
case 'audio-capture':
|
||||||
|
return 'chat.voiceAudioCapture';
|
||||||
|
case 'network':
|
||||||
|
return 'chat.voiceNetworkError';
|
||||||
|
default:
|
||||||
|
return 'chat.voiceRecognitionFailed';
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export function useSpeechRecognition(options: {
|
||||||
|
lang: Ref<string>;
|
||||||
|
onResult: (text: string) => void;
|
||||||
|
onError: (key: SpeechRecognitionErrorKey) => void;
|
||||||
|
}) {
|
||||||
|
const isListening = ref(false);
|
||||||
|
const isSupported = computed(() => getVoiceUnavailableErrorKey() === null);
|
||||||
|
|
||||||
|
let recognition: SpeechRecognition | null = null;
|
||||||
|
let baseText = '';
|
||||||
|
|
||||||
|
const stop = () => {
|
||||||
|
if (recognition) {
|
||||||
|
try {
|
||||||
|
recognition.abort();
|
||||||
|
} catch {
|
||||||
|
// ignore abort errors
|
||||||
|
}
|
||||||
|
recognition = null;
|
||||||
|
}
|
||||||
|
isListening.value = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
const start = (existingText = '') => {
|
||||||
|
if (isListening.value) return;
|
||||||
|
|
||||||
|
const unavailable = getVoiceUnavailableErrorKey();
|
||||||
|
if (unavailable) {
|
||||||
|
options.onError(unavailable);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const Ctor = getSpeechRecognitionCtor()!;
|
||||||
|
|
||||||
|
stop();
|
||||||
|
baseText = existingText;
|
||||||
|
|
||||||
|
const instance = new Ctor();
|
||||||
|
instance.continuous = true;
|
||||||
|
instance.interimResults = true;
|
||||||
|
instance.lang = mapLocaleToSpeechLang(options.lang.value);
|
||||||
|
|
||||||
|
instance.onstart = () => {
|
||||||
|
isListening.value = true;
|
||||||
|
};
|
||||||
|
|
||||||
|
instance.onresult = (event: SpeechRecognitionEvent) => {
|
||||||
|
let sessionTranscript = '';
|
||||||
|
for (let i = 0; i < event.results.length; i++) {
|
||||||
|
sessionTranscript += event.results[i]?.[0]?.transcript || '';
|
||||||
|
}
|
||||||
|
options.onResult(`${baseText}${sessionTranscript}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
instance.onerror = (event: SpeechRecognitionErrorEvent) => {
|
||||||
|
if (event.error === 'aborted') return;
|
||||||
|
options.onError(mapErrorToKey(event.error));
|
||||||
|
stop();
|
||||||
|
};
|
||||||
|
|
||||||
|
instance.onend = () => {
|
||||||
|
isListening.value = false;
|
||||||
|
recognition = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
recognition = instance;
|
||||||
|
try {
|
||||||
|
recognition.start();
|
||||||
|
} catch {
|
||||||
|
options.onError('chat.voiceRecognitionFailed');
|
||||||
|
stop();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggle = (existingText = '') => {
|
||||||
|
if (isListening.value) {
|
||||||
|
stop();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
start(existingText);
|
||||||
|
};
|
||||||
|
|
||||||
|
onBeforeUnmount(stop);
|
||||||
|
|
||||||
|
return {
|
||||||
|
isListening,
|
||||||
|
isSupported,
|
||||||
|
start,
|
||||||
|
stop,
|
||||||
|
toggle,
|
||||||
|
};
|
||||||
|
}
|
||||||
+145
-1
@@ -1,4 +1,4 @@
|
|||||||
import { createI18n } from 'vue-i18n';
|
import { createI18n } from 'vue-i18n';
|
||||||
|
|
||||||
const messages = {
|
const messages = {
|
||||||
'en': {
|
'en': {
|
||||||
@@ -152,6 +152,28 @@ const messages = {
|
|||||||
confirm: 'OK'
|
confirm: 'OK'
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
errors: {
|
||||||
|
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.',
|
||||||
|
VALIDATION_INVALID_PARAM: 'Invalid request parameters.',
|
||||||
|
USER_USERNAME_REQUIRED: 'Username is required.',
|
||||||
|
USER_USERNAME_EXISTS: 'Username already exists.',
|
||||||
|
USER_EMAIL_INVALID: 'Invalid email format.',
|
||||||
|
USER_EMAIL_EXISTS: 'Email already exists.',
|
||||||
|
USER_EMPLOYEE_ID_EXISTS: 'Employee ID already exists.',
|
||||||
|
USER_PHONE_EXISTS: 'Phone number already exists.',
|
||||||
|
USER_UNIQUENESS_CONFLICT: 'Data uniqueness conflict.',
|
||||||
|
SYSTEM_INTERNAL_ERROR: 'Internal server error. Please try again later.',
|
||||||
|
SYSTEM_HTTP_ERROR: 'Request failed.',
|
||||||
|
}
|
||||||
|
},
|
||||||
scheduleRuns: {
|
scheduleRuns: {
|
||||||
title: 'Schedule Runs',
|
title: 'Schedule Runs',
|
||||||
refresh: 'Refresh',
|
refresh: 'Refresh',
|
||||||
@@ -524,7 +546,11 @@ const messages = {
|
|||||||
confirmClean: 'Are you sure you want to delete all REJECTED users?',
|
confirmClean: 'Are you sure you want to delete all REJECTED users?',
|
||||||
confirmBatchDelete: 'Are you sure you want to delete {count} users?',
|
confirmBatchDelete: 'Are you sure you want to delete {count} users?',
|
||||||
msgs: {
|
msgs: {
|
||||||
|
realNameRequired: 'Real name is required',
|
||||||
|
employeeIdRequired: 'Employee ID is required',
|
||||||
|
phoneRequired: 'Phone number is required',
|
||||||
usernameRequired: 'Username is required',
|
usernameRequired: 'Username is required',
|
||||||
|
emailRequired: 'Email is required',
|
||||||
passwordRequired: 'Password is required for new users',
|
passwordRequired: 'Password is required for new users',
|
||||||
invalidEmail: 'Invalid email format',
|
invalidEmail: 'Invalid email format',
|
||||||
created: 'User created successfully',
|
created: 'User created successfully',
|
||||||
@@ -1231,6 +1257,16 @@ const messages = {
|
|||||||
welcomeTitle: 'Hello, I am Hexin AI Digital Human',
|
welcomeTitle: 'Hello, I am Hexin AI Digital Human',
|
||||||
askAnything: 'Ask me anything...',
|
askAnything: 'Ask me anything...',
|
||||||
voiceFeature: 'Voice feature',
|
voiceFeature: 'Voice feature',
|
||||||
|
voiceListening: 'Listening...',
|
||||||
|
voiceStop: 'Stop voice input',
|
||||||
|
voiceNotSupported: 'Voice input is not supported in this browser',
|
||||||
|
voiceRequiresHttps: 'Voice input requires HTTPS or localhost access',
|
||||||
|
voicePermissionDenied: 'Microphone permission denied. Allow it in browser settings',
|
||||||
|
voiceNoSpeech: 'No speech detected. Please try again',
|
||||||
|
voiceAudioCapture: 'Unable to access microphone',
|
||||||
|
voiceNetworkError: 'Voice recognition network error',
|
||||||
|
voiceServiceNotAllowed: 'Voice recognition service is not allowed',
|
||||||
|
voiceRecognitionFailed: 'Voice recognition failed. Please try again',
|
||||||
collapseBrowser: 'Collapse Browser',
|
collapseBrowser: 'Collapse Browser',
|
||||||
openBrowser: 'Open Browser',
|
openBrowser: 'Open Browser',
|
||||||
kb: {
|
kb: {
|
||||||
@@ -1606,6 +1642,28 @@ const messages = {
|
|||||||
confirm: '确定'
|
confirm: '确定'
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
errors: {
|
||||||
|
generic: '请求失败。',
|
||||||
|
codes: {
|
||||||
|
AUTH_UNAUTHORIZED: '请先登录。',
|
||||||
|
AUTH_INCORRECT_PASSWORD: '密码错误',
|
||||||
|
AUTH_USER_NOT_FOUND: '用户不存在',
|
||||||
|
AUTH_ACCOUNT_DISABLED: '账号已禁用',
|
||||||
|
AUTH_FORBIDDEN: '你没有权限执行该操作。',
|
||||||
|
RESOURCE_NOT_FOUND: '请求的资源不存在。',
|
||||||
|
RESOURCE_CONFLICT: '请求冲突,请刷新后重试。',
|
||||||
|
VALIDATION_INVALID_PARAM: '请求参数不合法。',
|
||||||
|
USER_USERNAME_REQUIRED: '用户名必填。',
|
||||||
|
USER_USERNAME_EXISTS: '用户名已存在。',
|
||||||
|
USER_EMAIL_INVALID: '邮箱格式不正确。',
|
||||||
|
USER_EMAIL_EXISTS: '邮箱已存在。',
|
||||||
|
USER_EMPLOYEE_ID_EXISTS: '工号已存在。',
|
||||||
|
USER_PHONE_EXISTS: '手机号已存在。',
|
||||||
|
USER_UNIQUENESS_CONFLICT: '数据唯一性冲突。',
|
||||||
|
SYSTEM_INTERNAL_ERROR: '服务器内部错误,请稍后重试。',
|
||||||
|
SYSTEM_HTTP_ERROR: '请求失败。',
|
||||||
|
}
|
||||||
|
},
|
||||||
scheduleRuns: {
|
scheduleRuns: {
|
||||||
title: '排程记录',
|
title: '排程记录',
|
||||||
refresh: '刷新',
|
refresh: '刷新',
|
||||||
@@ -1979,7 +2037,11 @@ const messages = {
|
|||||||
confirmClean: '确定要删除所有“已拒绝”的用户吗?',
|
confirmClean: '确定要删除所有“已拒绝”的用户吗?',
|
||||||
confirmBatchDelete: '确定要删除选中的 {count} 个用户吗?',
|
confirmBatchDelete: '确定要删除选中的 {count} 个用户吗?',
|
||||||
msgs: {
|
msgs: {
|
||||||
|
realNameRequired: '真实姓名必填',
|
||||||
|
employeeIdRequired: '工号必填',
|
||||||
|
phoneRequired: '手机号必填',
|
||||||
usernameRequired: '用户名必填',
|
usernameRequired: '用户名必填',
|
||||||
|
emailRequired: '邮箱必填',
|
||||||
passwordRequired: '新用户必须设置密码',
|
passwordRequired: '新用户必须设置密码',
|
||||||
invalidEmail: '邮箱格式不正确',
|
invalidEmail: '邮箱格式不正确',
|
||||||
created: '用户创建成功',
|
created: '用户创建成功',
|
||||||
@@ -2665,6 +2727,16 @@ const messages = {
|
|||||||
welcomeTitle: '你好,我是和信AI数字人',
|
welcomeTitle: '你好,我是和信AI数字人',
|
||||||
askAnything: '问我任何事...',
|
askAnything: '问我任何事...',
|
||||||
voiceFeature: '语音功能',
|
voiceFeature: '语音功能',
|
||||||
|
voiceListening: '正在聆听…',
|
||||||
|
voiceStop: '停止语音输入',
|
||||||
|
voiceNotSupported: '当前浏览器不支持语音输入',
|
||||||
|
voiceRequiresHttps: '语音输入需要 HTTPS 或 localhost 访问',
|
||||||
|
voicePermissionDenied: '麦克风权限被拒绝,请在浏览器设置中允许',
|
||||||
|
voiceNoSpeech: '未检测到语音,请重试',
|
||||||
|
voiceAudioCapture: '无法访问麦克风',
|
||||||
|
voiceNetworkError: '语音识别网络错误',
|
||||||
|
voiceServiceNotAllowed: '不允许使用语音识别服务',
|
||||||
|
voiceRecognitionFailed: '语音识别失败,请重试',
|
||||||
collapseBrowser: '收起浏览器',
|
collapseBrowser: '收起浏览器',
|
||||||
openBrowser: '打开浏览器',
|
openBrowser: '打开浏览器',
|
||||||
kb: {
|
kb: {
|
||||||
@@ -3024,6 +3096,28 @@ const messages = {
|
|||||||
confirm: '確定'
|
confirm: '確定'
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
errors: {
|
||||||
|
generic: '請求失敗。',
|
||||||
|
codes: {
|
||||||
|
AUTH_UNAUTHORIZED: '請先登入。',
|
||||||
|
AUTH_INCORRECT_PASSWORD: '密碼錯誤',
|
||||||
|
AUTH_USER_NOT_FOUND: '用戶不存在',
|
||||||
|
AUTH_ACCOUNT_DISABLED: '帳號已禁用',
|
||||||
|
AUTH_FORBIDDEN: '你沒有權限執行此操作。',
|
||||||
|
RESOURCE_NOT_FOUND: '請求的資源不存在。',
|
||||||
|
RESOURCE_CONFLICT: '請求衝突,請刷新後重試。',
|
||||||
|
VALIDATION_INVALID_PARAM: '請求參數不合法。',
|
||||||
|
USER_USERNAME_REQUIRED: '用戶名必填。',
|
||||||
|
USER_USERNAME_EXISTS: '用戶名已存在。',
|
||||||
|
USER_EMAIL_INVALID: '郵箱格式不正確。',
|
||||||
|
USER_EMAIL_EXISTS: '郵箱已存在。',
|
||||||
|
USER_EMPLOYEE_ID_EXISTS: '工號已存在。',
|
||||||
|
USER_PHONE_EXISTS: '手機號已存在。',
|
||||||
|
USER_UNIQUENESS_CONFLICT: '數據唯一性衝突。',
|
||||||
|
SYSTEM_INTERNAL_ERROR: '伺服器內部錯誤,請稍後重試。',
|
||||||
|
SYSTEM_HTTP_ERROR: '請求失敗。',
|
||||||
|
}
|
||||||
|
},
|
||||||
scheduleRuns: {
|
scheduleRuns: {
|
||||||
title: '排程記錄',
|
title: '排程記錄',
|
||||||
refresh: '刷新',
|
refresh: '刷新',
|
||||||
@@ -3397,7 +3491,11 @@ const messages = {
|
|||||||
confirmClean: '確定要刪除所有“已拒絕”的用戶嗎?',
|
confirmClean: '確定要刪除所有“已拒絕”的用戶嗎?',
|
||||||
confirmBatchDelete: '確定要刪除選中的 {count} 個用戶嗎?',
|
confirmBatchDelete: '確定要刪除選中的 {count} 個用戶嗎?',
|
||||||
msgs: {
|
msgs: {
|
||||||
|
realNameRequired: '真實姓名必填',
|
||||||
|
employeeIdRequired: '工號必填',
|
||||||
|
phoneRequired: '手機號必填',
|
||||||
usernameRequired: '用戶名必填',
|
usernameRequired: '用戶名必填',
|
||||||
|
emailRequired: '郵箱必填',
|
||||||
passwordRequired: '新用戶必須設置密碼',
|
passwordRequired: '新用戶必須設置密碼',
|
||||||
invalidEmail: '郵箱格式不正確',
|
invalidEmail: '郵箱格式不正確',
|
||||||
created: '用戶創建成功',
|
created: '用戶創建成功',
|
||||||
@@ -3958,6 +4056,16 @@ const messages = {
|
|||||||
welcomeTitle: '你好,我是和信AI數字人',
|
welcomeTitle: '你好,我是和信AI數字人',
|
||||||
askAnything: '問我任何事...',
|
askAnything: '問我任何事...',
|
||||||
voiceFeature: '語音功能',
|
voiceFeature: '語音功能',
|
||||||
|
voiceListening: '正在聆聽…',
|
||||||
|
voiceStop: '停止語音輸入',
|
||||||
|
voiceNotSupported: '目前瀏覽器不支援語音輸入',
|
||||||
|
voiceRequiresHttps: '語音輸入需要 HTTPS 或 localhost 存取',
|
||||||
|
voicePermissionDenied: '麥克風權限被拒絕,請在瀏覽器設定中允許',
|
||||||
|
voiceNoSpeech: '未偵測到語音,請重試',
|
||||||
|
voiceAudioCapture: '無法存取麥克風',
|
||||||
|
voiceNetworkError: '語音辨識網路錯誤',
|
||||||
|
voiceServiceNotAllowed: '不允許使用語音辨識服務',
|
||||||
|
voiceRecognitionFailed: '語音辨識失敗,請重試',
|
||||||
collapseBrowser: '收起瀏覽器',
|
collapseBrowser: '收起瀏覽器',
|
||||||
openBrowser: '打開瀏覽器',
|
openBrowser: '打開瀏覽器',
|
||||||
kb: {
|
kb: {
|
||||||
@@ -4317,6 +4425,28 @@ const messages = {
|
|||||||
confirm: 'ตกลง'
|
confirm: 'ตกลง'
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
errors: {
|
||||||
|
generic: 'คำขอล้มเหลว',
|
||||||
|
codes: {
|
||||||
|
AUTH_UNAUTHORIZED: 'กรุณาเข้าสู่ระบบก่อน',
|
||||||
|
AUTH_INCORRECT_PASSWORD: 'รหัสผ่านไม่ถูกต้อง',
|
||||||
|
AUTH_USER_NOT_FOUND: 'ไม่พบผู้ใช้',
|
||||||
|
AUTH_ACCOUNT_DISABLED: 'บัญชีถูกปิดใช้งาน',
|
||||||
|
AUTH_FORBIDDEN: 'คุณไม่มีสิทธิ์ดำเนินการนี้',
|
||||||
|
RESOURCE_NOT_FOUND: 'ไม่พบทรัพยากรที่ร้องขอ',
|
||||||
|
RESOURCE_CONFLICT: 'คำขอขัดแย้ง โปรดรีเฟรชแล้วลองใหม่',
|
||||||
|
VALIDATION_INVALID_PARAM: 'พารามิเตอร์คำขอไม่ถูกต้อง',
|
||||||
|
USER_USERNAME_REQUIRED: 'กรุณากรอกชื่อผู้ใช้',
|
||||||
|
USER_USERNAME_EXISTS: 'ชื่อผู้ใช้นี้มีอยู่แล้ว',
|
||||||
|
USER_EMAIL_INVALID: 'รูปแบบอีเมลไม่ถูกต้อง',
|
||||||
|
USER_EMAIL_EXISTS: 'อีเมลนี้มีอยู่แล้ว',
|
||||||
|
USER_EMPLOYEE_ID_EXISTS: 'รหัสพนักงานนี้มีอยู่แล้ว',
|
||||||
|
USER_PHONE_EXISTS: 'หมายเลขโทรศัพท์นี้มีอยู่แล้ว',
|
||||||
|
USER_UNIQUENESS_CONFLICT: 'ข้อมูลซ้ำกัน',
|
||||||
|
SYSTEM_INTERNAL_ERROR: 'เซิร์ฟเวอร์ขัดข้อง กรุณาลองใหม่ภายหลัง',
|
||||||
|
SYSTEM_HTTP_ERROR: 'คำขอล้มเหลว',
|
||||||
|
}
|
||||||
|
},
|
||||||
scheduleRuns: {
|
scheduleRuns: {
|
||||||
title: 'บันทึกการตั้งเวลา',
|
title: 'บันทึกการตั้งเวลา',
|
||||||
refresh: 'รีเฟรช',
|
refresh: 'รีเฟรช',
|
||||||
@@ -4607,7 +4737,11 @@ const messages = {
|
|||||||
confirmClean: 'คุณแน่ใจหรือไม่ว่าต้องการลบผู้ใช้ที่ถูกปฏิเสธทั้งหมด?',
|
confirmClean: 'คุณแน่ใจหรือไม่ว่าต้องการลบผู้ใช้ที่ถูกปฏิเสธทั้งหมด?',
|
||||||
confirmBatchDelete: 'คุณแน่ใจหรือไม่ว่าต้องการลบผู้ใช้ {count} คน?',
|
confirmBatchDelete: 'คุณแน่ใจหรือไม่ว่าต้องการลบผู้ใช้ {count} คน?',
|
||||||
msgs: {
|
msgs: {
|
||||||
|
realNameRequired: 'กรุณากรอกชื่อจริง',
|
||||||
|
employeeIdRequired: 'กรุณากรอกรหัสพนักงาน',
|
||||||
|
phoneRequired: 'กรุณากรอกเบอร์โทรศัพท์',
|
||||||
usernameRequired: 'กรุณากรอกชื่อผู้ใช้',
|
usernameRequired: 'กรุณากรอกชื่อผู้ใช้',
|
||||||
|
emailRequired: 'กรุณากรอกอีเมล',
|
||||||
passwordRequired: 'ต้องระบุรหัสผ่านสำหรับผู้ใช้ใหม่',
|
passwordRequired: 'ต้องระบุรหัสผ่านสำหรับผู้ใช้ใหม่',
|
||||||
invalidEmail: 'รูปแบบอีเมลไม่ถูกต้อง',
|
invalidEmail: 'รูปแบบอีเมลไม่ถูกต้อง',
|
||||||
created: 'สร้างผู้ใช้สำเร็จ',
|
created: 'สร้างผู้ใช้สำเร็จ',
|
||||||
@@ -5168,6 +5302,16 @@ const messages = {
|
|||||||
welcomeTitle: 'สวัสดี ฉันคือ AI Digital Human ของ Hexin',
|
welcomeTitle: 'สวัสดี ฉันคือ AI Digital Human ของ Hexin',
|
||||||
askAnything: 'ถามฉันได้ทุกเรื่อง...',
|
askAnything: 'ถามฉันได้ทุกเรื่อง...',
|
||||||
voiceFeature: 'ฟีเจอร์เสียง',
|
voiceFeature: 'ฟีเจอร์เสียง',
|
||||||
|
voiceListening: 'กำลังฟัง...',
|
||||||
|
voiceStop: 'หยุดป้อนข้อมูลด้วยเสียง',
|
||||||
|
voiceNotSupported: 'เบราว์เซอร์นี้ไม่รองรับการป้อนข้อมูลด้วยเสียง',
|
||||||
|
voiceRequiresHttps: 'การป้อนข้อมูลด้วยเสียงต้องใช้ HTTPS หรือ localhost',
|
||||||
|
voicePermissionDenied: 'ไม่ได้รับอนุญาตให้ใช้ไมโครโฟน โปรดอนุญาตในการตั้งค่าเบราว์เซอร์',
|
||||||
|
voiceNoSpeech: 'ไม่พบเสียงพูด โปรดลองอีกครั้ง',
|
||||||
|
voiceAudioCapture: 'ไม่สามารถเข้าถึงไมโครโฟนได้',
|
||||||
|
voiceNetworkError: 'เกิดข้อผิดพลาดเครือข่ายในการรู้จำเสียง',
|
||||||
|
voiceServiceNotAllowed: 'ไม่อนุญาตให้ใช้บริการรู้จำเสียง',
|
||||||
|
voiceRecognitionFailed: 'การรู้จำเสียงล้มเหลว โปรดลองอีกครั้ง',
|
||||||
collapseBrowser: 'ย่อเบราว์เซอร์',
|
collapseBrowser: 'ย่อเบราว์เซอร์',
|
||||||
openBrowser: 'เปิดเบราว์เซอร์',
|
openBrowser: 'เปิดเบราว์เซอร์',
|
||||||
kb: {
|
kb: {
|
||||||
|
|||||||
+45
@@ -0,0 +1,45 @@
|
|||||||
|
interface SpeechRecognitionAlternative {
|
||||||
|
transcript: string;
|
||||||
|
confidence: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SpeechRecognitionResult {
|
||||||
|
readonly isFinal: boolean;
|
||||||
|
readonly length: number;
|
||||||
|
item(index: number): SpeechRecognitionAlternative;
|
||||||
|
[index: number]: SpeechRecognitionAlternative;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SpeechRecognitionResultList {
|
||||||
|
readonly length: number;
|
||||||
|
item(index: number): SpeechRecognitionResult;
|
||||||
|
[index: number]: SpeechRecognitionResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SpeechRecognitionEvent extends Event {
|
||||||
|
readonly resultIndex: number;
|
||||||
|
readonly results: SpeechRecognitionResultList;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SpeechRecognitionErrorEvent extends Event {
|
||||||
|
readonly error: string;
|
||||||
|
readonly message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SpeechRecognition extends EventTarget {
|
||||||
|
continuous: boolean;
|
||||||
|
interimResults: boolean;
|
||||||
|
lang: string;
|
||||||
|
start(): void;
|
||||||
|
stop(): void;
|
||||||
|
abort(): void;
|
||||||
|
onstart: ((this: SpeechRecognition, ev: Event) => void) | null;
|
||||||
|
onend: ((this: SpeechRecognition, ev: Event) => void) | null;
|
||||||
|
onresult: ((this: SpeechRecognition, ev: SpeechRecognitionEvent) => void) | null;
|
||||||
|
onerror: ((this: SpeechRecognition, ev: SpeechRecognitionErrorEvent) => void) | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Window {
|
||||||
|
SpeechRecognition?: new () => SpeechRecognition;
|
||||||
|
webkitSpeechRecognition?: new () => SpeechRecognition;
|
||||||
|
}
|
||||||
+297
-502
File diff suppressed because it is too large.
Load diff
+686
-156
File diff suppressed because it is too large.
Load diff
@@ -3,6 +3,7 @@ import { ref } from 'vue';
|
|||||||
import { useRoute, useRouter } from 'vue-router';
|
import { useRoute, useRouter } from 'vue-router';
|
||||||
import { Lock, AlertCircle, CheckCircle } from 'lucide-vue-next';
|
import { Lock, AlertCircle, CheckCircle } from 'lucide-vue-next';
|
||||||
import MinimalShell from '../layouts/MinimalShell.vue';
|
import MinimalShell from '../layouts/MinimalShell.vue';
|
||||||
|
import { resetPasswordConfirm } from '../api/user';
|
||||||
|
|
||||||
const route = useRoute();
|
const route = useRoute();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -32,29 +33,15 @@ const handleReset = async () => {
|
|||||||
message.value = '';
|
message.value = '';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/user/reset-password-confirm', {
|
await resetPasswordConfirm(token.value, password.value);
|
||||||
method: 'POST',
|
status.value = 'success';
|
||||||
headers: { 'Content-Type': 'application/json' },
|
message.value = 'Password reset successfully! Redirecting to login...';
|
||||||
body: JSON.stringify({
|
setTimeout(() => {
|
||||||
token: token.value,
|
router.push('/');
|
||||||
new_password: password.value
|
}, 3000);
|
||||||
})
|
} catch (e) {
|
||||||
});
|
|
||||||
|
|
||||||
const data = await res.json();
|
|
||||||
if (res.ok) {
|
|
||||||
status.value = 'success';
|
|
||||||
message.value = 'Password reset successfully! Redirecting to login...';
|
|
||||||
setTimeout(() => {
|
|
||||||
router.push('/');
|
|
||||||
}, 3000);
|
|
||||||
} else {
|
|
||||||
status.value = 'error';
|
|
||||||
message.value = data.error || 'Failed to reset password';
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
status.value = 'error';
|
status.value = 'error';
|
||||||
message.value = 'Network error occurred';
|
message.value = (e as Error).message || 'Failed to reset password';
|
||||||
} finally {
|
} finally {
|
||||||
isLoading.value = false;
|
isLoading.value = false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
/**
|
/**
|
||||||
* WorkspaceView.vue
|
* WorkspaceView.vue
|
||||||
* 文件用途:用户工作台,支持自定义布局、收藏、嵌入 Agent
|
* 文件用途:用户工作台,支持自定义布局、收藏、嵌入 Agent
|
||||||
@@ -57,6 +57,7 @@ import {
|
|||||||
|
|
||||||
import KbWorkspaceView from './KbWorkspaceView.vue';
|
import KbWorkspaceView from './KbWorkspaceView.vue';
|
||||||
import { listWorkspaceScheduleRuns, workspaceRunExcelUrl, type ScheduleRun } from '../api/schedule';
|
import { listWorkspaceScheduleRuns, workspaceRunExcelUrl, type ScheduleRun } from '../api/schedule';
|
||||||
|
import { BusinessError, requestJson } from '../api/client';
|
||||||
import { Clock, Download, Search, RefreshCw } from 'lucide-vue-next';
|
import { Clock, Download, Search, RefreshCw } from 'lucide-vue-next';
|
||||||
|
|
||||||
const { t, locale } = useI18n();
|
const { t, locale } = useI18n();
|
||||||
@@ -202,23 +203,17 @@ const handleForgotPassword = async () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/user/reset-password-by-email', {
|
await requestJson('/api/user/reset-password-by-email', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(forgotPasswordForm.value)
|
body: JSON.stringify(forgotPasswordForm.value)
|
||||||
});
|
});
|
||||||
|
msg.success(t('login.passwordResetEmailSent'));
|
||||||
const data = await res.json();
|
showForgotPasswordModal.value = false;
|
||||||
if (res.ok) {
|
forgotPasswordForm.value = { email: '' };
|
||||||
msg.success(t('login.passwordResetEmailSent'));
|
|
||||||
showForgotPasswordModal.value = false;
|
|
||||||
forgotPasswordForm.value = { email: '' };
|
|
||||||
} else {
|
|
||||||
msg.error(data.error || t('login.passwordResetRequestFailed'));
|
|
||||||
}
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Password reset error', e);
|
console.error('Password reset error', e);
|
||||||
msg.error(t('common.errorOccurred'));
|
msg.error((e as Error)?.message || t('login.passwordResetRequestFailed'));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -279,13 +274,10 @@ const getSectionTitleKey = (sectionId: string) => {
|
|||||||
// Methods
|
// Methods
|
||||||
const fetchHome = async () => {
|
const fetchHome = async () => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/user/home', { headers: getAuthHeaders() });
|
const data = await requestJson<any>('/api/user/home', { headers: getAuthHeaders() });
|
||||||
if (res.status === 401) {
|
if (!data) {
|
||||||
msg.error(t('login.loginRequired'));
|
throw new Error('Missing /api/user/home payload');
|
||||||
handleLogout();
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
const data = await res.json();
|
|
||||||
currentUser.value = {
|
currentUser.value = {
|
||||||
id: data.user.id,
|
id: data.user.id,
|
||||||
username: data.user.username,
|
username: data.user.username,
|
||||||
@@ -357,6 +349,11 @@ return;
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
if ((e as BusinessError)?.status === 401) {
|
||||||
|
msg.error(t('login.loginRequired'));
|
||||||
|
handleLogout();
|
||||||
|
return;
|
||||||
|
}
|
||||||
console.error('Failed to load user home', e);
|
console.error('Failed to load user home', e);
|
||||||
} finally {
|
} finally {
|
||||||
isLoading.value = false;
|
isLoading.value = false;
|
||||||
@@ -365,12 +362,7 @@ return;
|
|||||||
|
|
||||||
const fetchPublicAgents = async () => {
|
const fetchPublicAgents = async () => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/agents/public');
|
publicAgents.value = await requestJson<Agent[]>('/api/agents/public');
|
||||||
if (res.ok) {
|
|
||||||
publicAgents.value = await res.json();
|
|
||||||
} else {
|
|
||||||
publicAgents.value = [];
|
|
||||||
}
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
publicAgents.value = [];
|
publicAgents.value = [];
|
||||||
}
|
}
|
||||||
@@ -378,10 +370,7 @@ const fetchPublicAgents = async () => {
|
|||||||
|
|
||||||
const fetchAnnouncements = async () => {
|
const fetchAnnouncements = async () => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/user/announcements');
|
announcements.value = await requestJson<Announcement[]>('/api/user/announcements');
|
||||||
if (res.ok) {
|
|
||||||
announcements.value = await res.json();
|
|
||||||
}
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Failed to load announcements', e);
|
console.error('Failed to load announcements', e);
|
||||||
}
|
}
|
||||||
@@ -448,7 +437,7 @@ const handleLogin = async (event?: Event) => {
|
|||||||
const loginApi = isCasdoorMode
|
const loginApi = isCasdoorMode
|
||||||
? (config.auth?.casdoor?.passwordLoginApi || '/api/user/casdoor/password-login')
|
? (config.auth?.casdoor?.passwordLoginApi || '/api/user/casdoor/password-login')
|
||||||
: '/api/user/login';
|
: '/api/user/login';
|
||||||
const res = await fetch(loginApi, {
|
const user = await requestJson<any>(loginApi, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
@@ -457,31 +446,6 @@ const handleLogin = async (event?: Event) => {
|
|||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!res.ok) {
|
|
||||||
const err = await res.json();
|
|
||||||
// Handle specific error messages if needed, or just alert
|
|
||||||
let msg = err.error || t('login.failed');
|
|
||||||
if (isCasdoorMode) {
|
|
||||||
if (err.error_code === 'CASDOOR_USER_NOT_FOUND') {
|
|
||||||
msg = t('workspace.msg.casdoorNotMatchedContactAdmin');
|
|
||||||
} else if (err.error_code === 'ACCOUNT_DISABLED') {
|
|
||||||
msg = t('login.accountDisabled');
|
|
||||||
} else if (String(err.error || '').includes('invalid_grant')) {
|
|
||||||
msg = t('login.incorrectPassword');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (err.error === 'User not found') msg = t('login.userNotFound');
|
|
||||||
if (err.error === 'Incorrect password') msg = t('login.incorrectPassword');
|
|
||||||
if (err.error === 'Account is disabled') msg = t('login.accountDisabled');
|
|
||||||
if (err.error === 'Database connection failed') msg = t('login.dbConnectionFailed');
|
|
||||||
if (err.error === 'Internal server error') msg = t('login.internalError');
|
|
||||||
|
|
||||||
msg.error(msg);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const user = await res.json();
|
|
||||||
|
|
||||||
persistLoginUser(user);
|
persistLoginUser(user);
|
||||||
|
|
||||||
await fetchHome();
|
await fetchHome();
|
||||||
@@ -489,8 +453,27 @@ const handleLogin = async (event?: Event) => {
|
|||||||
pendingAgentId.value = null;
|
pendingAgentId.value = null;
|
||||||
await router.replace(`/chat/${DEFAULT_POST_LOGIN_AGENT_ID}`);
|
await router.replace(`/chat/${DEFAULT_POST_LOGIN_AGENT_ID}`);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
const err = e as BusinessError;
|
||||||
|
const rawError = String(err.message || '');
|
||||||
|
const errorCode = String(err.code || '');
|
||||||
|
let errorText = rawError || t('login.failed');
|
||||||
|
const loginMode = String(config.auth?.loginMode || 'casdoor').toLowerCase();
|
||||||
|
if (loginMode === 'casdoor') {
|
||||||
|
if (errorCode === 'CASDOOR_USER_NOT_FOUND') {
|
||||||
|
errorText = t('workspace.msg.casdoorNotMatchedContactAdmin');
|
||||||
|
} else if (errorCode === 'ACCOUNT_DISABLED') {
|
||||||
|
errorText = t('login.accountDisabled');
|
||||||
|
} else if (rawError.includes('invalid_grant')) {
|
||||||
|
errorText = t('login.incorrectPassword');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (rawError === 'User not found') errorText = t('login.userNotFound');
|
||||||
|
if (rawError === 'Incorrect password') errorText = t('login.incorrectPassword');
|
||||||
|
if (rawError === 'Account is disabled') errorText = t('login.accountDisabled');
|
||||||
|
if (rawError === 'Database connection failed') errorText = t('login.dbConnectionFailed');
|
||||||
|
if (rawError === 'Internal server error') errorText = t('login.internalError');
|
||||||
console.error(e);
|
console.error(e);
|
||||||
msg.error(t('login.requestFailed'));
|
msg.error(errorText || t('login.requestFailed'));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -519,24 +502,11 @@ const tryCasdoorCallbackLogin = async () => {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const api = config.auth.casdoor.loginApi || '/api/user/casdoor/login';
|
const api = config.auth.casdoor.loginApi || '/api/user/casdoor/login';
|
||||||
const res = await fetch(api, {
|
const data = await requestJson<any>(api, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ code, state }),
|
body: JSON.stringify({ code, state }),
|
||||||
});
|
});
|
||||||
const data = await res.json();
|
|
||||||
if (!res.ok) {
|
|
||||||
const code = String(data.error_code || '');
|
|
||||||
let msg = data.error || 'Casdoor login failed';
|
|
||||||
if (code === 'CASDOOR_USER_NOT_FOUND') {
|
|
||||||
msg = t('workspace.msg.casdoorNotMatchedNeedLocalUser');
|
|
||||||
} else if (code === 'ACCOUNT_DISABLED') {
|
|
||||||
msg = t('workspace.msg.localAccountDisabled');
|
|
||||||
}
|
|
||||||
msg.error(msg);
|
|
||||||
clearWecomCallbackQuery();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
// Persist access+refresh tokens for API auth and silent refresh.
|
// Persist access+refresh tokens for API auth and silent refresh.
|
||||||
persistLoginUser(data);
|
persistLoginUser(data);
|
||||||
sessionStorage.removeItem('hxops_casdoor_state');
|
sessionStorage.removeItem('hxops_casdoor_state');
|
||||||
@@ -544,8 +514,15 @@ const tryCasdoorCallbackLogin = async () => {
|
|||||||
await fetchHome();
|
await fetchHome();
|
||||||
return true;
|
return true;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
const err = e as BusinessError;
|
||||||
|
if (err.code === 'CASDOOR_USER_NOT_FOUND') {
|
||||||
|
msg.error(t('workspace.msg.casdoorNotMatchedNeedLocalUser'));
|
||||||
|
} else if (err.code === 'ACCOUNT_DISABLED') {
|
||||||
|
msg.error(t('workspace.msg.localAccountDisabled'));
|
||||||
|
} else {
|
||||||
|
msg.error(err.message || 'Casdoor login failed');
|
||||||
|
}
|
||||||
console.error(e);
|
console.error(e);
|
||||||
msg.error('Casdoor login failed');
|
|
||||||
clearWecomCallbackQuery();
|
clearWecomCallbackQuery();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -572,10 +549,9 @@ const handleWecomLogin = async () => {
|
|||||||
if (hint) {
|
if (hint) {
|
||||||
qs.set('provider_hint', hint);
|
qs.set('provider_hint', hint);
|
||||||
}
|
}
|
||||||
const res = await fetch(`${api}?${qs.toString()}`);
|
const data = await requestJson<any>(`${api}?${qs.toString()}`);
|
||||||
const data = await res.json();
|
if (!data?.url) {
|
||||||
if (!res.ok || !data.url) {
|
msg.error(t('login.wecomStartFailed'));
|
||||||
msg.error(data.error || t('login.wecomStartFailed'));
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (data.state) {
|
if (data.state) {
|
||||||
@@ -587,10 +563,9 @@ const handleWecomLogin = async () => {
|
|||||||
|
|
||||||
const redirectUri = `${window.location.origin}${wecomCfg.callbackPath || '/workspace'}`;
|
const redirectUri = `${window.location.origin}${wecomCfg.callbackPath || '/workspace'}`;
|
||||||
const api = wecomCfg.authorizeApi || '/api/user/wecom/authorize-url';
|
const api = wecomCfg.authorizeApi || '/api/user/wecom/authorize-url';
|
||||||
const res = await fetch(`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`);
|
const data = await requestJson<any>(`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`);
|
||||||
const data = await res.json();
|
if (!data?.url) {
|
||||||
if (!res.ok || !data.url) {
|
msg.error(t('login.wecomStartFailed'));
|
||||||
msg.error(data.error || t('login.wecomStartFailed'));
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (data.state) {
|
if (data.state) {
|
||||||
@@ -599,7 +574,7 @@ const handleWecomLogin = async () => {
|
|||||||
window.location.href = data.url;
|
window.location.href = data.url;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
msg.error(t('login.wecomStartFailed'));
|
msg.error((e as Error)?.message || t('login.wecomStartFailed'));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -645,7 +620,7 @@ const submitWecomCompleteBind = async () => {
|
|||||||
wecomBindPrompt.value.error = '';
|
wecomBindPrompt.value.error = '';
|
||||||
try {
|
try {
|
||||||
const api = config.auth.wecom.completeBindApi || '/api/user/wecom/complete-bind';
|
const api = config.auth.wecom.completeBindApi || '/api/user/wecom/complete-bind';
|
||||||
const res = await fetch(api, {
|
const data = await requestJson<any>(api, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
@@ -654,15 +629,6 @@ const submitWecomCompleteBind = async () => {
|
|||||||
value: wecomBindPrompt.value.value.trim(),
|
value: wecomBindPrompt.value.value.trim(),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
const data = await res.json();
|
|
||||||
if (!res.ok) {
|
|
||||||
wecomBindPrompt.value.error = formatWecomBindPromptError(data);
|
|
||||||
if (String(data.error_code || '') === 'WECOM_BIND_SESSION_EXPIRED') {
|
|
||||||
openWecomLoginDialog(data);
|
|
||||||
wecomBindPrompt.value = null;
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
wecomLoginDialog.value = null;
|
wecomLoginDialog.value = null;
|
||||||
persistLoginUser(data);
|
persistLoginUser(data);
|
||||||
@@ -671,10 +637,19 @@ const submitWecomCompleteBind = async () => {
|
|||||||
window.history.replaceState({}, '', '/workspace');
|
window.history.replaceState({}, '', '/workspace');
|
||||||
await fetchHome();
|
await fetchHome();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
const err = e as BusinessError;
|
||||||
if (wecomBindPrompt.value) {
|
if (wecomBindPrompt.value) {
|
||||||
wecomBindPrompt.value.error = t('login.wecomLoginFailed');
|
const errorPayload = {
|
||||||
|
error: err.message,
|
||||||
|
error_code: err.code,
|
||||||
|
};
|
||||||
|
wecomBindPrompt.value.error = formatWecomBindPromptError(errorPayload);
|
||||||
|
if (String(err.code || '') === 'WECOM_BIND_SESSION_EXPIRED') {
|
||||||
|
openWecomLoginDialog(errorPayload);
|
||||||
|
wecomBindPrompt.value = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
console.error(e);
|
||||||
} finally {
|
} finally {
|
||||||
if (wecomBindPrompt.value) {
|
if (wecomBindPrompt.value) {
|
||||||
wecomBindPrompt.value.submitting = false;
|
wecomBindPrompt.value.submitting = false;
|
||||||
@@ -706,33 +681,11 @@ const tryWecomCallbackLogin = async () => {
|
|||||||
isWecomLoggingIn.value = true;
|
isWecomLoggingIn.value = true;
|
||||||
try {
|
try {
|
||||||
const api = config.auth.wecom.loginApi || '/api/user/wecom/login';
|
const api = config.auth.wecom.loginApi || '/api/user/wecom/login';
|
||||||
const res = await fetch(api, {
|
const data = await requestJson<any>(api, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify({ code, state }),
|
body: JSON.stringify({ code, state }),
|
||||||
});
|
});
|
||||||
const data = await res.json();
|
|
||||||
if (!res.ok) {
|
|
||||||
const rawError = String(data.error || '');
|
|
||||||
let friendly = rawError || t('login.wecomLoginFailed');
|
|
||||||
if (rawError.includes('Invalid or expired WeCom state')) {
|
|
||||||
friendly = t('login.wecomStateExpired');
|
|
||||||
} else if (rawError.includes('bind WeCom account') || rawError.includes('No linked account found')) {
|
|
||||||
friendly = t('login.wecomBindRequired');
|
|
||||||
} else if (rawError.includes('Account is disabled')) {
|
|
||||||
friendly = t('login.wecomAccountDisabled');
|
|
||||||
}
|
|
||||||
msg.error(friendly);
|
|
||||||
sessionStorage.removeItem('hxops_wecom_state');
|
|
||||||
if (String(data.error_code || '') === 'WECOM_BIND_INPUT_REQUIRED') {
|
|
||||||
openWecomBindPrompt(data);
|
|
||||||
clearWecomCallbackQuery();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
openWecomLoginDialog(data);
|
|
||||||
clearWecomCallbackQuery();
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
wecomLoginDialog.value = null;
|
wecomLoginDialog.value = null;
|
||||||
persistLoginUser(data);
|
persistLoginUser(data);
|
||||||
@@ -741,10 +694,25 @@ const tryWecomCallbackLogin = async () => {
|
|||||||
await fetchHome();
|
await fetchHome();
|
||||||
return true;
|
return true;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
const err = e as BusinessError;
|
||||||
|
const rawError = String(err.message || '');
|
||||||
|
const errorCode = String(err.code || '');
|
||||||
|
let friendly = rawError || t('login.wecomLoginFailed');
|
||||||
|
if (rawError.includes('Invalid or expired WeCom state')) {
|
||||||
|
friendly = t('login.wecomStateExpired');
|
||||||
|
} else if (rawError.includes('bind WeCom account') || rawError.includes('No linked account found')) {
|
||||||
|
friendly = t('login.wecomBindRequired');
|
||||||
|
} else if (rawError.includes('Account is disabled')) {
|
||||||
|
friendly = t('login.wecomAccountDisabled');
|
||||||
|
}
|
||||||
console.error(e);
|
console.error(e);
|
||||||
msg.error(t('login.wecomLoginFailed'));
|
msg.error(friendly);
|
||||||
sessionStorage.removeItem('hxops_wecom_state');
|
sessionStorage.removeItem('hxops_wecom_state');
|
||||||
openWecomLoginDialog({ error: t('login.wecomLoginFailed') });
|
if (errorCode === 'WECOM_BIND_INPUT_REQUIRED') {
|
||||||
|
openWecomBindPrompt({ error: rawError, error_code: errorCode });
|
||||||
|
} else {
|
||||||
|
openWecomLoginDialog({ error: rawError || t('login.wecomLoginFailed'), error_code: errorCode });
|
||||||
|
}
|
||||||
clearWecomCallbackQuery();
|
clearWecomCallbackQuery();
|
||||||
return true;
|
return true;
|
||||||
} finally {
|
} finally {
|
||||||
@@ -759,23 +727,17 @@ const handleRegister = async () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/user/register', {
|
await requestJson('/api/user/register', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(registerForm.value)
|
body: JSON.stringify(registerForm.value)
|
||||||
});
|
});
|
||||||
|
msg.success(t('register.success'));
|
||||||
if (res.ok) {
|
showRegisterModal.value = false;
|
||||||
msg.success(t('register.success'));
|
registerForm.value = { username: '', password: '', email: '', real_name: '', employee_id: '', phone_number: '' };
|
||||||
showRegisterModal.value = false;
|
|
||||||
registerForm.value = { username: '', password: '', email: '', real_name: '', employee_id: '', phone_number: '' };
|
|
||||||
} else {
|
|
||||||
const err = await res.json();
|
|
||||||
msg.error(err.error || t('register.failed'));
|
|
||||||
}
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error('Register error:', e);
|
console.error('Register error:', e);
|
||||||
msg.error(t('register.requestFailed'));
|
msg.error((e as Error)?.message || t('register.requestFailed'));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -872,28 +834,14 @@ const captureOriginalProfile = () => {
|
|||||||
originalProfile.value = { ...profileUser.value };
|
originalProfile.value = { ...profileUser.value };
|
||||||
};
|
};
|
||||||
|
|
||||||
const parseErrorMessage = async (res: Response) => {
|
|
||||||
try {
|
|
||||||
const data = await res.json();
|
|
||||||
return data?.error || data?.message || '';
|
|
||||||
} catch {
|
|
||||||
try {
|
|
||||||
return await res.text();
|
|
||||||
} catch {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const fetchProfile = async () => {
|
const fetchProfile = async () => {
|
||||||
isProfileLoading.value = true;
|
isProfileLoading.value = true;
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/user/profile', { headers: getAuthHeaders() });
|
const data = await requestJson<any>('/api/user/profile', { headers: getAuthHeaders() });
|
||||||
if (!res.ok) {
|
if (!data) {
|
||||||
msg.error(t('workspace.profile.msg.loadFailed'));
|
msg.error(t('workspace.profile.msg.loadFailed'));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const data = await res.json();
|
|
||||||
profileUser.value = { ...profileUser.value, ...data };
|
profileUser.value = { ...profileUser.value, ...data };
|
||||||
if (data.language) locale.value = data.language;
|
if (data.language) locale.value = data.language;
|
||||||
if (data.theme_preference) {
|
if (data.theme_preference) {
|
||||||
@@ -952,24 +900,17 @@ const saveProfile = async () => {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
isProfileSaving.value = true;
|
isProfileSaving.value = true;
|
||||||
const res = await fetch('/api/user/profile', {
|
await requestJson('/api/user/profile', {
|
||||||
method: 'PUT',
|
method: 'PUT',
|
||||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!res.ok) {
|
|
||||||
const message = await parseErrorMessage(res);
|
|
||||||
msg.error(message || t('workspace.profile.msg.saveFailed'));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
msg.success(t('workspace.profile.msg.saved'));
|
msg.success(t('workspace.profile.msg.saved'));
|
||||||
captureOriginalProfile();
|
captureOriginalProfile();
|
||||||
isProfileEditing.value = false;
|
isProfileEditing.value = false;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
msg.error(t('workspace.profile.msg.saveFailed'));
|
msg.error((e as Error)?.message || t('workspace.profile.msg.saveFailed'));
|
||||||
} finally {
|
} finally {
|
||||||
isProfileSaving.value = false;
|
isProfileSaving.value = false;
|
||||||
}
|
}
|
||||||
@@ -982,7 +923,7 @@ const handleChangePassword = async () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/user/change-password', {
|
await requestJson('/api/user/change-password', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
@@ -990,19 +931,12 @@ const handleChangePassword = async () => {
|
|||||||
new_password: passwordForm.value.new,
|
new_password: passwordForm.value.new,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const data = await res.json();
|
|
||||||
if (!res.ok) {
|
|
||||||
msg.error(data.error || t('workspace.profile.msg.changePasswordFailed'));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
msg.success(t('profile.passwordChanged') || 'Password changed successfully');
|
msg.success(t('profile.passwordChanged') || 'Password changed successfully');
|
||||||
passwordForm.value = { current: '', new: '', confirm: '' };
|
passwordForm.value = { current: '', new: '', confirm: '' };
|
||||||
showPasswordModal.value = false;
|
showPasswordModal.value = false;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
msg.error(t('workspace.profile.msg.changePasswordFailed'));
|
msg.error((e as Error)?.message || t('workspace.profile.msg.changePasswordFailed'));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1147,19 +1081,14 @@ const isLoadingHistories = ref(false);
|
|||||||
const loadChatHistories = async () => {
|
const loadChatHistories = async () => {
|
||||||
isLoadingHistories.value = true;
|
isLoadingHistories.value = true;
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/agents', { headers: getAuthHeaders() });
|
const agentList = await requestJson<any[]>('/api/agents', { headers: getAuthHeaders() });
|
||||||
if (!res.ok) { isLoadingHistories.value = false; return; }
|
|
||||||
const agentList = await res.json();
|
|
||||||
const allHistories: ChatHistoryItem[] = [];
|
const allHistories: ChatHistoryItem[] = [];
|
||||||
await Promise.all(
|
await Promise.all(
|
||||||
(Array.isArray(agentList) ? agentList : []).map(async (agent: any) => {
|
(Array.isArray(agentList) ? agentList : []).map(async (agent: any) => {
|
||||||
try {
|
try {
|
||||||
const hRes = await fetch(`/api/chat/sessions?agent_id=${agent.id}`, { headers: getAuthHeaders() });
|
const sessions = await requestJson<any[]>(`/api/chat/sessions?agent_id=${agent.id}`, { headers: getAuthHeaders() });
|
||||||
if (hRes.ok) {
|
for (const s of (Array.isArray(sessions) ? sessions : [])) {
|
||||||
const sessions = await hRes.json();
|
allHistories.push({ ...s, agent_id: agent.id, agent_name: agent.name });
|
||||||
for (const s of sessions) {
|
|
||||||
allHistories.push({ ...s, agent_id: agent.id, agent_name: agent.name });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} catch {}
|
} catch {}
|
||||||
})
|
})
|
||||||
@@ -1214,7 +1143,7 @@ const handleWecomDeeplinkContext = async () => {
|
|||||||
if (traceId && isLoggedIn.value) {
|
if (traceId && isLoggedIn.value) {
|
||||||
try {
|
try {
|
||||||
const api = config.auth?.wecom?.deeplinkTraceApi || '/api/user/wecom/deeplink-opened';
|
const api = config.auth?.wecom?.deeplinkTraceApi || '/api/user/wecom/deeplink-opened';
|
||||||
await fetch(api, {
|
await requestJson(api, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||||
body: JSON.stringify({ trace_id: traceId }),
|
body: JSON.stringify({ trace_id: traceId }),
|
||||||
@@ -1242,14 +1171,18 @@ const handleWecomDeeplinkContext = async () => {
|
|||||||
|
|
||||||
// Favorites
|
// Favorites
|
||||||
const toggleFavorite = async (agentId: number) => {
|
const toggleFavorite = async (agentId: number) => {
|
||||||
if (favoriteAgentIds.value.includes(agentId)) {
|
try {
|
||||||
// Remove
|
if (favoriteAgentIds.value.includes(agentId)) {
|
||||||
await fetch(`/api/user/favorites/${agentId}`, { method: 'DELETE', headers: getAuthHeaders() });
|
// Remove
|
||||||
favoriteAgentIds.value = favoriteAgentIds.value.filter(id => id !== agentId);
|
await requestJson(`/api/user/favorites/${agentId}`, { method: 'DELETE', headers: getAuthHeaders() });
|
||||||
} else {
|
favoriteAgentIds.value = favoriteAgentIds.value.filter(id => id !== agentId);
|
||||||
// Add
|
} else {
|
||||||
await fetch(`/api/user/favorites/${agentId}`, { method: 'POST', headers: getAuthHeaders() });
|
// Add
|
||||||
favoriteAgentIds.value.push(agentId);
|
await requestJson(`/api/user/favorites/${agentId}`, { method: 'POST', headers: getAuthHeaders() });
|
||||||
|
favoriteAgentIds.value.push(agentId);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
msg.error((e as Error)?.message || t('common.errorOccurred'));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1293,18 +1226,17 @@ const saveQuickQuestion = async () => {
|
|||||||
|
|
||||||
const method = editingQuestionId.value ? 'PUT' : 'POST';
|
const method = editingQuestionId.value ? 'PUT' : 'POST';
|
||||||
|
|
||||||
const res = await fetch(url, {
|
try {
|
||||||
method: method,
|
await requestJson(url, {
|
||||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
method: method,
|
||||||
body: JSON.stringify(newQuestion.value),
|
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||||
});
|
body: JSON.stringify(newQuestion.value),
|
||||||
|
});
|
||||||
if (res.ok) {
|
|
||||||
await fetchHome();
|
await fetchHome();
|
||||||
isAddingQuestion.value = false;
|
isAddingQuestion.value = false;
|
||||||
editingQuestionId.value = null;
|
editingQuestionId.value = null;
|
||||||
} else {
|
} catch (e) {
|
||||||
msg.error(t('workspace.quickQuestions.msg.saveFailed'));
|
msg.error((e as Error)?.message || t('workspace.quickQuestions.msg.saveFailed'));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1316,10 +1248,14 @@ const removeQuickQuestion = async (id: number) => {
|
|||||||
|
|
||||||
const confirmRemoveQuickQuestion = async () => {
|
const confirmRemoveQuickQuestion = async () => {
|
||||||
if (pendingDeleteQuickQuestionId.value === null) return;
|
if (pendingDeleteQuickQuestionId.value === null) return;
|
||||||
await fetch(`/api/user/quick-questions/${pendingDeleteQuickQuestionId.value}`, { method: 'DELETE', headers: getAuthHeaders() });
|
try {
|
||||||
await fetchHome();
|
await requestJson(`/api/user/quick-questions/${pendingDeleteQuickQuestionId.value}`, { method: 'DELETE', headers: getAuthHeaders() });
|
||||||
pendingDeleteQuickQuestionId.value = null;
|
await fetchHome();
|
||||||
showDeleteQuickQuestionDialog.value = false;
|
pendingDeleteQuickQuestionId.value = null;
|
||||||
|
showDeleteQuickQuestionDialog.value = false;
|
||||||
|
} catch (e) {
|
||||||
|
msg.error((e as Error)?.message || t('workspace.quickQuestions.msg.saveFailed'));
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const cancelRemoveQuickQuestion = () => {
|
const cancelRemoveQuickQuestion = () => {
|
||||||
@@ -1330,13 +1266,17 @@ const cancelRemoveQuickQuestion = () => {
|
|||||||
// Drag & Drop
|
// Drag & Drop
|
||||||
const toggleSectionCollapse = async (section: LayoutSection) => {
|
const toggleSectionCollapse = async (section: LayoutSection) => {
|
||||||
section.collapsed = !section.collapsed;
|
section.collapsed = !section.collapsed;
|
||||||
|
|
||||||
// Save layout state
|
// Save layout state
|
||||||
await fetch('/api/user/homepage-layout', {
|
try {
|
||||||
method: 'PUT',
|
await requestJson('/api/user/homepage-layout', {
|
||||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
method: 'PUT',
|
||||||
body: JSON.stringify({ layout: { sections: layoutSections.value } })
|
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||||
});
|
body: JSON.stringify({ layout: { sections: layoutSections.value } })
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
msg.error((e as Error)?.message || t('common.errorOccurred'));
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const onDragStart = (index: number) => {
|
const onDragStart = (index: number) => {
|
||||||
@@ -1354,13 +1294,17 @@ const onDrop = async (index: number) => {
|
|||||||
layoutSections.value.splice(draggedSectionIndex.value, 1);
|
layoutSections.value.splice(draggedSectionIndex.value, 1);
|
||||||
layoutSections.value.splice(index, 0, draggedItem);
|
layoutSections.value.splice(index, 0, draggedItem);
|
||||||
draggedSectionIndex.value = null;
|
draggedSectionIndex.value = null;
|
||||||
|
|
||||||
// Save layout
|
// Save layout
|
||||||
await fetch('/api/user/homepage-layout', {
|
try {
|
||||||
method: 'PUT',
|
await requestJson('/api/user/homepage-layout', {
|
||||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
method: 'PUT',
|
||||||
body: JSON.stringify({ layout: { sections: layoutSections.value } })
|
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||||
});
|
body: JSON.stringify({ layout: { sections: layoutSections.value } })
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
msg.error((e as Error)?.message || t('common.errorOccurred'));
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const openAnnouncement = (ann: Announcement) => {
|
const openAnnouncement = (ann: Announcement) => {
|
||||||
|
|||||||
Reference in new issue
Block a user