fix(conflicts): Merge branch 'refator' into dev
This commit is contained in:
commit
7f126cfd52
24 files changed
+2314
-4223
No files matched your search
+118
-16
@@ -1,16 +1,18 @@
|
||||
|
||||
"""
|
||||
"""
|
||||
backend/app/__init__.py
|
||||
应用工厂
|
||||
应用工厂:创建 Flask 应用、注册蓝图并挂载全局异常与响应处理。
|
||||
"""
|
||||
import logging
|
||||
import uuid
|
||||
|
||||
from flask import Flask, jsonify, request
|
||||
from flask import Flask, jsonify, request, g
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
from flask_cors import CORS
|
||||
from werkzeug.exceptions import HTTPException
|
||||
from app.config import config
|
||||
from app.errors import AppError
|
||||
from app.response_utils import error_payload, utc_iso_now
|
||||
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
@@ -42,7 +44,7 @@ def create_app(config_name='default'):
|
||||
|
||||
db.init_app(app)
|
||||
migrate.init_app(app, db)
|
||||
CORS(app) # 允许跨域
|
||||
CORS(app) # 允许跨域
|
||||
|
||||
# 注册 Blueprints
|
||||
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')
|
||||
# 普通用户可见的 Agent 列表接口
|
||||
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||
# 当前用户相关接口(首页、常用问题等)
|
||||
# 当前用户相关接口(首页、常见问题等)
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
# 知识库/数据清洗模块接口
|
||||
# 知识库数据清洗模块接口
|
||||
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
||||
# 知识库外部集成接口(供聊天/外部系统按 Dify 映射反查源文件)
|
||||
# 知识库外部集成接口(供外部系统按 Dify 映射反查源文件)
|
||||
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
|
||||
@@ -83,6 +85,41 @@ def create_app(config_name='default'):
|
||||
@app.before_request
|
||||
def _sync_persisted_settings():
|
||||
_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:
|
||||
if request.path.startswith('/api/'):
|
||||
@@ -90,24 +127,89 @@ def create_app(config_name='default'):
|
||||
accepted = request.headers.get('Accept', '')
|
||||
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)
|
||||
def _handle_http_exception(exc: HTTPException):
|
||||
if not _should_return_json_error():
|
||||
return exc
|
||||
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)
|
||||
def _handle_unexpected_exception(exc: Exception):
|
||||
app.logger.exception(
|
||||
'Unhandled exception on %s %s',
|
||||
request.method,
|
||||
request.path,
|
||||
exc_info=exc,
|
||||
_log_api_error(
|
||||
code='SYSTEM.INTERNAL_ERROR',
|
||||
message='Internal server error',
|
||||
status=500,
|
||||
exc=exc,
|
||||
)
|
||||
if not _should_return_json_error():
|
||||
return '<h1><p>Internal Server Error</p></h1>', 500
|
||||
message = str(exc).strip() or 'Internal server error'
|
||||
return jsonify({'error': message}), 500
|
||||
payload = error_payload(
|
||||
code='SYSTEM.INTERNAL_ERROR',
|
||||
message='Internal server error',
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
)
|
||||
return jsonify(payload), 500
|
||||
|
||||
return app
|
||||
+180
-652
File diff suppressed because it is too large.
Load diff
+108
-279
@@ -1,4 +1,3 @@
|
||||
|
||||
"""
|
||||
backend/app/api/chat.py
|
||||
文件用途:定义聊天相关 API 路由
|
||||
@@ -15,7 +14,6 @@ import uuid
|
||||
import json
|
||||
from datetime import datetime
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import requests
|
||||
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app, has_request_context
|
||||
from sqlalchemy import func, desc, or_
|
||||
@@ -25,12 +23,9 @@ from app.services.integration_api import IntegrationApiService
|
||||
from app.decorators import require_agent_permission
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback
|
||||
from app import db
|
||||
|
||||
# 定义 Blueprint,用于在应用工厂中注册路由前缀 /api/chat
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip()
|
||||
|
||||
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
|
||||
|
||||
def _session_title_from_text(text: str) -> str:
|
||||
value = str(text or '').strip()
|
||||
@@ -145,21 +140,15 @@ def _update_chat_session(
|
||||
|
||||
|
||||
def _normalize_windows_share_path(path_value: str) -> str:
|
||||
normalized = str(path_value or "").strip().strip('"').replace("/", "\\")
|
||||
if normalized.startswith("\\\\"):
|
||||
return "\\\\" + normalized[2:].rstrip("\\")
|
||||
return normalized.rstrip("\\")
|
||||
|
||||
normalized = str(path_value or '').strip().strip('"').replace('/', '\\')
|
||||
if normalized.startswith('\\\\'):
|
||||
return '\\\\' + normalized[2:].rstrip('\\')
|
||||
return normalized.rstrip('\\')
|
||||
|
||||
def _is_allowed_share_path(target_url: str) -> bool:
|
||||
normalized_target = _normalize_windows_share_path(target_url)
|
||||
normalized_root = _normalize_windows_share_path(PLM_PREVIEW_SHARE_ROOT)
|
||||
return bool(
|
||||
normalized_root
|
||||
and normalized_target.startswith("\\\\")
|
||||
and normalized_target.lower().startswith(normalized_root.lower())
|
||||
)
|
||||
|
||||
return bool(normalized_root and normalized_target.startswith('\\\\') and normalized_target.lower().startswith(normalized_root.lower()))
|
||||
|
||||
def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
"""
|
||||
@@ -173,16 +162,14 @@ def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
if _is_allowed_share_path(target_url):
|
||||
return True
|
||||
parsed = urlparse(target_url)
|
||||
if parsed.scheme not in ("http", "https"):
|
||||
if parsed.scheme not in ('http', 'https'):
|
||||
return False
|
||||
host = (parsed.hostname or "").strip().lower()
|
||||
host = (parsed.hostname or '').strip().lower()
|
||||
if not host:
|
||||
return False
|
||||
|
||||
# 显式放行配置中的集成服务主机。
|
||||
integration_base = (IntegrationApiService.get_base_url() or "").strip()
|
||||
integration_base = (IntegrationApiService.get_base_url() or '').strip()
|
||||
if integration_base:
|
||||
integration_host = (urlparse(integration_base).hostname or "").strip().lower()
|
||||
integration_host = (urlparse(integration_base).hostname or '').strip().lower()
|
||||
if integration_host and host == integration_host:
|
||||
return True
|
||||
|
||||
@@ -194,7 +181,6 @@ def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
|
||||
if host in ("localhost", "127.0.0.1", "::1"):
|
||||
return True
|
||||
|
||||
try:
|
||||
ip = ipaddress.ip_address(host)
|
||||
return ip.is_private or ip.is_loopback
|
||||
@@ -204,8 +190,7 @@ def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024 * 1024):
|
||||
def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * 1024):
|
||||
"""
|
||||
从上游文件 URL 拉取二进制内容(供预览接口复用)。
|
||||
如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。
|
||||
@@ -217,26 +202,23 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
|
||||
import time
|
||||
import sqlalchemy as sa
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
if _is_allowed_share_path(file_url):
|
||||
normalized_path = _normalize_windows_share_path(file_url)
|
||||
try:
|
||||
if not os.path.isfile(normalized_path):
|
||||
return None, None, ('source file not found', 404)
|
||||
return (None, None, ('source file not found', 404))
|
||||
file_size = os.path.getsize(normalized_path)
|
||||
if max_size is not None and file_size > max_size:
|
||||
return None, None, ('file too large for online preview', 413)
|
||||
return (None, None, ('file too large for online preview', 413))
|
||||
with open(normalized_path, 'rb') as fh:
|
||||
content = fh.read()
|
||||
except OSError as exc:
|
||||
current_app.logger.warning("[file-preview] failed to read share path %s: %s", normalized_path, exc)
|
||||
return None, None, ('failed to read source file', 502)
|
||||
|
||||
current_app.logger.warning('[file-preview] failed to read share path %s: %s', normalized_path, exc)
|
||||
return (None, None, ('failed to read source file', 502))
|
||||
guessed_type = (mimetypes.guess_type(normalized_path)[0] or '').strip().lower()
|
||||
if _extract_placeholder_text(content):
|
||||
guessed_type = 'text/plain; charset=utf-8'
|
||||
return content, guessed_type, None
|
||||
|
||||
return (content, guessed_type, None)
|
||||
headers = {}
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
@@ -258,28 +240,24 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
|
||||
remote_document_id = str(payload_data.get('remote_document_id') or '').strip()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not dataset_id or not remote_document_id:
|
||||
try:
|
||||
stmt = sa.text("CAST(retriever_resources AS TEXT) LIKE :url")
|
||||
stmt = sa.text('CAST(retriever_resources AS TEXT) LIKE :url')
|
||||
log = db.session.query(ChatLog).filter(stmt).params(url=f'%{raw_url}%').order_by(ChatLog.created_at.desc()).first()
|
||||
if log and log.retriever_resources:
|
||||
for r in log.retriever_resources:
|
||||
source_url = str(r.get('source_download_url') or '')
|
||||
if source_url == raw_url or (source_url and source_url.split('&token=')[0] == raw_url.split('&token=')[0]):
|
||||
dataset_id = dataset_id or str(r.get('dataset_id') or r.get('metadata', {}).get('dataset_id') or '').strip()
|
||||
remote_document_id = remote_document_id or str(
|
||||
r.get('remote_document_id') or r.get('metadata', {}).get('remote_document_id') or r.get('document_id') or ''
|
||||
).strip()
|
||||
remote_document_id = remote_document_id or str(r.get('remote_document_id') or r.get('metadata', {}).get('remote_document_id') or r.get('document_id') or '').strip()
|
||||
if dataset_id and remote_document_id:
|
||||
break
|
||||
except Exception as e:
|
||||
current_app.logger.warning("[file-preview] failed to find IDs in ChatLog: %s", e)
|
||||
|
||||
current_app.logger.warning('[file-preview] failed to find IDs in ChatLog: %s', e)
|
||||
if dataset_id and remote_document_id:
|
||||
new_info = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
|
||||
if new_info and new_info.get('source_download_url'):
|
||||
current_app.logger.info("[file-preview] refreshed integration url for dataset=%s doc=%s", dataset_id, remote_document_id)
|
||||
current_app.logger.info('[file-preview] refreshed integration url for dataset=%s doc=%s', dataset_id, remote_document_id)
|
||||
return new_info['source_download_url']
|
||||
return raw_url
|
||||
|
||||
@@ -327,8 +305,7 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
|
||||
if 'unauthorized' in body or '"error"' in body:
|
||||
return True
|
||||
return False
|
||||
|
||||
if base_url and file_url.startswith(base_url) and 'token=' in file_url:
|
||||
if base_url and file_url.startswith(base_url) and ('token=' in file_url):
|
||||
try:
|
||||
parsed = urlparse(file_url)
|
||||
qs = parse_qs(parsed.query)
|
||||
@@ -343,18 +320,14 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
|
||||
if exp and exp < time.time() + 300:
|
||||
file_url = _resolve_latest_integration_url(file_url)
|
||||
except Exception as e:
|
||||
current_app.logger.warning("[file-preview] failed to refresh expired integration token: %s", e)
|
||||
|
||||
current_app.logger.warning('[file-preview] failed to refresh expired integration token: %s', e)
|
||||
headers = _build_headers(file_url)
|
||||
try:
|
||||
upstream = requests.get(file_url, headers=headers, timeout=(5, 20))
|
||||
except requests.RequestException as e:
|
||||
current_app.logger.warning("[file-preview] upstream request failed: %s", e)
|
||||
return None, None, ('failed to fetch source file', 502)
|
||||
|
||||
# 某些旧历史记录中的 source_download_url 已过期,但上游可能返回 200 + JSON 错误体。
|
||||
# 这里统一视为“坏链接”,刷新最新下载地址后重试一次。
|
||||
if base_url and file_url.startswith(base_url) and 'token=' in file_url and _should_refresh_from_response(upstream):
|
||||
current_app.logger.warning('[file-preview] upstream request failed: %s', e)
|
||||
return (None, None, ('failed to fetch source file', 502))
|
||||
if base_url and file_url.startswith(base_url) and ('token=' in file_url) and _should_refresh_from_response(upstream):
|
||||
refreshed_url = _resolve_latest_integration_url(file_url)
|
||||
if refreshed_url != file_url:
|
||||
headers = _build_headers(refreshed_url)
|
||||
@@ -362,24 +335,21 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None = 15 * 1024
|
||||
upstream = requests.get(refreshed_url, headers=headers, timeout=(5, 20))
|
||||
file_url = refreshed_url
|
||||
except requests.RequestException as e:
|
||||
current_app.logger.warning("[file-preview] refreshed upstream request failed: %s", e)
|
||||
return None, None, ('failed to fetch source file', 502)
|
||||
|
||||
current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e)
|
||||
return (None, None, ('failed to fetch source file', 502))
|
||||
if upstream.status_code != 200:
|
||||
current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}")
|
||||
return None, None, (f'upstream returned status {upstream.status_code}', 502)
|
||||
|
||||
content = upstream.content or b''
|
||||
if max_size is not None and len(content) > max_size:
|
||||
return None, None, ('file too large for online preview', 413)
|
||||
|
||||
return (None, None, ('file too large for online preview', 413))
|
||||
content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower()
|
||||
if content_type == 'application/json':
|
||||
body = content[:512].decode('utf-8', errors='ignore')
|
||||
current_app.logger.warning("[file-preview] upstream returned json instead of binary url=%s body=%s", file_url, body)
|
||||
return None, None, ('upstream returned invalid preview payload', 502)
|
||||
return content, content_type, None
|
||||
|
||||
current_app.logger.warning('[file-preview] upstream returned json instead of binary url=%s body=%s', file_url, body)
|
||||
return (None, None, ('upstream returned invalid preview payload', 502))
|
||||
return (content, content_type, None)
|
||||
|
||||
def _extract_placeholder_text(content: bytes) -> str:
|
||||
sample = content[:2048]
|
||||
@@ -394,7 +364,7 @@ def _extract_placeholder_text(content: bytes) -> str:
|
||||
if not lines:
|
||||
continue
|
||||
first_line = lines[0][:160]
|
||||
if any(token in first_line for token in ('该文件', '机密文件', '未经允许', '法律风险', '禁止', '保密')):
|
||||
if any((token in first_line for token in ('该文件', '机密文件', '未经允许', '法律风险', '禁止', '保密'))):
|
||||
return first_line
|
||||
return ''
|
||||
|
||||
@@ -473,23 +443,11 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
|
||||
input_path = os.path.join(temp_dir, f"input.{ext}")
|
||||
with open(input_path, 'wb') as f:
|
||||
f.write(content)
|
||||
|
||||
commands = [
|
||||
'soffice',
|
||||
'libreoffice',
|
||||
r'C:\Program Files\LibreOffice\program\soffice.exe',
|
||||
r'C:\Program Files (x86)\LibreOffice\program\soffice.exe'
|
||||
]
|
||||
|
||||
commands = ['soffice', 'libreoffice', 'C:\\Program Files\\LibreOffice\\program\\soffice.exe', 'C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe']
|
||||
success = False
|
||||
for cmd in commands:
|
||||
try:
|
||||
process = subprocess.run(
|
||||
[cmd, '--headless', '--convert-to', 'pdf', '--outdir', temp_dir, input_path],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
timeout=60
|
||||
)
|
||||
process = subprocess.run([cmd, '--headless', '--convert-to', 'pdf', '--outdir', temp_dir, input_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60)
|
||||
if process.returncode == 0:
|
||||
success = True
|
||||
break
|
||||
@@ -497,8 +455,6 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
|
||||
current_app.logger.warning(f"LibreOffice command {cmd} failed: {process.stderr.decode('utf-8', errors='ignore')}")
|
||||
except (FileNotFoundError, subprocess.TimeoutExpired):
|
||||
continue
|
||||
|
||||
# 如果 LibreOffice 失败,且是在 Windows 系统下,尝试调用本地安装的 WPS 或 MS Office
|
||||
if not success and os.name == 'nt':
|
||||
app = None
|
||||
doc_obj = None
|
||||
@@ -507,8 +463,7 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
|
||||
import win32com.client
|
||||
import pythoncom
|
||||
pythoncom.CoInitialize()
|
||||
output_path = os.path.join(temp_dir, "input.pdf")
|
||||
|
||||
output_path = os.path.join(temp_dir, 'input.pdf')
|
||||
if ext in ('doc', 'docx'):
|
||||
try:
|
||||
from pathlib import Path
|
||||
@@ -548,12 +503,11 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
|
||||
except Exception:
|
||||
doc_obj.SaveAs(output_abs, 17) # 17 = wdFormatPDF
|
||||
success = True
|
||||
|
||||
elif ext in ('ppt', 'pptx'):
|
||||
try:
|
||||
app = win32com.client.Dispatch("KWPP.Application") # 尝试 WPS PPT
|
||||
app = win32com.client.Dispatch('KWPP.Application')
|
||||
except Exception:
|
||||
app = win32com.client.Dispatch("PowerPoint.Application") # 回退 MS PPT
|
||||
app = win32com.client.Dispatch('PowerPoint.Application')
|
||||
app.Visible = False
|
||||
try:
|
||||
app.DisplayAlerts = False
|
||||
@@ -562,19 +516,18 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
|
||||
doc_obj = app.Presentations.Open(os.path.abspath(input_path), ReadOnly=True, WithWindow=False)
|
||||
doc_obj.SaveAs(os.path.abspath(output_path), 32) # 32 = ppSaveAsPDF
|
||||
success = True
|
||||
|
||||
elif ext in ('xls', 'xlsx'):
|
||||
try:
|
||||
app = win32com.client.Dispatch("KET.Application") # 尝试 WPS Excel
|
||||
app = win32com.client.Dispatch('KET.Application')
|
||||
except Exception:
|
||||
app = win32com.client.Dispatch("Excel.Application") # 回退 MS Excel
|
||||
app = win32com.client.Dispatch('Excel.Application')
|
||||
app.Visible = False
|
||||
app.DisplayAlerts = False
|
||||
doc_obj = app.Workbooks.Open(os.path.abspath(input_path), ReadOnly=True)
|
||||
doc_obj.ExportAsFixedFormat(0, os.path.abspath(output_path)) # 0 = xlTypePDF
|
||||
success = True
|
||||
except ImportError:
|
||||
current_app.logger.warning("pywin32 not installed, cannot fallback to WPS/MS Office COM API.")
|
||||
current_app.logger.warning('pywin32 not installed, cannot fallback to WPS/MS Office COM API.')
|
||||
except Exception as e:
|
||||
current_app.logger.warning(f"WPS/MS Office COM conversion failed: {e}")
|
||||
finally:
|
||||
@@ -595,9 +548,8 @@ def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
|
||||
pass
|
||||
|
||||
if not success:
|
||||
raise Exception("Failed to convert document to PDF using LibreOffice or WPS/MS Office")
|
||||
|
||||
output_path = os.path.join(temp_dir, "input.pdf")
|
||||
raise Exception('Failed to convert document to PDF using LibreOffice or WPS/MS Office')
|
||||
output_path = os.path.join(temp_dir, 'input.pdf')
|
||||
if os.path.exists(output_path):
|
||||
with open(output_path, 'rb') as f:
|
||||
return f.read()
|
||||
@@ -614,37 +566,22 @@ def _convert_excel_to_xlsx(content: bytes, ext: str) -> bytes:
|
||||
normalized_ext = (ext or '').strip().lower()
|
||||
if normalized_ext != 'xls':
|
||||
return content
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
input_path = os.path.join(temp_dir, "input.xls")
|
||||
output_path = os.path.join(temp_dir, "input.xlsx")
|
||||
input_path = os.path.join(temp_dir, 'input.xls')
|
||||
output_path = os.path.join(temp_dir, 'input.xlsx')
|
||||
with open(input_path, 'wb') as f:
|
||||
f.write(content)
|
||||
|
||||
commands = [
|
||||
'soffice',
|
||||
'libreoffice',
|
||||
r'C:\Program Files\LibreOffice\program\soffice.exe',
|
||||
r'C:\Program Files (x86)\LibreOffice\program\soffice.exe'
|
||||
]
|
||||
|
||||
commands = ['soffice', 'libreoffice', 'C:\\Program Files\\LibreOffice\\program\\soffice.exe', 'C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe']
|
||||
errors = []
|
||||
for cmd in commands:
|
||||
try:
|
||||
process = subprocess.run(
|
||||
[cmd, '--headless', '--convert-to', 'xlsx', '--outdir', temp_dir, input_path],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
timeout=60
|
||||
)
|
||||
process = subprocess.run([cmd, '--headless', '--convert-to', 'xlsx', '--outdir', temp_dir, input_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=60)
|
||||
except (FileNotFoundError, subprocess.TimeoutExpired) as e:
|
||||
errors.append(f"{cmd}: {e}")
|
||||
errors.append(f'{cmd}: {e}')
|
||||
continue
|
||||
|
||||
if process.returncode == 0 and os.path.exists(output_path):
|
||||
with open(output_path, 'rb') as f:
|
||||
return f.read()
|
||||
|
||||
stderr = process.stderr.decode('utf-8', errors='ignore').strip()
|
||||
errors.append(f"{cmd}: {stderr or f'code={process.returncode}'}")
|
||||
|
||||
@@ -670,33 +607,31 @@ def _convert_excel_via_windows_office(input_path: str, output_path: str) -> bool
|
||||
"""
|
||||
if os.name != 'nt':
|
||||
return False
|
||||
|
||||
try:
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
except ImportError:
|
||||
current_app.logger.warning("pywin32 not installed, cannot fallback to WPS/MS Excel for xls preview.")
|
||||
current_app.logger.warning('pywin32 not installed, cannot fallback to WPS/MS Excel for xls preview.')
|
||||
return False
|
||||
|
||||
app = None
|
||||
workbook = None
|
||||
pythoncom.CoInitialize()
|
||||
try:
|
||||
try:
|
||||
app = win32com.client.Dispatch("KET.Application")
|
||||
app = win32com.client.Dispatch('KET.Application')
|
||||
except Exception:
|
||||
app = win32com.client.Dispatch("Excel.Application")
|
||||
app = win32com.client.Dispatch('Excel.Application')
|
||||
app.Visible = False
|
||||
app.DisplayAlerts = False
|
||||
workbook = app.Workbooks.Open(os.path.abspath(input_path))
|
||||
workbook.SaveAs(os.path.abspath(output_path), FileFormat=51) # 51 = xlOpenXMLWorkbook (.xlsx)
|
||||
workbook.SaveAs(os.path.abspath(output_path), FileFormat=51)
|
||||
workbook.Close(False)
|
||||
workbook = None
|
||||
app.Quit()
|
||||
app = None
|
||||
return os.path.exists(output_path)
|
||||
except Exception as exc:
|
||||
current_app.logger.warning("WPS/MS Excel conversion failed for xls preview: %s", exc)
|
||||
current_app.logger.warning('WPS/MS Excel conversion failed for xls preview: %s', exc)
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
@@ -714,7 +649,6 @@ def _convert_excel_via_windows_office(input_path: str, output_path: str) -> bool
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _detect_excel_format(content: bytes, ext: str) -> str:
|
||||
"""
|
||||
根据文件头兜底判断 Excel 实际格式,避免只依赖 URL/文件名扩展名。
|
||||
@@ -725,18 +659,16 @@ def _detect_excel_format(content: bytes, ext: str) -> str:
|
||||
head = content[:8] if content else b''
|
||||
if head.startswith(b'PK\x03\x04'):
|
||||
return 'xlsx'
|
||||
if head.startswith(b'\xD0\xCF\x11\xE0'):
|
||||
if head.startswith(b'\xd0\xcf\x11\xe0'):
|
||||
return 'xls'
|
||||
return normalized_ext
|
||||
|
||||
|
||||
def _load_excel_workbook(content: bytes, ext: str):
|
||||
normalized_ext = _detect_excel_format(content, ext)
|
||||
if normalized_ext == 'xls':
|
||||
content = _convert_excel_to_xlsx(content, 'xls')
|
||||
return load_workbook(filename=io.BytesIO(content), data_only=True, read_only=True)
|
||||
|
||||
|
||||
@chat_bp.route('/oa/employees', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_oa_employees():
|
||||
@@ -750,15 +682,13 @@ def get_oa_employees():
|
||||
except ValueError:
|
||||
page = 1
|
||||
page_size = 20
|
||||
|
||||
try:
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
result = OASQLServerService.search_employees(keyword, page, page_size)
|
||||
return jsonify(result)
|
||||
except Exception as e:
|
||||
current_app.logger.error(f"[OA-Employees] Query failed: {e}")
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
current_app.logger.error(f'[OA-Employees] Query failed: {e}')
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
||||
|
||||
@chat_bp.route('/oa/resolve-names', methods=['GET'])
|
||||
@require_agent_permission
|
||||
@@ -779,10 +709,9 @@ def resolve_oa_names():
|
||||
if sid:
|
||||
result[f'sub_{sid}'] = OASQLServerService.get_subcompany_name(sid)
|
||||
except Exception as e:
|
||||
current_app.logger.error(f"[OA-ResolveNames] Query failed: {e}")
|
||||
current_app.logger.error(f'[OA-ResolveNames] Query failed: {e}')
|
||||
return jsonify(result)
|
||||
|
||||
|
||||
@chat_bp.route('/sessions', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_chat_sessions():
|
||||
@@ -791,9 +720,8 @@ def get_chat_sessions():
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
|
||||
if user is None or agent is None:
|
||||
return jsonify({'error': 'Missing context'}), 500
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
|
||||
session_rows = db.session.query(ChatSession).filter_by(
|
||||
user_id=user.id,
|
||||
@@ -823,13 +751,7 @@ def get_chat_sessions():
|
||||
for row in legacy_rows:
|
||||
if not row.conversation_id or row.conversation_id in session_ids:
|
||||
continue
|
||||
latest_query_row = db.session.query(ChatLog.query).filter(
|
||||
ChatLog.user_id == user.id,
|
||||
ChatLog.agent_id == agent.id,
|
||||
ChatLog.conversation_id == row.conversation_id,
|
||||
ChatLog.query.isnot(None),
|
||||
ChatLog.query != '',
|
||||
).order_by(desc(ChatLog.created_at), desc(ChatLog.id)).first()
|
||||
latest_query_row = db.session.query(ChatLog.query).filter(ChatLog.user_id == user.id, ChatLog.agent_id == agent.id, ChatLog.conversation_id == row.conversation_id, ChatLog.query.isnot(None), ChatLog.query != '').order_by(desc(ChatLog.created_at), desc(ChatLog.id)).first()
|
||||
title = (latest_query_row[0] if latest_query_row and latest_query_row[0] else '').strip()
|
||||
sessions.append({
|
||||
'id': 0,
|
||||
@@ -842,7 +764,6 @@ def get_chat_sessions():
|
||||
sessions.sort(key=lambda item: item.get('created_at') or '', reverse=True)
|
||||
return jsonify(sessions[:20])
|
||||
|
||||
|
||||
@chat_bp.route('/sessions', methods=['DELETE'])
|
||||
@require_agent_permission
|
||||
def delete_all_chat_sessions():
|
||||
@@ -851,10 +772,8 @@ def delete_all_chat_sessions():
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
|
||||
if user is None or agent is None:
|
||||
return jsonify({'error': 'Missing context'}), 500
|
||||
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
chat_logs = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id).all()
|
||||
chat_log_ids = [log.id for log in chat_logs]
|
||||
if chat_log_ids:
|
||||
@@ -867,7 +786,6 @@ def delete_all_chat_sessions():
|
||||
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@chat_bp.route('/sessions/<conversation_id>', methods=['DELETE'])
|
||||
@require_agent_permission
|
||||
def delete_chat_session(conversation_id):
|
||||
@@ -876,9 +794,8 @@ def delete_chat_session(conversation_id):
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
|
||||
if user is None or agent is None:
|
||||
return jsonify({'error': 'Missing context'}), 500
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
|
||||
session = _get_chat_session(user.id, agent.id, conversation_id)
|
||||
if session:
|
||||
@@ -909,7 +826,6 @@ def delete_chat_session(conversation_id):
|
||||
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@chat_bp.route('/messages', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_chat_messages():
|
||||
@@ -936,24 +852,14 @@ def get_chat_messages():
|
||||
for log in logs:
|
||||
if log.query:
|
||||
messages.append({'role': 'user', 'content': log.query})
|
||||
|
||||
assistant_msg = {
|
||||
'role': 'assistant',
|
||||
'content': log.answer,
|
||||
'chat_log_id': log.id,
|
||||
'retriever_resources': log.retriever_resources or [],
|
||||
'attribution_parts': log.attribution_parts or []
|
||||
}
|
||||
assistant_msg = {'role': 'assistant', 'content': log.answer, 'chat_log_id': log.id, 'retriever_resources': log.retriever_resources or [], 'attribution_parts': log.attribution_parts or []}
|
||||
if log.message_type:
|
||||
assistant_msg['type'] = log.message_type
|
||||
if log.payload:
|
||||
assistant_msg['payload'] = log.payload
|
||||
|
||||
messages.append(assistant_msg)
|
||||
|
||||
return jsonify(messages)
|
||||
|
||||
|
||||
@chat_bp.route('/messages/local', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def save_local_message():
|
||||
@@ -962,10 +868,8 @@ def save_local_message():
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
|
||||
if user is None or agent is None:
|
||||
return jsonify({'error': 'Missing context'}), 500
|
||||
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
data = request.get_json() or {}
|
||||
conversation_id = (data.get('conversation_id') or '').strip()
|
||||
message_type = data.get('type')
|
||||
@@ -974,7 +878,7 @@ def save_local_message():
|
||||
user_query = data.get('query', '')
|
||||
|
||||
if not message_type:
|
||||
return jsonify({'error': 'type is required'}), 400
|
||||
raise ValidationError('type is required')
|
||||
|
||||
title = user_query or content
|
||||
external_conversation_id = conversation_id if conversation_id and _get_chat_session(user.id, agent.id, conversation_id) is None else None
|
||||
@@ -991,7 +895,6 @@ def save_local_message():
|
||||
# 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录
|
||||
# 这样能保证前端表单状态(例如已确认)被持久化
|
||||
local_id = payload.get('formId') if payload and isinstance(payload, dict) else None
|
||||
|
||||
chat_log = None
|
||||
if local_id:
|
||||
# 在 payload 中查找是否已存在相同 formId 的同类型消息
|
||||
@@ -1004,15 +907,14 @@ def save_local_message():
|
||||
).order_by(ChatLog.created_at.desc()).limit(20).all()
|
||||
|
||||
for log in logs:
|
||||
if log.payload and isinstance(log.payload, dict) and log.payload.get('formId') == local_id:
|
||||
if log.payload and isinstance(log.payload, dict) and (log.payload.get('formId') == local_id):
|
||||
chat_log = log
|
||||
break
|
||||
|
||||
if chat_log:
|
||||
chat_log.content = content
|
||||
chat_log.answer = content
|
||||
chat_log.payload = payload
|
||||
if user_query and not chat_log.query:
|
||||
if user_query and (not chat_log.query):
|
||||
chat_log.query = user_query
|
||||
else:
|
||||
chat_log = ChatLog(
|
||||
@@ -1032,7 +934,6 @@ def save_local_message():
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'chat_log_id': chat_log.id, 'conversation_id': conversation_id})
|
||||
|
||||
|
||||
@chat_bp.route('/completions', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def chat_completions():
|
||||
@@ -1048,34 +949,18 @@ def chat_completions():
|
||||
返回值:
|
||||
Flask Response 对象,mimetype=text/event-stream
|
||||
"""
|
||||
# 解析 JSON 请求体
|
||||
data = request.get_json() or {}
|
||||
# 提取用户提问内容
|
||||
query = data.get('query')
|
||||
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
||||
conversation_id = data.get('conversation_id')
|
||||
# 知识库类型
|
||||
kb_type = data.get('kb_type', '企业知识库')
|
||||
request_id = uuid.uuid4().hex[:12]
|
||||
|
||||
# 从全局 g 中获取装饰器注入的用户和 Agent 对象
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
|
||||
current_app.logger.info(
|
||||
"[chat-api] /completions request_id=%s user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s",
|
||||
request_id,
|
||||
getattr(user, 'id', None),
|
||||
getattr(agent, 'id', None),
|
||||
len(query or ''),
|
||||
conversation_id,
|
||||
kb_type
|
||||
)
|
||||
|
||||
# 安全兜底:如果装饰器未正确注入,返回错误
|
||||
current_app.logger.info('[chat-api] /completions request_id=%s user_id=%s agent_id=%s query_len=%s conversation_id=%s kb_type=%s', request_id, getattr(user, 'id', None), getattr(agent, 'id', None), len(query or ''), conversation_id, kb_type)
|
||||
if user is None or agent is None:
|
||||
current_app.logger.error("[chat-api] missing user/agent context user=%s agent=%s", bool(user), bool(agent))
|
||||
return jsonify({'error': 'Missing user or agent context'}), 500
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
||||
|
||||
user_id = getattr(user, 'id', None)
|
||||
agent_id = getattr(agent, 'id', None)
|
||||
@@ -1127,14 +1012,12 @@ def chat_completions():
|
||||
elif kb_type == 'ERP知识库':
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
if HRLeaveSQLServerService.supports(query):
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
generator = Text2SQLService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
|
||||
if HRLeaveSQLServerService.supports(query):
|
||||
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
|
||||
else:
|
||||
@@ -1230,27 +1113,20 @@ def submit_feedback():
|
||||
score = data.get('score')
|
||||
comment = data.get('comment') or ''
|
||||
conversation_id = data.get('conversation_id')
|
||||
|
||||
if not current_app.config.get('FEEDBACK_ENABLED', True):
|
||||
return jsonify({'error': 'feedback is disabled'}), 403
|
||||
|
||||
raise ForbiddenError('feedback is disabled')
|
||||
if score is None:
|
||||
return jsonify({'error': 'score is required'}), 400
|
||||
|
||||
raise ValidationError('score is required')
|
||||
try:
|
||||
score_value = int(score)
|
||||
except (TypeError, ValueError):
|
||||
return jsonify({'error': 'score must be an integer'}), 400
|
||||
|
||||
raise ValidationError('score must be an integer')
|
||||
if score_value < 1 or score_value > 5:
|
||||
return jsonify({'error': 'score must be between 1 and 5'}), 400
|
||||
|
||||
raise ValidationError('score must be between 1 and 5')
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
return jsonify({'error': 'Missing user or agent context'}), 500
|
||||
|
||||
# 构造查询:限定在当前用户和 Agent 范围内
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
||||
chat_logs_query = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id)
|
||||
if conversation_id:
|
||||
chat_logs_query = chat_logs_query.filter(
|
||||
@@ -1260,24 +1136,16 @@ def submit_feedback():
|
||||
# 取最新一条对话日志
|
||||
chat_log = chat_logs_query.order_by(ChatLog.created_at.desc()).first()
|
||||
if not chat_log:
|
||||
return jsonify({'error': 'ChatLog not found'}), 404
|
||||
|
||||
# 如果已存在反馈,则更新;否则新建
|
||||
raise NotFoundError('ChatLog not found')
|
||||
if chat_log.feedback:
|
||||
chat_log.feedback.score = score_value
|
||||
chat_log.feedback.comment = comment
|
||||
else:
|
||||
fb = Feedback(
|
||||
chat_log_id=chat_log.id,
|
||||
score=score_value,
|
||||
comment=comment,
|
||||
)
|
||||
fb = Feedback(chat_log_id=chat_log.id, score=score_value, comment=comment)
|
||||
db.session.add(fb)
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@chat_bp.route('/source-file', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def resolve_source_file():
|
||||
@@ -1287,18 +1155,11 @@ def resolve_source_file():
|
||||
dataset_id = (request.args.get('dataset_id') or '').strip()
|
||||
remote_document_id = (request.args.get('remote_document_id') or '').strip()
|
||||
if not dataset_id or not remote_document_id:
|
||||
current_app.logger.warning(
|
||||
"[source-file] missing required params: dataset_id=%r remote_document_id_present=%s remote_document_id_preview=%r query_args=%s",
|
||||
dataset_id,
|
||||
bool(remote_document_id),
|
||||
(remote_document_id[:8] + "...") if remote_document_id else "",
|
||||
dict(request.args),
|
||||
)
|
||||
return jsonify({'error': 'dataset_id and remote_document_id are required'}), 400
|
||||
|
||||
current_app.logger.warning('[source-file] missing required params: dataset_id=%r remote_document_id_present=%s remote_document_id_preview=%r query_args=%s', dataset_id, bool(remote_document_id), remote_document_id[:8] + '...' if remote_document_id else '', dict(request.args))
|
||||
raise ValidationError('dataset_id and remote_document_id are required')
|
||||
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
|
||||
if not payload:
|
||||
return jsonify({'error': 'source file mapping not found'}), 404
|
||||
raise NotFoundError('source file mapping not found')
|
||||
|
||||
source_ext = str(payload.get('source_ext') or '').strip().lower()
|
||||
source_download_url = payload.get('source_download_url')
|
||||
@@ -1325,11 +1186,11 @@ def source_file_text():
|
||||
dataset_id = (request.args.get('dataset_id') or '').strip()
|
||||
remote_document_id = (request.args.get('remote_document_id') or '').strip()
|
||||
if not dataset_id or not remote_document_id:
|
||||
return jsonify({'error': 'dataset_id and remote_document_id are required'}), 400
|
||||
raise ValidationError('dataset_id and remote_document_id are required')
|
||||
|
||||
text = _fetch_dify_text_document(dataset_id, remote_document_id)
|
||||
if not text:
|
||||
return jsonify({'error': 'failed to resolve text source file'}), 404
|
||||
raise NotFoundError('failed to resolve text source file')
|
||||
|
||||
filename = f'{remote_document_id}.txt'
|
||||
return Response(
|
||||
@@ -1354,31 +1215,29 @@ def preview_excel():
|
||||
"""
|
||||
file_url = (request.args.get('url') or '').strip()
|
||||
if not file_url:
|
||||
return jsonify({'error': 'url is required'}), 400
|
||||
|
||||
raise ValidationError('url is required')
|
||||
if not _is_allowed_preview_url(file_url):
|
||||
return jsonify({'error': 'url is not allowed for preview'}), 403
|
||||
|
||||
raise ForbiddenError('url is not allowed for preview')
|
||||
parsed = urlparse(file_url)
|
||||
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
||||
name = (request.args.get('name') or '').strip()
|
||||
name_ext = (name.split('.')[-1] if '.' in name else '').lower()
|
||||
ext = url_path_ext or name_ext
|
||||
|
||||
if ext and ext not in ('xlsx', 'xls'):
|
||||
raise_for_status(f'unsupported file extension: {ext}', 415)
|
||||
try:
|
||||
limit = int(request.args.get('limit', 100))
|
||||
except ValueError:
|
||||
limit = 100
|
||||
limit = max(1, min(limit, 300))
|
||||
|
||||
content, _, err = _fetch_preview_source_bytes(file_url, max_size=50 * 1024 * 1024)
|
||||
if err:
|
||||
msg, code = err
|
||||
return jsonify({'error': msg}), code
|
||||
raise_for_status(msg, code)
|
||||
|
||||
detected_ext = _detect_excel_format(content or b'', ext)
|
||||
if detected_ext not in ('xlsx', 'xls'):
|
||||
return jsonify({'error': f'unsupported file extension: {ext or detected_ext or "unknown"}'}), 415
|
||||
raise_for_status(f'unsupported file extension: {ext or detected_ext or "unknown"}', 415)
|
||||
|
||||
try:
|
||||
wb = _load_excel_workbook(content, detected_ext)
|
||||
@@ -1392,23 +1251,15 @@ def preview_excel():
|
||||
file_url,
|
||||
e,
|
||||
)
|
||||
payload = {'error': 'failed to parse excel file'}
|
||||
details: dict = {}
|
||||
if current_app.config.get('DEBUG') or os.getenv('ENV_NAME', 'dev').strip().lower() == 'dev':
|
||||
payload.update({
|
||||
'detail': str(e),
|
||||
'ext': ext,
|
||||
'detected_ext': detected_ext,
|
||||
'size': len(content or b''),
|
||||
})
|
||||
return jsonify(payload), 422
|
||||
|
||||
details = {'detail': str(e), 'ext': ext, 'detected_ext': detected_ext, 'size': len(content or b'')}
|
||||
raise AppError(code='VALIDATION.UNPROCESSABLE', message='failed to parse excel file', http_status=422, details=details)
|
||||
if not wb.sheetnames:
|
||||
return jsonify({'error': 'workbook has no sheets'}), 422
|
||||
|
||||
raise_for_status('workbook has no sheets', 422)
|
||||
requested_sheet = (request.args.get('sheet') or '').strip()
|
||||
sheet_name = requested_sheet if requested_sheet in wb.sheetnames else wb.sheetnames[0]
|
||||
ws = wb[sheet_name]
|
||||
|
||||
rows = []
|
||||
for row in ws.iter_rows(values_only=True):
|
||||
normalized = []
|
||||
@@ -1422,23 +1273,12 @@ def preview_excel():
|
||||
rows.append(normalized)
|
||||
if len(rows) >= limit:
|
||||
break
|
||||
|
||||
# 统一列宽,保证前端表格渲染稳定。
|
||||
max_cols = max((len(r) for r in rows), default=0)
|
||||
for r in rows:
|
||||
if len(r) < max_cols:
|
||||
r.extend([''] * (max_cols - len(r)))
|
||||
|
||||
columns = [f'COL_{i + 1}' for i in range(max_cols)]
|
||||
return jsonify({
|
||||
'sheet_name': sheet_name,
|
||||
'sheets': wb.sheetnames,
|
||||
'columns': columns,
|
||||
'rows': rows,
|
||||
'limit': limit,
|
||||
'truncated': len(rows) >= limit,
|
||||
})
|
||||
|
||||
return jsonify({'sheet_name': sheet_name, 'sheets': wb.sheetnames, 'columns': columns, 'rows': rows, 'limit': limit, 'truncated': len(rows) >= limit})
|
||||
|
||||
@chat_bp.route('/preview-text', methods=['GET'])
|
||||
@require_agent_permission
|
||||
@@ -1449,10 +1289,9 @@ def preview_text():
|
||||
"""
|
||||
file_url = (request.args.get('url') or '').strip()
|
||||
if not file_url:
|
||||
return jsonify({'error': 'url is required'}), 400
|
||||
raise ValidationError('url is required')
|
||||
if not _is_allowed_preview_url(file_url):
|
||||
return jsonify({'error': 'url is not allowed for preview'}), 403
|
||||
|
||||
raise ForbiddenError('url is not allowed for preview')
|
||||
parsed = urlparse(file_url)
|
||||
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
||||
name = (request.args.get('name') or '').strip()
|
||||
@@ -1461,15 +1300,12 @@ def preview_text():
|
||||
ext = explicit_ext or url_path_ext or name_ext
|
||||
allowed = {'md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'}
|
||||
if ext and ext not in allowed:
|
||||
return jsonify({'error': f'unsupported text extension: {ext}'}), 415
|
||||
|
||||
raise_for_status(f'unsupported text extension: {ext}', 415)
|
||||
max_size = 100 * 1024 * 1024 if request.args.get('download') == '1' else 15 * 1024 * 1024
|
||||
content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size)
|
||||
if err:
|
||||
msg, code = err
|
||||
return jsonify({'error': msg}), code
|
||||
|
||||
# 尝试多编码解码,提升兼容性。
|
||||
raise_for_status(msg, code)
|
||||
text = None
|
||||
for enc in ('utf-8', 'utf-8-sig', 'gb18030', 'latin-1'):
|
||||
try:
|
||||
@@ -1478,14 +1314,8 @@ def preview_text():
|
||||
except Exception:
|
||||
continue
|
||||
if text is None:
|
||||
return jsonify({'error': 'failed to decode text file'}), 422
|
||||
|
||||
return jsonify({
|
||||
'content': text,
|
||||
'content_type': content_type or 'text/plain',
|
||||
'ext': ext,
|
||||
})
|
||||
|
||||
raise_for_status('failed to decode text file', 422)
|
||||
return jsonify({'content': text, 'content_type': content_type or 'text/plain', 'ext': ext})
|
||||
|
||||
def _guess_ext_from_content(content: bytes, default_ext: str) -> str:
|
||||
"""
|
||||
@@ -1540,10 +1370,9 @@ def preview_file_raw():
|
||||
"""
|
||||
file_url = (request.args.get('url') or '').strip()
|
||||
if not file_url:
|
||||
return jsonify({'error': 'url is required'}), 400
|
||||
raise ValidationError('url is required')
|
||||
if not _is_allowed_preview_url(file_url):
|
||||
return jsonify({'error': 'url is not allowed for preview'}), 403
|
||||
|
||||
raise ForbiddenError('url is not allowed for preview')
|
||||
parsed = urlparse(file_url)
|
||||
url_path_ext = ((parsed.path or '').split('.')[-1] if '.' in (parsed.path or '') else '').lower()
|
||||
name = (request.args.get('name') or '').strip()
|
||||
@@ -1555,7 +1384,7 @@ def preview_file_raw():
|
||||
content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size)
|
||||
if err:
|
||||
msg, code = err
|
||||
return jsonify({'error': msg}), code
|
||||
raise_for_status(msg, code)
|
||||
|
||||
# 根据文件二进制头部纠正扩展名,防止文件本身是 docx 却被命名为 doc,导致转换或下载后乱码
|
||||
real_ext = _guess_ext_from_content(content, ext)
|
||||
@@ -1589,7 +1418,11 @@ def preview_file_raw():
|
||||
content_type = 'text/plain; charset=utf-8'
|
||||
current_app.logger.info('[file-preview] office preview degraded to text placeholder for %s', file_url)
|
||||
else:
|
||||
return jsonify({'error': 'failed to convert office file for preview'}), 422
|
||||
raise AppError(
|
||||
code='VALIDATION.UNPROCESSABLE',
|
||||
message='failed to convert office file for preview',
|
||||
http_status=422,
|
||||
)
|
||||
|
||||
fallback_types = {
|
||||
'pdf': 'application/pdf',
|
||||
@@ -1610,18 +1443,14 @@ def preview_file_raw():
|
||||
content = placeholder_text.encode('utf-8')
|
||||
content_type = 'text/plain; charset=utf-8'
|
||||
current_app.logger.info('[file-preview] pdf preview degraded to text placeholder for %s', file_url)
|
||||
|
||||
mime = content_type or fallback_types.get(ext) or 'application/octet-stream'
|
||||
|
||||
from urllib.parse import quote
|
||||
filename = (request.args.get('name') or '').strip() or f'preview.{ext or "bin"}'
|
||||
filename = (request.args.get('name') or '').strip() or f"preview.{ext or 'bin'}"
|
||||
encoded_filename = quote(filename)
|
||||
ascii_filename = filename.encode('ascii', 'ignore').decode('ascii') or f'preview.{ext or "bin"}'
|
||||
|
||||
ascii_filename = filename.encode('ascii', 'ignore').decode('ascii') or f"preview.{ext or 'bin'}"
|
||||
disposition_type = 'attachment' if is_download else 'inline'
|
||||
|
||||
resp = Response(content, status=200, mimetype=mime)
|
||||
resp.headers['Content-Disposition'] = f"{disposition_type}; filename=\"{ascii_filename}\"; filename*=UTF-8''{encoded_filename}"
|
||||
resp.headers['Content-Disposition'] = f"""{disposition_type}; filename="{ascii_filename}"; filename*=UTF-8''{encoded_filename}"""
|
||||
resp.headers['Cache-Control'] = 'no-store'
|
||||
resp.headers['X-Preview-Actual-Ext'] = ext or ''
|
||||
resp.headers['X-Preview-Original-Ext'] = original_ext or ''
|
||||
|
||||
+31
-193
@@ -3,25 +3,22 @@ backend/app/api/integration.py
|
||||
文件用途:知识库外部集成查询接口
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from flask import Blueprint, abort, current_app, jsonify, request, send_file
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import joinedload
|
||||
|
||||
from app import db
|
||||
from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup
|
||||
|
||||
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
integration_bp = Blueprint('integration', __name__)
|
||||
|
||||
|
||||
def _require_integration_key():
|
||||
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
|
||||
incoming = str(request.headers.get('X-Integration-Key') or '').strip()
|
||||
|
||||
if not configured:
|
||||
return jsonify({'error': 'INTEGRATION_API_KEY is not configured'}), 503
|
||||
|
||||
raise ServiceUnavailableError('INTEGRATION_API_KEY is not configured')
|
||||
|
||||
if configured == incoming:
|
||||
return None
|
||||
@@ -37,7 +34,7 @@ def _require_integration_key():
|
||||
current_app.logger.warning(f"Integration API token validation failed: {e}")
|
||||
pass
|
||||
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
|
||||
|
||||
def _integration_base_url() -> str:
|
||||
@@ -46,107 +43,35 @@ def _integration_base_url() -> str:
|
||||
return explicit
|
||||
return request.host_url.rstrip('/')
|
||||
|
||||
|
||||
def _current_version(document: KbDocument) -> KbDocumentVersion | None:
|
||||
versions = list(getattr(document, 'versions', []) or [])
|
||||
if not versions:
|
||||
return None
|
||||
return next((item for item in versions if item.is_current), versions[0])
|
||||
|
||||
|
||||
def _document_query():
|
||||
return (
|
||||
db.session.query(KbDocument)
|
||||
.options(
|
||||
joinedload(KbDocument.group),
|
||||
joinedload(KbDocument.versions).joinedload(KbDocumentVersion.sync_records),
|
||||
)
|
||||
.filter(KbDocument.is_deleted.is_(False))
|
||||
)
|
||||
return 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)
|
||||
if not version:
|
||||
abort(404, description='No current version found.')
|
||||
|
||||
sync_record = sync_record or (
|
||||
next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None)
|
||||
or (version.sync_records[0] if getattr(version, 'sync_records', None) else None)
|
||||
)
|
||||
|
||||
sync_record = sync_record or (next((item for item in getattr(version, 'sync_records', []) if item.status == 'synced'), None) or (version.sync_records[0] if getattr(version, 'sync_records', None) else None))
|
||||
base_url = _integration_base_url()
|
||||
source_download_url = f'{base_url}/api/integration/files/{document.id}/download?kind=source'
|
||||
markdown_download_url = (
|
||||
f'{base_url}/api/integration/files/{document.id}/download?kind=md'
|
||||
if version.cleaned_file_path or version.cleaned_preview_path
|
||||
else None
|
||||
)
|
||||
|
||||
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,
|
||||
},
|
||||
}
|
||||
|
||||
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
|
||||
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:
|
||||
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,
|
||||
}
|
||||
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}
|
||||
|
||||
|
||||
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()
|
||||
query = _document_query().order_by(KbDocument.updated_at.desc(), KbDocument.id.desc())
|
||||
if knowledge_base_id is not None:
|
||||
query = query.filter(KbDocument.group_id == knowledge_base_id)
|
||||
if department_id is not None:
|
||||
query = query.join(KbGroup, KbGroup.id == KbDocument.group_id).filter(KbGroup.department_id == department_id)
|
||||
|
||||
documents = query.all()
|
||||
payload = []
|
||||
for document in documents:
|
||||
@@ -154,25 +79,22 @@ def _list_files_payload(
|
||||
if not version:
|
||||
continue
|
||||
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
|
||||
payload.append(_serialize_integration_document(document, version=version))
|
||||
return payload
|
||||
|
||||
|
||||
def _resolve_download_path(version: KbDocumentVersion, kind: str) -> tuple[Path, str]:
|
||||
if kind == 'source':
|
||||
path = Path(version.source_file_path)
|
||||
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
|
||||
if not preferred:
|
||||
abort(409, description='Markdown not ready.')
|
||||
path = Path(preferred)
|
||||
filename = f'document-{version.document_id}-v{version.version_no}.md'
|
||||
return path, filename
|
||||
|
||||
return (path, filename)
|
||||
|
||||
@integration_bp.before_request
|
||||
def _verify_integration_access():
|
||||
@@ -181,138 +103,66 @@ def _verify_integration_access():
|
||||
return result
|
||||
return None
|
||||
|
||||
|
||||
@integration_bp.route('/files/<int:file_id>', methods=['GET'])
|
||||
def get_file_detail(file_id: int):
|
||||
document = _document_query().filter(KbDocument.id == file_id).first()
|
||||
if not document:
|
||||
return jsonify({'error': 'Document not found.'}), 404
|
||||
raise NotFoundError('Document not found.')
|
||||
return jsonify(_serialize_integration_document(document))
|
||||
|
||||
|
||||
@integration_bp.route('/knowledge-bases', methods=['GET'])
|
||||
def list_knowledge_bases():
|
||||
department_id = request.args.get('department_id', type=int)
|
||||
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()
|
||||
)
|
||||
|
||||
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())
|
||||
)
|
||||
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()
|
||||
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:
|
||||
query = query.filter(KbGroup.department_id == department_id)
|
||||
if q:
|
||||
query = query.filter(KbGroup.name.ilike(f'%{q}%'))
|
||||
|
||||
rows = query.all()
|
||||
return jsonify({'data': [_serialize_knowledge_base(group, document_count=document_count) for group, document_count in rows]})
|
||||
|
||||
|
||||
@integration_bp.route('/files', methods=['GET'])
|
||||
def list_files():
|
||||
knowledge_base_id = request.args.get('knowledge_base_id', type=int)
|
||||
department_id = request.args.get('department_id', type=int)
|
||||
file_name = request.args.get('file_name')
|
||||
return jsonify({'data': _list_files_payload(
|
||||
knowledge_base_id=knowledge_base_id,
|
||||
department_id=department_id,
|
||||
file_name=file_name,
|
||||
)})
|
||||
|
||||
return jsonify({'data': _list_files_payload(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'])
|
||||
def list_files_for_knowledge_base(knowledge_base_id: int):
|
||||
return jsonify({'data': _list_files_payload(
|
||||
knowledge_base_id=knowledge_base_id,
|
||||
file_name=request.args.get('file_name'),
|
||||
)})
|
||||
|
||||
return jsonify({'data': _list_files_payload(knowledge_base_id=knowledge_base_id, file_name=request.args.get('file_name'))})
|
||||
|
||||
@integration_bp.route('/dify-file', methods=['GET'])
|
||||
def get_file_detail_by_dify():
|
||||
remote_document_id = str(request.args.get('remote_document_id') or '').strip()
|
||||
dataset_id = str(request.args.get('dataset_id') or '').strip() or None
|
||||
if not remote_document_id:
|
||||
return jsonify({'error': 'remote_document_id is required'}), 400
|
||||
|
||||
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())
|
||||
)
|
||||
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())
|
||||
if dataset_id:
|
||||
record_query = record_query.filter(KbDifySyncRecord.dataset_id == dataset_id)
|
||||
|
||||
record = record_query.first()
|
||||
version = record.document_version if record else None
|
||||
document = version.document if version else None
|
||||
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))
|
||||
|
||||
|
||||
@integration_bp.route('/dify-files/resolve', methods=['POST'])
|
||||
def resolve_files_by_dify():
|
||||
data = request.get_json(silent=True) or {}
|
||||
items = data.get('items') if isinstance(data.get('items'), list) else []
|
||||
if not items:
|
||||
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()
|
||||
})
|
||||
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()
|
||||
})
|
||||
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()})
|
||||
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:
|
||||
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:
|
||||
query = query.filter(
|
||||
(KbDifySyncRecord.dataset_id.in_(dataset_ids)) | (KbDifySyncRecord.dataset_id.is_(None))
|
||||
)
|
||||
|
||||
query = query.filter(KbDifySyncRecord.dataset_id.in_(dataset_ids) | KbDifySyncRecord.dataset_id.is_(None))
|
||||
records = query.all()
|
||||
records_by_key: dict[tuple[str | None, str], KbDifySyncRecord] = {}
|
||||
records_by_remote: dict[str, KbDifySyncRecord] = {}
|
||||
@@ -320,7 +170,6 @@ def resolve_files_by_dify():
|
||||
key = (record.dataset_id, record.remote_document_id)
|
||||
records_by_key.setdefault(key, record)
|
||||
records_by_remote.setdefault(record.remote_document_id, record)
|
||||
|
||||
payload = []
|
||||
for item in items:
|
||||
if not isinstance(item, dict):
|
||||
@@ -334,30 +183,19 @@ def resolve_files_by_dify():
|
||||
record = records_by_remote.get(requested_remote_document_id)
|
||||
version = record.document_version if record else None
|
||||
document = version.document if version else None
|
||||
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,
|
||||
})
|
||||
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})
|
||||
return jsonify({'data': payload})
|
||||
|
||||
|
||||
@integration_bp.route('/files/<int:file_id>/download', methods=['GET'])
|
||||
def download_file(file_id: int):
|
||||
kind = str(request.args.get('kind') or 'md').strip().lower()
|
||||
document = _document_query().filter(KbDocument.id == file_id).first()
|
||||
if not document:
|
||||
return jsonify({'error': 'Document not found.'}), 404
|
||||
|
||||
raise NotFoundError('Document not found.')
|
||||
version = _current_version(document)
|
||||
if not version:
|
||||
return jsonify({'error': 'No version found.'}), 404
|
||||
|
||||
raise NotFoundError('No version found.')
|
||||
path, filename = _resolve_download_path(version, kind)
|
||||
if not path.exists():
|
||||
return jsonify({'error': 'File not found on disk.'}), 404
|
||||
|
||||
return send_file(path, as_attachment=True, download_name=filename)
|
||||
raise NotFoundError('File not found on disk.')
|
||||
return send_file(path, as_attachment=True, download_name=filename)
|
||||
@@ -1,71 +1,49 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.services.schedule import _run_generic_check_job
|
||||
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.route('/<name>', methods=['POST'])
|
||||
def run_internal_job(name: str):
|
||||
key = name.strip().lower()
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
run_no = str(data.get("run_no") or "").strip()
|
||||
schedule_task_id = data.get("schedule_task_id")
|
||||
|
||||
run_no = str(data.get('run_no') or '').strip()
|
||||
schedule_task_id = data.get('schedule_task_id')
|
||||
task = None
|
||||
if schedule_task_id:
|
||||
task = db.session.get(ScheduleTask, int(schedule_task_id))
|
||||
if not task and key.isdigit():
|
||||
task = db.session.get(ScheduleTask, int(key))
|
||||
if not task:
|
||||
task = ScheduleTask.query.filter(
|
||||
ScheduleTask.platform_api_path.ilike(f"%{key}%")
|
||||
).first()
|
||||
task = ScheduleTask.query.filter(ScheduleTask.platform_api_path.ilike(f'%{key}%')).first()
|
||||
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
|
||||
if run_no:
|
||||
run = ScheduleRun.query.filter_by(run_no=run_no).first()
|
||||
if not run:
|
||||
from app.services.schedule.scheduler_service import _generate_run_no
|
||||
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 = ScheduleRun(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.commit()
|
||||
|
||||
if not run.dify_execution_snapshot:
|
||||
capture_dify_execution_snapshot(run, task)
|
||||
db.session.commit()
|
||||
|
||||
try:
|
||||
total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_generic_check_job(task, run)
|
||||
except Exception as exc:
|
||||
run.status = "failed"
|
||||
run.status = 'failed'
|
||||
run.error_message = str(exc)
|
||||
run.finished_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return jsonify({
|
||||
"error": str(exc),
|
||||
"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")
|
||||
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}})
|
||||
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
|
||||
run.total_count = total_count
|
||||
run.success_count = success_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.step_logs = step_logs if step_logs else None
|
||||
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
|
||||
|
||||
import threading
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
from flask import Response
|
||||
from io import BytesIO
|
||||
import json
|
||||
|
||||
from app.decorators import require_admin
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig
|
||||
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.scheduler_service import (
|
||||
create_task,
|
||||
run_task_now,
|
||||
update_task,
|
||||
_generate_run_no,
|
||||
_generate_test_run_no,
|
||||
_notify_schedule_run_wecom,
|
||||
)
|
||||
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
|
||||
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.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
schedule_admin_bp = Blueprint('schedule_admin', __name__)
|
||||
|
||||
|
||||
def _serialize_task_for_export(task: ScheduleTask, cfg_model: ScheduleTaskConfig | None) -> dict:
|
||||
payload = serialize_task(task)
|
||||
payload['config'] = _serialize_task_config(cfg_model) if cfg_model else None
|
||||
return payload
|
||||
|
||||
|
||||
def _serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict:
|
||||
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 "",
|
||||
}
|
||||
|
||||
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 ''}
|
||||
|
||||
@schedule_admin_bp.route('/schedule-config/<int:task_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_task_config(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
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()
|
||||
if not cfg_model:
|
||||
return jsonify({
|
||||
"data_source_type": task.data_source_type,
|
||||
"config": None,
|
||||
})
|
||||
return jsonify({
|
||||
"data_source_type": task.data_source_type,
|
||||
"config": _serialize_task_config(cfg_model),
|
||||
})
|
||||
|
||||
return jsonify({'data_source_type': task.data_source_type, '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'])
|
||||
@require_admin
|
||||
def update_schedule_task_config(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
if "data_source_type" in data:
|
||||
task.data_source_type = str(data["data_source_type"])
|
||||
if 'data_source_type' in data:
|
||||
task.data_source_type = str(data['data_source_type'])
|
||||
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_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
return jsonify({
|
||||
"data_source_type": task.data_source_type,
|
||||
"config": _serialize_task_config(cfg_model) if cfg_model else None,
|
||||
})
|
||||
return jsonify({'data_source_type': task.data_source_type, 'config': _serialize_task_config(cfg_model) if cfg_model else None})
|
||||
except Exception as e:
|
||||
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'])
|
||||
@require_admin
|
||||
def test_schedule_sql(task_id: int):
|
||||
cfg = get_schedule_sql_config_by_task_id(task_id)
|
||||
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 {}
|
||||
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()
|
||||
limit = min(int(data.get("limit") or 10), 100)
|
||||
|
||||
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()
|
||||
limit = min(int(data.get('limit') or 10), 100)
|
||||
base = cfg.base_fetch_sql or cfg.fetch_sql
|
||||
if cfg.base_fetch_sql:
|
||||
sql = _build_fetch_sql(base, custom_where, custom_order_by)
|
||||
else:
|
||||
sql = base
|
||||
|
||||
try:
|
||||
from app.services.schedule import _build_srm_conn_str
|
||||
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()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
rows = _fetch_records(conn_str, sql)
|
||||
|
||||
def _safe(v):
|
||||
if isinstance(v, decimal.Decimal):
|
||||
return float(v)
|
||||
@@ -142,75 +87,46 @@ def test_schedule_sql(task_id: int):
|
||||
return str(v)
|
||||
return v
|
||||
result_rows = [{k: _safe(v) for k, v in r.items()} for r in rows[:limit]]
|
||||
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,
|
||||
})
|
||||
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})
|
||||
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'])
|
||||
@require_admin
|
||||
def test_schedule_run(task_id: int):
|
||||
import time as _time
|
||||
from app.services.schedule.excel_service import export_schedule_result_excel
|
||||
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
raise NotFoundError('Not found')
|
||||
cfg = get_schedule_sql_config_by_task_id(task_id)
|
||||
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 {}
|
||||
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()
|
||||
limit = min(int(data.get("limit") or 3), 10)
|
||||
|
||||
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()
|
||||
limit = min(int(data.get('limit') or 3), 10)
|
||||
base = cfg.base_fetch_sql or cfg.fetch_sql
|
||||
if cfg.base_fetch_sql:
|
||||
test_sql = _build_fetch_sql(base, custom_where, custom_order_by)
|
||||
else:
|
||||
test_sql = base
|
||||
|
||||
from app.services.schedule import _build_srm_conn_str, _resolve_dify_agent, _resolve_schedule_user
|
||||
from app.services.schedule.srm_service import (
|
||||
_fetch_records,
|
||||
_run_check_job_loop,
|
||||
_build_record_text,
|
||||
_execute_writeback,
|
||||
)
|
||||
|
||||
if cfg.data_source and not cfg.data_source.is_empty():
|
||||
from app.services.schedule.srm_service import _fetch_records, _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()
|
||||
else:
|
||||
conn_str = _build_srm_conn_str()
|
||||
|
||||
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
|
||||
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.commit()
|
||||
|
||||
from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot
|
||||
capture_dify_execution_snapshot(run, task)
|
||||
db.session.commit()
|
||||
|
||||
if not cfg.fetch_sql:
|
||||
run.status = 'success'
|
||||
run.finished_at = datetime.utcnow()
|
||||
@@ -219,86 +135,49 @@ def test_schedule_run(task_id: int):
|
||||
if task.notify_enabled:
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
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()
|
||||
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,
|
||||
})
|
||||
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})
|
||||
|
||||
def _test_fetch_fn(conn_str_arg):
|
||||
return _fetch_records(conn_str_arg, test_sql)
|
||||
|
||||
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)))
|
||||
|
||||
test_pre_dify = None
|
||||
test_build_record = None
|
||||
|
||||
if cfg.detail_sql:
|
||||
|
||||
def _test_pre_dify(conn_str_arg, item, row_id_value):
|
||||
try:
|
||||
detail_rows = _fetch_records(conn_str_arg, cfg.detail_sql, params=(str(row_id_value),))
|
||||
except Exception as detail_exc:
|
||||
return {
|
||||
"dify_result": "人工判定",
|
||||
"dify_message": f"查询成分明细失败:{detail_exc}",
|
||||
"writeback_srm": False,
|
||||
"writeback_err": str(detail_exc),
|
||||
}
|
||||
return {'dify_result': '人工判定', 'dify_message': f'查询成分明细失败:{detail_exc}', 'writeback_srm': False, 'writeback_err': str(detail_exc)}
|
||||
detail_lines = []
|
||||
for dr in detail_rows:
|
||||
parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order]
|
||||
detail_lines.append(", ".join(parts))
|
||||
item["detail_text"] = "; ".join(detail_lines) if detail_lines else ""
|
||||
item["_detail_rows"] = detail_rows
|
||||
detail_lines.append(', '.join(parts))
|
||||
item['detail_text'] = '; '.join(detail_lines) if detail_lines else ''
|
||||
item['_detail_rows'] = detail_rows
|
||||
return None
|
||||
test_pre_dify = _test_pre_dify
|
||||
|
||||
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)
|
||||
return text, item.get("attachment")
|
||||
return (text, item.get('attachment'))
|
||||
test_build_record = _test_build_with_detail
|
||||
else:
|
||||
|
||||
def _test_build_simple(conn_str_arg, item, row_id_value):
|
||||
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
|
||||
|
||||
start_ts = _time.time()
|
||||
try:
|
||||
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,
|
||||
)
|
||||
|
||||
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)
|
||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||
if total_count == 0 and not errors:
|
||||
if total_count == 0 and (not errors):
|
||||
status = 'success'
|
||||
elif failed_count == 0:
|
||||
status = 'success'
|
||||
@@ -306,22 +185,13 @@ def test_schedule_run(task_id: int):
|
||||
status = 'failed'
|
||||
else:
|
||||
status = 'partial_failed'
|
||||
|
||||
header_order = cfg.alias_order if cfg.alias_order else None
|
||||
header_labels = cfg.header_labels if cfg.header_labels else None
|
||||
detail_alias_order = cfg.detail_alias_order or []
|
||||
try:
|
||||
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,
|
||||
)
|
||||
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)
|
||||
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.duration_ms = duration_ms
|
||||
run.status = status
|
||||
@@ -330,7 +200,7 @@ def test_schedule_run(task_id: int):
|
||||
run.failed_count = failed_count
|
||||
run.skipped_count = skipped_count
|
||||
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_name = file_name
|
||||
run.excel_file_size = file_size or 0
|
||||
@@ -338,10 +208,10 @@ def test_schedule_run(task_id: int):
|
||||
if task.notify_enabled:
|
||||
_notify_schedule_run_wecom(task, run)
|
||||
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()
|
||||
|
||||
import decimal, datetime as dt
|
||||
|
||||
def _safe(v):
|
||||
if isinstance(v, decimal.Decimal):
|
||||
return float(v)
|
||||
@@ -350,27 +220,11 @@ def test_schedule_run(task_id: int):
|
||||
if isinstance(v, dt.timedelta):
|
||||
return str(v)
|
||||
return v
|
||||
|
||||
safe_details = []
|
||||
for item in details:
|
||||
safe_item = {k: _safe(v) for k, v in item.items()}
|
||||
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:
|
||||
duration_ms = int((_time.time() - start_ts) * 1000)
|
||||
run.finished_at = datetime.utcnow()
|
||||
@@ -379,35 +233,24 @@ def test_schedule_run(task_id: int):
|
||||
run.error_message = str(e)
|
||||
db.session.commit()
|
||||
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'])
|
||||
@require_admin
|
||||
def get_schedules():
|
||||
return jsonify(list_tasks())
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/export', methods=['GET'])
|
||||
@require_admin
|
||||
def export_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
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()
|
||||
payload = {
|
||||
"schema_version": 1,
|
||||
"exported_at": datetime.utcnow().isoformat(),
|
||||
"schedules": [_serialize_task_for_export(task, cfg_model)],
|
||||
}
|
||||
payload = {'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)
|
||||
filename = f"{(task.schedule_no or f'schedule_{task.id}')}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
|
||||
return Response(
|
||||
body,
|
||||
mimetype='application/json; charset=utf-8',
|
||||
headers={'Content-Disposition': f'attachment; filename="{filename}"'},
|
||||
)
|
||||
|
||||
filename = f"{task.schedule_no or f'schedule_{task.id}'}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
|
||||
return Response(body, mimetype='application/json; charset=utf-8', headers={'Content-Disposition': f'attachment; filename="{filename}"'})
|
||||
|
||||
@schedule_admin_bp.route('/schedules/import', methods=['POST'])
|
||||
@require_admin
|
||||
@@ -415,13 +258,11 @@ def import_schedules():
|
||||
data = request.get_json(silent=True) or {}
|
||||
schedules = data.get('schedules')
|
||||
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()
|
||||
imported = 0
|
||||
skipped = 0
|
||||
errors: list[str] = []
|
||||
|
||||
for item in schedules:
|
||||
if not isinstance(item, dict):
|
||||
skipped += 1
|
||||
@@ -432,46 +273,19 @@ def import_schedules():
|
||||
owner_user_id = int(item.get('owner_user_id'))
|
||||
if not name or not cron_expr:
|
||||
raise ValueError('name or cron_expr missing')
|
||||
|
||||
existing = None
|
||||
schedule_no = str(item.get('schedule_no') or '').strip()
|
||||
if schedule_no:
|
||||
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
|
||||
|
||||
if existing:
|
||||
update_task(existing, payload=task_payload, actor_id=getattr(user, 'id', None))
|
||||
existing.data_source_type = task_payload['data_source_type']
|
||||
if cfg:
|
||||
upsert_schedule_task_config(existing.id, cfg)
|
||||
else:
|
||||
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),
|
||||
)
|
||||
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))
|
||||
task.data_source_type = task_payload['data_source_type']
|
||||
db.session.commit()
|
||||
if cfg:
|
||||
@@ -480,15 +294,8 @@ def import_schedules():
|
||||
except Exception as exc:
|
||||
errors.append(str(exc))
|
||||
skipped += 1
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({
|
||||
'ok': True,
|
||||
'imported': imported,
|
||||
'skipped': skipped,
|
||||
'errors': errors[:20],
|
||||
})
|
||||
|
||||
return jsonify({'ok': True, 'imported': imported, 'skipped': skipped, 'errors': errors[:20]})
|
||||
|
||||
@schedule_admin_bp.route('/schedules', methods=['POST'])
|
||||
@require_admin
|
||||
@@ -496,24 +303,11 @@ def post_schedule():
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
data_source_type = str(data.get('data_source_type') or 'database')
|
||||
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),
|
||||
)
|
||||
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))
|
||||
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.refresh(task)
|
||||
|
||||
config_data = data.get('config')
|
||||
if 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:
|
||||
cfg_model.dify_system_prompt = None
|
||||
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'])
|
||||
@require_admin
|
||||
def get_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['PATCH'])
|
||||
@require_admin
|
||||
def patch_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
user = get_current_user()
|
||||
|
||||
if "data_source_type" in data:
|
||||
task.data_source_type = str(data["data_source_type"])
|
||||
if 'data_source_type' in data:
|
||||
task.data_source_type = str(data['data_source_type'])
|
||||
db.session.commit()
|
||||
|
||||
config_data = data.get('config')
|
||||
if config_data:
|
||||
upsert_schedule_task_config(task_id, config_data)
|
||||
|
||||
task = update_task(task, payload=data, actor_id=getattr(user, 'id', None))
|
||||
|
||||
if not task.dify_agent_id:
|
||||
cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first()
|
||||
if cfg_model and cfg_model.dify_system_prompt:
|
||||
cfg_model.dify_system_prompt = None
|
||||
db.session.commit()
|
||||
|
||||
return jsonify(serialize_task(task))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.schedule.scheduler_service import request_cancel_run
|
||||
running_runs = db.session.query(ScheduleRun).filter(
|
||||
ScheduleRun.schedule_task_id == task_id,
|
||||
ScheduleRun.status == "running",
|
||||
).all()
|
||||
running_runs = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status == 'running').all()
|
||||
for rr in running_runs:
|
||||
request_cancel_run(rr.id)
|
||||
rr.status = "failed"
|
||||
rr.error_message = "排程已被删除,执行中断"
|
||||
rr.status = 'failed'
|
||||
rr.error_message = '排程已被删除,执行中断'
|
||||
rr.finished_at = datetime.utcnow()
|
||||
if running_runs:
|
||||
db.session.commit()
|
||||
|
||||
db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False)
|
||||
db.session.delete(task)
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/enable', methods=['POST'])
|
||||
@require_admin
|
||||
def enable_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
raise NotFoundError('Not found')
|
||||
task.enabled = True
|
||||
if task.cron_expr:
|
||||
try:
|
||||
@@ -606,44 +385,29 @@ def enable_schedule(task_id: int):
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/disable', methods=['POST'])
|
||||
@require_admin
|
||||
def disable_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
raise NotFoundError('Not found')
|
||||
task.enabled = False
|
||||
db.session.commit()
|
||||
return jsonify({'ok': True})
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/run', methods=['POST'])
|
||||
@require_admin
|
||||
def run_schedule(task_id: int):
|
||||
task = db.session.get(ScheduleTask, task_id)
|
||||
if not task:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
raise NotFoundError('Not found')
|
||||
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:
|
||||
return jsonify({'error': '该排程正在执行中,请等待完成后再试', 'run_id': existing.id}), 409
|
||||
|
||||
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',
|
||||
)
|
||||
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')
|
||||
db.session.add(run)
|
||||
db.session.commit()
|
||||
|
||||
app = current_app._get_current_object()
|
||||
run_id = run.id
|
||||
|
||||
@@ -665,15 +429,12 @@ def run_schedule(task_id: int):
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
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}")
|
||||
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.start()
|
||||
|
||||
fresh = db.session.get(ScheduleRun, run_id)
|
||||
return jsonify(serialize_run(fresh))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedules/<int:task_id>/runs', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_runs(task_id: int):
|
||||
@@ -695,24 +456,22 @@ def get_schedule_runs(task_id: int):
|
||||
pass
|
||||
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'])
|
||||
@require_admin
|
||||
def get_schedule_run(run_id: int):
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
raise NotFoundError('Not found')
|
||||
return jsonify(serialize_run(run))
|
||||
|
||||
|
||||
@schedule_admin_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||
@require_admin
|
||||
def get_schedule_run_excel(run_id: int):
|
||||
from io import BytesIO
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
raise NotFoundError('Not found')
|
||||
if not run.excel_file_data:
|
||||
return jsonify({'error': 'Excel not found'}), 404
|
||||
raise NotFoundError('Excel not found')
|
||||
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')
|
||||
+244
-1049
File diff suppressed because it is too large.
Load diff
@@ -1,27 +1,20 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from flask import Blueprint, jsonify, request, send_file
|
||||
|
||||
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.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
|
||||
workspace_schedule_bp = Blueprint('workspace_schedule', __name__)
|
||||
|
||||
|
||||
def _require_user():
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return None, (jsonify({'error': 'Unauthorized'}), 401)
|
||||
return user, None
|
||||
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
@workspace_schedule_bp.route('/schedule-runs', methods=['GET'])
|
||||
def workspace_schedule_runs():
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
status = str(request.args.get('status') or '').strip() or None
|
||||
schedule_name = str(request.args.get('schedule_name') or '').strip() or None
|
||||
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_before = datetime.fromisoformat(started_before_str) if started_before_str else None
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
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,
|
||||
))
|
||||
|
||||
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))
|
||||
|
||||
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>', methods=['GET'])
|
||||
def workspace_schedule_run_detail(run_id: int):
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
raise NotFoundError('Not found')
|
||||
if not can_view_run(run, user.id):
|
||||
return jsonify({'error': 'Forbidden'}), 403
|
||||
raise ForbiddenError('Forbidden')
|
||||
return jsonify(serialize_run(run))
|
||||
|
||||
|
||||
@workspace_schedule_bp.route('/schedule-runs/<int:run_id>/excel', methods=['GET'])
|
||||
def workspace_schedule_run_excel(run_id: int):
|
||||
from io import BytesIO
|
||||
user, err = _require_user()
|
||||
if err:
|
||||
return err
|
||||
user = _require_user()
|
||||
run = get_run(run_id)
|
||||
if not run:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
raise NotFoundError('Not found')
|
||||
if not can_view_run(run, user.id):
|
||||
return jsonify({'error': 'Forbidden'}), 403
|
||||
raise ForbiddenError('Forbidden')
|
||||
if not run.excel_file_data:
|
||||
return jsonify({'error': 'Excel not found'}), 404
|
||||
raise NotFoundError('Excel not found')
|
||||
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
|
||||
文件用途:权限控制装饰器集合
|
||||
@@ -9,7 +8,7 @@ from functools import wraps
|
||||
from flask import request, jsonify, g, current_app
|
||||
from app.models import Agent, 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:
|
||||
"""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
|
||||
return user
|
||||
|
||||
|
||||
def require_agent_permission(f):
|
||||
"""
|
||||
装饰器:检查当前用户是否有指定 Agent 的访问权限
|
||||
@@ -35,42 +33,24 @@ def require_agent_permission(f):
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
# 从 JSON 请求体中解析数据
|
||||
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,则返回 400 错误
|
||||
if not agent_id:
|
||||
return jsonify({'error': 'agent_id is required'}), 400
|
||||
|
||||
# 获取当前用户
|
||||
raise ValidationError('agent_id is required')
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
|
||||
# 查询目标 Agent 是否存在
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
agent = Agent.query.get(agent_id)
|
||||
if not agent:
|
||||
return jsonify({'error': 'Agent not found'}), 404
|
||||
|
||||
# 将 agent 对象挂在 g 上,方便下游使用
|
||||
raise NotFoundError('Agent not found')
|
||||
g.current_agent = agent
|
||||
|
||||
# 如果用户是管理员,跳过权限检查直接放行
|
||||
if user.role == 'admin':
|
||||
return f(*args, **kwargs)
|
||||
|
||||
# 非管理员:检查多对多关联表中是否存在权限
|
||||
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 decorated_function
|
||||
|
||||
|
||||
def require_admin(f):
|
||||
"""
|
||||
装饰器:限制只有管理员角色才能访问的接口
|
||||
@@ -81,16 +61,12 @@ def require_admin(f):
|
||||
|
||||
@wraps(f)
|
||||
def decorated_function(*args, **kwargs):
|
||||
# 获取当前用户
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
return jsonify({'error': 'Unauthorized'}), 401
|
||||
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and not request.headers.get('Authorization'):
|
||||
return jsonify({'error': 'JWT token is required'}), 401
|
||||
# 如果不是管理员,则返回 403
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and (not request.headers.get('Authorization')):
|
||||
raise UnauthorizedError('JWT token is required')
|
||||
if user.role != 'admin':
|
||||
return jsonify({'error': 'Admin privilege required'}), 403
|
||||
# 是管理员则放行
|
||||
raise ForbiddenError('Admin privilege required')
|
||||
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 {},
|
||||
)
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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,80 @@
|
||||
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 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());
|
||||
};
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* 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}` : '';
|
||||
if (key && i18n.global.te(key)) {
|
||||
return String(i18n.global.t(key));
|
||||
}
|
||||
if (fallbackMessage) return fallbackMessage;
|
||||
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 { BusinessError, requestJson } from './client';
|
||||
|
||||
export interface KbGroup {
|
||||
id: number;
|
||||
@@ -116,11 +117,14 @@ export interface KbListResponse<T> {
|
||||
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> => {
|
||||
try {
|
||||
const res = await fetch(path, { headers: getAuthHeaders() });
|
||||
if (!res.ok) return fallback;
|
||||
return (await res.json()) as T;
|
||||
return await requestJson<T>(path, auth());
|
||||
} catch {
|
||||
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>> => {
|
||||
try {
|
||||
const res = await fetch(path, { headers: getAuthHeaders() });
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return {
|
||||
ok: false,
|
||||
data: fallback,
|
||||
error: data?.error || '知识库接口请求失败',
|
||||
status: res.status,
|
||||
};
|
||||
}
|
||||
return { ok: true, data: (await res.json()) as T, status: res.status };
|
||||
} catch {
|
||||
return { ok: false, data: fallback, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
const data = await requestJson<T>(path, auth());
|
||||
return { ok: true, data };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
return {
|
||||
ok: false,
|
||||
data: fallback,
|
||||
error: kbErrorMessage(e, '知识库接口请求失败'),
|
||||
status: err.status,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
@@ -165,21 +166,14 @@ export const createKbGroup = async (payload: {
|
||||
description?: string;
|
||||
}): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
|
||||
try {
|
||||
const res = await fetch('/api/kb/groups', {
|
||||
const group = await requestJson<KbGroup>('/api/kb/groups', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '创建知识库分组失败' };
|
||||
}
|
||||
return { ok: true, group: (await res.json()) as KbGroup };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
return { ok: true, group };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '创建知识库分组失败') };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -199,21 +193,14 @@ export const updateKbDifySettings = async (
|
||||
payload: Partial<KbDifySettings>
|
||||
): Promise<{ ok: boolean; error?: string; settings?: KbDifySettings }> => {
|
||||
try {
|
||||
const res = await fetch('/api/kb/dify/settings', {
|
||||
const settings = await requestJson<KbDifySettings>('/api/kb/dify/settings', {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '保存 Dify 设置失败' };
|
||||
}
|
||||
return { ok: true, settings: (await res.json()) as KbDifySettings };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
return { ok: true, settings };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '保存 Dify 设置失败') };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -225,18 +212,13 @@ export const runKbJob = async (
|
||||
jobId: number | string
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
|
||||
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',
|
||||
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 };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '执行任务失败') };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -245,21 +227,14 @@ export const createKbDocument = async (
|
||||
payload: { title: string; description?: string }
|
||||
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/groups/${groupId}/files`, {
|
||||
const document = await requestJson<KbDocumentItem>(`/api/kb/groups/${groupId}/files`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '创建文档失败' };
|
||||
}
|
||||
return { ok: true, document: (await res.json()) as KbDocumentItem };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
return { ok: true, document };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '创建文档失败') };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -268,21 +243,14 @@ export const updateKbDocument = async (
|
||||
payload: { title: string; description?: string; status?: string }
|
||||
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/documents/${documentId}`, {
|
||||
const document = await requestJson<KbDocumentItem>(`/api/kb/documents/${documentId}`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '更新文档失败' };
|
||||
}
|
||||
return { ok: true, document: (await res.json()) as KbDocumentItem };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
return { ok: true, document };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '更新文档失败') };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -290,17 +258,10 @@ export const deleteKbDocument = async (
|
||||
documentId: number
|
||||
): Promise<{ ok: boolean; error?: string }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/documents/${documentId}`, {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '删除文档失败' };
|
||||
}
|
||||
await requestJson(`/api/kb/documents/${documentId}`, { method: 'DELETE', ...auth() });
|
||||
return { ok: true };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '删除文档失败') };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -318,8 +279,15 @@ export const getKbDocumentVersionSourceFile = async (
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '读取原始文件失败' };
|
||||
let message = '读取原始文件失败';
|
||||
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 filenameMatch = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^"]+)"?/i);
|
||||
@@ -345,16 +313,10 @@ export const getKbDocumentMarkdown = async (
|
||||
documentId: number
|
||||
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/documents/${documentId}/markdown`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
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: '知识库接口暂未就绪,请稍后再试' };
|
||||
const data = await requestJson<KbDocumentMarkdown>(`/api/kb/documents/${documentId}/markdown`, auth());
|
||||
return { ok: true, data };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '读取清洗后的 Markdown 失败') };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -363,21 +325,14 @@ export const updateKbDocumentMarkdown = async (
|
||||
payload: { content: string }
|
||||
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/documents/${documentId}/markdown`, {
|
||||
const data = await requestJson<KbDocumentMarkdown>(`/api/kb/documents/${documentId}/markdown`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) {
|
||||
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: '知识库接口暂未就绪,请稍后再试' };
|
||||
return { ok: true, data };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '保存 Markdown 失败') };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -388,22 +343,22 @@ export const uploadKbDocumentVersion = async (
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
const res = await fetch(`/api/kb/documents/${documentId}/upload`, {
|
||||
const version = await requestJson<KbDocumentVersionItem>(`/api/kb/documents/${documentId}/upload`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
...auth(),
|
||||
body: formData,
|
||||
});
|
||||
if (!res.ok) {
|
||||
if (res.status === 413) {
|
||||
return { ok: false, error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试', status: res.status };
|
||||
}
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '上传文档版本失败', status: res.status };
|
||||
return { ok: true, version };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
if (err.status === 413) {
|
||||
return {
|
||||
ok: false,
|
||||
error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试',
|
||||
status: 413,
|
||||
};
|
||||
}
|
||||
return { ok: true, version: (await res.json()) as KbDocumentVersionItem, status: res.status };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
return { ok: false, error: kbErrorMessage(e, '上传文档版本失败'), status: err.status };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -412,21 +367,15 @@ export const createKbPathUploadJob = async (
|
||||
payload: { total_files: number; selected_paths: string[] }
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
|
||||
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',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
return { ok: false, error: data?.error || '创建路径上传任务失败', status: res.status };
|
||||
}
|
||||
return { ok: true, job: data as KbJob, status: res.status };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
return { ok: false, error: kbErrorMessage(e, '创建路径上传任务失败'), status: err.status };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -439,19 +388,14 @@ export const uploadKbPathJobFile = async (
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('relative_path', relativePath);
|
||||
|
||||
const res = await fetch(`/api/kb/path-upload-jobs/${jobId}/files`, {
|
||||
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/files`, {
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders(),
|
||||
...auth(),
|
||||
body: formData,
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
return { ok: false, error: data?.error || '上传路径文件失败' };
|
||||
}
|
||||
return { ok: true, job: data as KbJob };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '上传路径文件失败') };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -459,17 +403,13 @@ export const finalizeKbPathUploadJob = async (
|
||||
jobId: number | string,
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
|
||||
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',
|
||||
headers: getAuthHeaders(),
|
||||
...auth(),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
return { ok: false, error: data?.error || '提交路径上传任务失败' };
|
||||
}
|
||||
return { ok: true, job: data as KbJob };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '提交路径上传任务失败') };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -478,21 +418,15 @@ export const retryFailedKbPathUploadJob = async (
|
||||
payload?: { relative_paths?: string[] },
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
|
||||
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',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload || {}),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
return { ok: false, error: data?.error || '重试失败文件失败', status: res.status };
|
||||
}
|
||||
return { ok: true, job: data as KbJob, status: res.status };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
return { ok: false, error: kbErrorMessage(e, '重试失败文件失败'), status: err.status };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -500,18 +434,13 @@ export const syncKbDocumentToDify = async (
|
||||
documentId: number
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
|
||||
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',
|
||||
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 };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '同步到 Dify 失败') };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -520,21 +449,14 @@ export const updateKbGroup = async (
|
||||
payload: { name: string; description?: string }
|
||||
): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/groups/${groupId}`, {
|
||||
const group = await requestJson<KbGroup>(`/api/kb/groups/${groupId}`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '更新知识库分组失败' };
|
||||
}
|
||||
return { ok: true, group: (await res.json()) as KbGroup };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
return { ok: true, group };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '更新知识库分组失败') };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -542,16 +464,9 @@ export const deleteKbGroup = async (
|
||||
groupId: number
|
||||
): Promise<{ ok: boolean; error?: string }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/groups/${groupId}`, {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return { ok: false, error: data?.error || '删除知识库分组失败' };
|
||||
}
|
||||
await requestJson(`/api/kb/groups/${groupId}`, { method: 'DELETE', ...auth() });
|
||||
return { ok: true };
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '删除知识库分组失败') };
|
||||
}
|
||||
};
|
||||
@@ -1,4 +1,5 @@
|
||||
import { getAuthHeaders } from '../utils/auth';
|
||||
import { requestJson } from './client';
|
||||
|
||||
export interface ScheduleTask {
|
||||
id: number;
|
||||
@@ -70,9 +71,7 @@ export interface DifyExecutionSnapshot {
|
||||
}
|
||||
|
||||
async function getJson<T>(url: string): Promise<T> {
|
||||
const res = await fetch(url, { headers: getAuthHeaders() });
|
||||
if (!res.ok) throw new Error((await res.json().catch(() => ({})))?.error || 'Request failed');
|
||||
return (await res.json()) as T;
|
||||
return requestJson<T>(url, { headers: getAuthHeaders() });
|
||||
}
|
||||
|
||||
export const listAdminSchedules = () =>
|
||||
@@ -81,39 +80,37 @@ export const listAdminSchedules = () =>
|
||||
export const exportAdminScheduleUrl = (taskId: number) => `/api/admin/schedules/${taskId}/export`;
|
||||
|
||||
export const importAdminSchedules = async (payload: any) => {
|
||||
const res = await fetch('/api/admin/schedules/import', {
|
||||
return requestJson('/api/admin/schedules/import', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
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) =>
|
||||
getJson<{ data_source_type: string; config: Record<string, any> | null }>(`/api/admin/schedule-config/${taskId}`);
|
||||
|
||||
export const updateAdminScheduleTaskConfig = (taskId: number, payload: Record<string, any>) =>
|
||||
fetch(`/api/admin/schedule-config/${taskId}`, {
|
||||
requestJson(`/api/admin/schedule-config/${taskId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
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 }) =>
|
||||
fetch(`/api/admin/schedule-config/${taskId}/test-sql`, {
|
||||
requestJson<TestScheduleSqlResult>(`/api/admin/schedule-config/${taskId}/test-sql`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
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 {
|
||||
@@ -133,38 +130,35 @@ export interface TestScheduleRunResult {
|
||||
}
|
||||
|
||||
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',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
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> }) =>
|
||||
fetch('/api/admin/schedules', {
|
||||
requestJson('/api/admin/schedules', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
export const updateAdminSchedule = (id: number, payload: Partial<ScheduleTask> & { config?: Record<string, any> }) =>
|
||||
fetch(`/api/admin/schedules/${id}`, {
|
||||
requestJson(`/api/admin/schedules/${id}`, {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
export const deleteAdminSchedule = (id: number) =>
|
||||
fetch(`/api/admin/schedules/${id}`, {
|
||||
requestJson(`/api/admin/schedules/${id}`, {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
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) =>
|
||||
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 }) => {
|
||||
const sp = new URLSearchParams();
|
||||
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());
|
||||
+77
-1
@@ -1,4 +1,4 @@
|
||||
import { createI18n } from 'vue-i18n';
|
||||
import { createI18n } from 'vue-i18n';
|
||||
|
||||
const messages = {
|
||||
'en': {
|
||||
@@ -152,6 +152,25 @@ const messages = {
|
||||
confirm: 'OK'
|
||||
}
|
||||
},
|
||||
errors: {
|
||||
generic: 'Request failed.',
|
||||
codes: {
|
||||
AUTH_UNAUTHORIZED: 'Please log in first.',
|
||||
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: {
|
||||
title: 'Schedule Runs',
|
||||
refresh: 'Refresh',
|
||||
@@ -1606,6 +1625,25 @@ const messages = {
|
||||
confirm: '确定'
|
||||
}
|
||||
},
|
||||
errors: {
|
||||
generic: '请求失败。',
|
||||
codes: {
|
||||
AUTH_UNAUTHORIZED: '请先登录。',
|
||||
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: {
|
||||
title: '排程记录',
|
||||
refresh: '刷新',
|
||||
@@ -3024,6 +3062,25 @@ const messages = {
|
||||
confirm: '確定'
|
||||
}
|
||||
},
|
||||
errors: {
|
||||
generic: '請求失敗。',
|
||||
codes: {
|
||||
AUTH_UNAUTHORIZED: '請先登入。',
|
||||
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: {
|
||||
title: '排程記錄',
|
||||
refresh: '刷新',
|
||||
@@ -4317,6 +4374,25 @@ const messages = {
|
||||
confirm: 'ตกลง'
|
||||
}
|
||||
},
|
||||
errors: {
|
||||
generic: 'คำขอล้มเหลว',
|
||||
codes: {
|
||||
AUTH_UNAUTHORIZED: 'กรุณาเข้าสู่ระบบก่อน',
|
||||
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: {
|
||||
title: 'บันทึกการตั้งเวลา',
|
||||
refresh: 'รีเฟรช',
|
||||
|
||||
+233
-431
File diff suppressed because it is too large.
Load diff
+77
-127
@@ -1,6 +1,4 @@
|
||||
|
||||
|
||||
<script setup lang="ts">
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* ChatView.vue
|
||||
* 文件用途:单个 Agent 的对话界面
|
||||
@@ -29,6 +27,23 @@ import { copyTextToClipboard } from '../utils/clipboard';
|
||||
import { setLastChatAgentId } from '../utils/lastChatAgent';
|
||||
import { openAgentChatTab, registerOpenAgentId } from '../utils/agentTabs';
|
||||
import ChatShell from '../layouts/ChatShell.vue';
|
||||
import { BusinessError } from '../api/client';
|
||||
import {
|
||||
listChatSessions,
|
||||
deleteAllChatSessions,
|
||||
deleteChatSession,
|
||||
listChatMessages,
|
||||
saveLocalChatMessage,
|
||||
resolveChatSourceFile,
|
||||
listOaEmployees,
|
||||
} from '../api/chat';
|
||||
import {
|
||||
getUserProfile,
|
||||
getLeaveBalance,
|
||||
submitLeaveWorkflow,
|
||||
getUserAgent,
|
||||
listUserAgents,
|
||||
} from '../api/user';
|
||||
|
||||
const { t, locale } = useI18n();
|
||||
const { appliedTheme, toggleLightDark } = useTheme();
|
||||
@@ -556,18 +571,11 @@ const resolveSourceLink = async (file: SourceFileLink): Promise<{ name: string;
|
||||
throw new Error('当前源文件暂未返回可预览链接');
|
||||
}
|
||||
|
||||
const params = new URLSearchParams({
|
||||
agent_id: String(agentId),
|
||||
const data = await resolveChatSourceFile({
|
||||
agent_id: agentId,
|
||||
dataset_id: file.datasetId,
|
||||
remote_document_id: file.remoteDocumentId,
|
||||
});
|
||||
const response = await fetch(`/api/chat/source-file?${params.toString()}`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
const data = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw new Error(data?.error || `HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const resolvedUrl = normalizeUrl(data?.source_download_url || '');
|
||||
if (!resolvedUrl) {
|
||||
@@ -858,18 +866,17 @@ const fetchLeaveAgents = async (isLoadMore = false) => {
|
||||
|
||||
leaveAgentLoading.value = true;
|
||||
try {
|
||||
const res = await fetch(`/api/chat/oa/employees?keyword=${encodeURIComponent(leaveAgentKeyword.value)}&page=${leaveAgentPage.value}&page_size=20&agent_id=${agentId}`, {
|
||||
headers: getAuthHeaders()
|
||||
const data = await listOaEmployees(agentId, {
|
||||
keyword: leaveAgentKeyword.value,
|
||||
page: leaveAgentPage.value,
|
||||
page_size: 20,
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (isLoadMore) {
|
||||
leaveAgentOptions.value.push(...data.items);
|
||||
} else {
|
||||
leaveAgentOptions.value = data.items;
|
||||
}
|
||||
leaveAgentHasMore.value = leaveAgentOptions.value.length < data.total;
|
||||
if (isLoadMore) {
|
||||
leaveAgentOptions.value.push(...data.items);
|
||||
} else {
|
||||
leaveAgentOptions.value = data.items;
|
||||
}
|
||||
leaveAgentHasMore.value = leaveAgentOptions.value.length < data.total;
|
||||
} catch (e) {
|
||||
console.error('Failed to load OA employees', e);
|
||||
} finally {
|
||||
@@ -891,14 +898,13 @@ const loadAllAgents = async () => {
|
||||
if (!leaveAgentHasMore.value || leaveAgentLoading.value) return;
|
||||
leaveAgentLoading.value = true;
|
||||
try {
|
||||
const res = await fetch(`/api/chat/oa/employees?keyword=${encodeURIComponent(leaveAgentKeyword.value)}&page=1&page_size=100000&agent_id=${agentId}`, {
|
||||
headers: getAuthHeaders()
|
||||
const data = await listOaEmployees(agentId, {
|
||||
keyword: leaveAgentKeyword.value,
|
||||
page: 1,
|
||||
page_size: 100000,
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
leaveAgentOptions.value = data.items;
|
||||
leaveAgentHasMore.value = false;
|
||||
}
|
||||
leaveAgentOptions.value = data.items;
|
||||
leaveAgentHasMore.value = false;
|
||||
} catch (e) {
|
||||
console.error('Failed to load all OA employees', e);
|
||||
} finally {
|
||||
@@ -1187,29 +1193,19 @@ const isStrongLeaveIntent = (content: string) => {
|
||||
|
||||
const saveLocalMessageToBackend = async (msg: any, userQuery: string = '') => {
|
||||
try {
|
||||
const res = await fetch('/api/chat/messages/local', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders()
|
||||
},
|
||||
body: JSON.stringify({
|
||||
conversation_id: conversationId.value,
|
||||
type: msg.type,
|
||||
content: msg.content,
|
||||
payload: msg.payload,
|
||||
query: userQuery,
|
||||
agent_id: agentId
|
||||
})
|
||||
const data = await saveLocalChatMessage({
|
||||
conversation_id: conversationId.value,
|
||||
type: msg.type,
|
||||
content: msg.content,
|
||||
payload: msg.payload,
|
||||
query: userQuery,
|
||||
agent_id: agentId,
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
if (!conversationId.value && data.conversation_id) {
|
||||
conversationId.value = data.conversation_id;
|
||||
}
|
||||
if (data.chat_log_id) {
|
||||
msg.chat_log_id = data.chat_log_id;
|
||||
}
|
||||
if (!conversationId.value && data.conversation_id) {
|
||||
conversationId.value = data.conversation_id;
|
||||
}
|
||||
if (data.chat_log_id) {
|
||||
msg.chat_log_id = data.chat_log_id;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to save local message', e);
|
||||
@@ -1234,11 +1230,7 @@ const checkLeaveBalance = async (leaveTypeCode: string): Promise<{
|
||||
remaining_hours: number | null;
|
||||
} | null> => {
|
||||
try {
|
||||
const res = await fetch(`/api/user/leave-balance?leave_type=${encodeURIComponent(leaveTypeCode)}`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!res.ok) return null;
|
||||
return await res.json();
|
||||
return await getLeaveBalance(leaveTypeCode);
|
||||
} catch (e) {
|
||||
console.error('Failed to check leave balance', e);
|
||||
return null;
|
||||
@@ -1316,10 +1308,8 @@ const startLocalLeaveFlow = async (content: string) => {
|
||||
try {
|
||||
const keyword = payload.form.applicantName || payload.form.employeeId;
|
||||
if (keyword) {
|
||||
const res = await fetch(`/api/chat/oa/employees?keyword=${encodeURIComponent(keyword)}&page=1&page_size=1&agent_id=${agentId}`, { headers: getAuthHeaders() });
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
const match = (data.items || []).find((item: LeaveAgentOption) => item.employeeId === payload.form.employeeId);
|
||||
const data = await listOaEmployees(agentId, { keyword, page: 1, page_size: 1 });
|
||||
const match = (data.items || []).find((item: LeaveAgentOption) => item.employeeId === payload.form.employeeId);
|
||||
if (match) {
|
||||
payload.form.fillerJobTitle = match.jobtitle || '';
|
||||
payload.form.fillerJobTitleName = match.jobtitleName || '';
|
||||
@@ -1335,7 +1325,6 @@ const startLocalLeaveFlow = async (content: string) => {
|
||||
payload.form.applicantDepartmentName = match.departmentName || '';
|
||||
payload.form.applicantSubCompanyName = match.subcompanyName || '';
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to prefill OA user info', e);
|
||||
@@ -1396,9 +1385,7 @@ const formatYesNoLabel = (value: 0 | 1 | null) => {
|
||||
const syncCurrentUserProfile = async () => {
|
||||
if (currentUser.value?.real_name?.trim()) return;
|
||||
try {
|
||||
const res = await fetch('/api/user/profile', { headers: getAuthHeaders() });
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
const data = await getUserProfile();
|
||||
currentUser.value = { ...currentUser.value, ...data };
|
||||
} catch (e) {
|
||||
console.error('Failed to load current user profile', e);
|
||||
@@ -1819,19 +1806,7 @@ const confirmLeaveSubmission = async (chatMsg: any) => {
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/user/leave-workflow/submit', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...getAuthHeaders(),
|
||||
},
|
||||
body: JSON.stringify(payload.form),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
throw new Error(data?.error || t('chat.oaLeaveSubmitFailed'));
|
||||
}
|
||||
|
||||
const data = await submitLeaveWorkflow(payload.form);
|
||||
const resultMsg = {
|
||||
role: 'assistant' as const,
|
||||
type: 'leave-result' as const,
|
||||
@@ -1916,10 +1891,7 @@ const regenerate = () => {
|
||||
// 加载历史记录
|
||||
const loadHistory = async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/chat/sessions?agent_id=${agentId}`, { headers: getAuthHeaders() });
|
||||
if (res.ok) {
|
||||
history.value = await res.json();
|
||||
}
|
||||
history.value = await listChatSessions(agentId);
|
||||
} catch (e) {
|
||||
console.error('Failed to load history', e);
|
||||
}
|
||||
@@ -1928,16 +1900,11 @@ const loadHistory = async () => {
|
||||
const clearAllHistory = async () => {
|
||||
openDeleteConfirmDialog(t('chat.confirmClearHistory'), async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/chat/sessions?agent_id=${agentId}`, {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
if (res.ok) {
|
||||
history.value = [];
|
||||
runs.value = [];
|
||||
if (conversationId.value || activeRunId.value) {
|
||||
startNewChat();
|
||||
}
|
||||
await deleteAllChatSessions(agentId);
|
||||
history.value = [];
|
||||
runs.value = [];
|
||||
if (conversationId.value || activeRunId.value) {
|
||||
startNewChat();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to clear history', e);
|
||||
@@ -1949,15 +1916,10 @@ const deleteHistoryItem = async (id: string, event: Event) => {
|
||||
event.stopPropagation();
|
||||
openDeleteConfirmDialog(t('chat.confirmDeleteHistoryItem'), async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/chat/sessions/${id}?agent_id=${agentId}`, {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
if (res.ok) {
|
||||
history.value = history.value.filter(h => h.conversation_id !== id);
|
||||
if (conversationId.value === id) {
|
||||
startNewChat();
|
||||
}
|
||||
await deleteChatSession(id, agentId);
|
||||
history.value = history.value.filter(h => h.conversation_id !== id);
|
||||
if (conversationId.value === id) {
|
||||
startNewChat();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Failed to delete history item', e);
|
||||
@@ -1971,13 +1933,8 @@ const loadConversation = async (id: string) => {
|
||||
try {
|
||||
activeRunId.value = null;
|
||||
isThinking.value = false;
|
||||
const res = await fetch(`/api/chat/messages?conversation_id=${id}&agent_id=${agentId}`, { headers: getAuthHeaders() });
|
||||
if (res.ok) {
|
||||
messages.value = await res.json();
|
||||
conversationId.value = id;
|
||||
|
||||
// Reset feedback state
|
||||
}
|
||||
messages.value = await listChatMessages(id, agentId);
|
||||
conversationId.value = id;
|
||||
} catch (e) {
|
||||
console.error('Failed to load conversation', e);
|
||||
}
|
||||
@@ -1989,33 +1946,26 @@ const startNewChat = () => {
|
||||
|
||||
const loadAgent = async () => {
|
||||
try {
|
||||
const res = await fetch(`/api/user/agents/${agentId}`, { headers: getAuthHeaders() });
|
||||
if (res.ok) {
|
||||
currentAgent.value = await res.json();
|
||||
} else {
|
||||
if (res.status === 403) {
|
||||
msg.error(t('workspace.permission.denied') || 'Access denied');
|
||||
router.push('/workspace?no_redirect=1');
|
||||
return;
|
||||
}
|
||||
currentAgent.value = { name: t('workspace.unknownAgent') };
|
||||
}
|
||||
currentAgent.value = await getUserAgent(agentId);
|
||||
} catch (e) {
|
||||
if (e instanceof BusinessError && e.status === 403) {
|
||||
msg.error(t('workspace.permission.denied') || 'Access denied');
|
||||
router.push('/workspace?no_redirect=1');
|
||||
return;
|
||||
}
|
||||
console.error('Failed to load agent', e);
|
||||
currentAgent.value = { name: t('workspace.unknownAgent') };
|
||||
}
|
||||
};
|
||||
|
||||
const loadUserAgents = async () => {
|
||||
try {
|
||||
const res = await fetch('/api/agents', { headers: getAuthHeaders() });
|
||||
if (res.ok) {
|
||||
const agents = await res.json();
|
||||
userAgents.value = Array.isArray(agents)
|
||||
? agents.filter((a: any) => a.id !== agentId && (a.dify_app_type || 'chatflow') === 'chatflow')
|
||||
: [];
|
||||
if (userAgents.value.length === 0) {
|
||||
showAgentPanel.value = false;
|
||||
}
|
||||
const agents = await listUserAgents();
|
||||
userAgents.value = Array.isArray(agents)
|
||||
? agents.filter((a: any) => a.id !== agentId && (a.dify_app_type || 'chatflow') === 'chatflow')
|
||||
: [];
|
||||
if (userAgents.value.length === 0) {
|
||||
showAgentPanel.value = false;
|
||||
}
|
||||
} catch (e) {
|
||||
userAgents.value = [];
|
||||
|
||||
@@ -3,6 +3,7 @@ import { ref } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { Lock, AlertCircle, CheckCircle } from 'lucide-vue-next';
|
||||
import MinimalShell from '../layouts/MinimalShell.vue';
|
||||
import { resetPasswordConfirm } from '../api/user';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
@@ -32,29 +33,15 @@ const handleReset = async () => {
|
||||
message.value = '';
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/user/reset-password-confirm', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
token: token.value,
|
||||
new_password: password.value
|
||||
})
|
||||
});
|
||||
|
||||
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 {
|
||||
await resetPasswordConfirm(token.value, password.value);
|
||||
status.value = 'success';
|
||||
message.value = 'Password reset successfully! Redirecting to login...';
|
||||
setTimeout(() => {
|
||||
router.push('/');
|
||||
}, 3000);
|
||||
} catch (e) {
|
||||
status.value = 'error';
|
||||
message.value = 'Network error occurred';
|
||||
message.value = (e as Error).message || 'Failed to reset password';
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
}
|
||||
|
||||
@@ -57,6 +57,7 @@ import {
|
||||
|
||||
import KbWorkspaceView from './KbWorkspaceView.vue';
|
||||
import { listWorkspaceScheduleRuns, workspaceRunExcelUrl, type ScheduleRun } from '../api/schedule';
|
||||
import { BusinessError, requestJson } from '../api/client';
|
||||
import { Clock, Download, Search, RefreshCw } from 'lucide-vue-next';
|
||||
|
||||
const { t, locale } = useI18n();
|
||||
@@ -202,23 +203,17 @@ const handleForgotPassword = async () => {
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/user/reset-password-by-email', {
|
||||
await requestJson('/api/user/reset-password-by-email', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(forgotPasswordForm.value)
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
if (res.ok) {
|
||||
msg.success(t('login.passwordResetEmailSent'));
|
||||
showForgotPasswordModal.value = false;
|
||||
forgotPasswordForm.value = { email: '' };
|
||||
} else {
|
||||
msg.error(data.error || t('login.passwordResetRequestFailed'));
|
||||
}
|
||||
msg.success(t('login.passwordResetEmailSent'));
|
||||
showForgotPasswordModal.value = false;
|
||||
forgotPasswordForm.value = { email: '' };
|
||||
} catch (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
|
||||
const fetchHome = async () => {
|
||||
try {
|
||||
const res = await fetch('/api/user/home', { headers: getAuthHeaders() });
|
||||
if (res.status === 401) {
|
||||
msg.error(t('login.loginRequired'));
|
||||
handleLogout();
|
||||
return;
|
||||
const data = await requestJson<any>('/api/user/home', { headers: getAuthHeaders() });
|
||||
if (!data) {
|
||||
throw new Error('Missing /api/user/home payload');
|
||||
}
|
||||
const data = await res.json();
|
||||
currentUser.value = {
|
||||
id: data.user.id,
|
||||
username: data.user.username,
|
||||
@@ -357,6 +349,11 @@ return;
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
if ((e as BusinessError)?.status === 401) {
|
||||
msg.error(t('login.loginRequired'));
|
||||
handleLogout();
|
||||
return;
|
||||
}
|
||||
console.error('Failed to load user home', e);
|
||||
} finally {
|
||||
isLoading.value = false;
|
||||
@@ -365,12 +362,7 @@ return;
|
||||
|
||||
const fetchPublicAgents = async () => {
|
||||
try {
|
||||
const res = await fetch('/api/agents/public');
|
||||
if (res.ok) {
|
||||
publicAgents.value = await res.json();
|
||||
} else {
|
||||
publicAgents.value = [];
|
||||
}
|
||||
publicAgents.value = await requestJson<Agent[]>('/api/agents/public');
|
||||
} catch (e) {
|
||||
publicAgents.value = [];
|
||||
}
|
||||
@@ -378,10 +370,7 @@ const fetchPublicAgents = async () => {
|
||||
|
||||
const fetchAnnouncements = async () => {
|
||||
try {
|
||||
const res = await fetch('/api/user/announcements');
|
||||
if (res.ok) {
|
||||
announcements.value = await res.json();
|
||||
}
|
||||
announcements.value = await requestJson<Announcement[]>('/api/user/announcements');
|
||||
} catch (e) {
|
||||
console.error('Failed to load announcements', e);
|
||||
}
|
||||
@@ -448,7 +437,7 @@ const handleLogin = async (event?: Event) => {
|
||||
const loginApi = isCasdoorMode
|
||||
? (config.auth?.casdoor?.passwordLoginApi || '/api/user/casdoor/password-login')
|
||||
: '/api/user/login';
|
||||
const res = await fetch(loginApi, {
|
||||
const user = await requestJson<any>(loginApi, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
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);
|
||||
|
||||
await fetchHome();
|
||||
@@ -489,8 +453,27 @@ const handleLogin = async (event?: Event) => {
|
||||
pendingAgentId.value = null;
|
||||
await router.replace(`/chat/${DEFAULT_POST_LOGIN_AGENT_ID}`);
|
||||
} 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);
|
||||
msg.error(t('login.requestFailed'));
|
||||
msg.error(errorText || t('login.requestFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -519,24 +502,11 @@ const tryCasdoorCallbackLogin = async () => {
|
||||
}
|
||||
try {
|
||||
const api = config.auth.casdoor.loginApi || '/api/user/casdoor/login';
|
||||
const res = await fetch(api, {
|
||||
const data = await requestJson<any>(api, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
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.
|
||||
persistLoginUser(data);
|
||||
sessionStorage.removeItem('hxops_casdoor_state');
|
||||
@@ -544,8 +514,15 @@ const tryCasdoorCallbackLogin = async () => {
|
||||
await fetchHome();
|
||||
return true;
|
||||
} 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);
|
||||
msg.error('Casdoor login failed');
|
||||
clearWecomCallbackQuery();
|
||||
return true;
|
||||
}
|
||||
@@ -572,10 +549,9 @@ const handleWecomLogin = async () => {
|
||||
if (hint) {
|
||||
qs.set('provider_hint', hint);
|
||||
}
|
||||
const res = await fetch(`${api}?${qs.toString()}`);
|
||||
const data = await res.json();
|
||||
if (!res.ok || !data.url) {
|
||||
msg.error(data.error || t('login.wecomStartFailed'));
|
||||
const data = await requestJson<any>(`${api}?${qs.toString()}`);
|
||||
if (!data?.url) {
|
||||
msg.error(t('login.wecomStartFailed'));
|
||||
return;
|
||||
}
|
||||
if (data.state) {
|
||||
@@ -587,10 +563,9 @@ const handleWecomLogin = async () => {
|
||||
|
||||
const redirectUri = `${window.location.origin}${wecomCfg.callbackPath || '/workspace'}`;
|
||||
const api = wecomCfg.authorizeApi || '/api/user/wecom/authorize-url';
|
||||
const res = await fetch(`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`);
|
||||
const data = await res.json();
|
||||
if (!res.ok || !data.url) {
|
||||
msg.error(data.error || t('login.wecomStartFailed'));
|
||||
const data = await requestJson<any>(`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`);
|
||||
if (!data?.url) {
|
||||
msg.error(t('login.wecomStartFailed'));
|
||||
return;
|
||||
}
|
||||
if (data.state) {
|
||||
@@ -599,7 +574,7 @@ const handleWecomLogin = async () => {
|
||||
window.location.href = data.url;
|
||||
} catch (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 = '';
|
||||
try {
|
||||
const api = config.auth.wecom.completeBindApi || '/api/user/wecom/complete-bind';
|
||||
const res = await fetch(api, {
|
||||
const data = await requestJson<any>(api, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
@@ -654,15 +629,6 @@ const submitWecomCompleteBind = async () => {
|
||||
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;
|
||||
persistLoginUser(data);
|
||||
@@ -671,10 +637,19 @@ const submitWecomCompleteBind = async () => {
|
||||
window.history.replaceState({}, '', '/workspace');
|
||||
await fetchHome();
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
const err = e as BusinessError;
|
||||
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 {
|
||||
if (wecomBindPrompt.value) {
|
||||
wecomBindPrompt.value.submitting = false;
|
||||
@@ -706,33 +681,11 @@ const tryWecomCallbackLogin = async () => {
|
||||
isWecomLoggingIn.value = true;
|
||||
try {
|
||||
const api = config.auth.wecom.loginApi || '/api/user/wecom/login';
|
||||
const res = await fetch(api, {
|
||||
const data = await requestJson<any>(api, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
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;
|
||||
persistLoginUser(data);
|
||||
@@ -741,10 +694,25 @@ const tryWecomCallbackLogin = async () => {
|
||||
await fetchHome();
|
||||
return true;
|
||||
} 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);
|
||||
msg.error(t('login.wecomLoginFailed'));
|
||||
msg.error(friendly);
|
||||
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();
|
||||
return true;
|
||||
} finally {
|
||||
@@ -759,23 +727,17 @@ const handleRegister = async () => {
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/user/register', {
|
||||
await requestJson('/api/user/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(registerForm.value)
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
msg.success(t('register.success'));
|
||||
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'));
|
||||
}
|
||||
msg.success(t('register.success'));
|
||||
showRegisterModal.value = false;
|
||||
registerForm.value = { username: '', password: '', email: '', real_name: '', employee_id: '', phone_number: '' };
|
||||
} catch (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 };
|
||||
};
|
||||
|
||||
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 () => {
|
||||
isProfileLoading.value = true;
|
||||
try {
|
||||
const res = await fetch('/api/user/profile', { headers: getAuthHeaders() });
|
||||
if (!res.ok) {
|
||||
const data = await requestJson<any>('/api/user/profile', { headers: getAuthHeaders() });
|
||||
if (!data) {
|
||||
msg.error(t('workspace.profile.msg.loadFailed'));
|
||||
return;
|
||||
}
|
||||
const data = await res.json();
|
||||
profileUser.value = { ...profileUser.value, ...data };
|
||||
if (data.language) locale.value = data.language;
|
||||
if (data.theme_preference) {
|
||||
@@ -952,24 +900,17 @@ const saveProfile = async () => {
|
||||
|
||||
try {
|
||||
isProfileSaving.value = true;
|
||||
const res = await fetch('/api/user/profile', {
|
||||
await requestJson('/api/user/profile', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
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'));
|
||||
captureOriginalProfile();
|
||||
isProfileEditing.value = false;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
msg.error(t('workspace.profile.msg.saveFailed'));
|
||||
msg.error((e as Error)?.message || t('workspace.profile.msg.saveFailed'));
|
||||
} finally {
|
||||
isProfileSaving.value = false;
|
||||
}
|
||||
@@ -982,7 +923,7 @@ const handleChangePassword = async () => {
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/user/change-password', {
|
||||
await requestJson('/api/user/change-password', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify({
|
||||
@@ -990,19 +931,12 @@ const handleChangePassword = async () => {
|
||||
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');
|
||||
passwordForm.value = { current: '', new: '', confirm: '' };
|
||||
showPasswordModal.value = false;
|
||||
} catch (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 () => {
|
||||
isLoadingHistories.value = true;
|
||||
try {
|
||||
const res = await fetch('/api/agents', { headers: getAuthHeaders() });
|
||||
if (!res.ok) { isLoadingHistories.value = false; return; }
|
||||
const agentList = await res.json();
|
||||
const agentList = await requestJson<any[]>('/api/agents', { headers: getAuthHeaders() });
|
||||
const allHistories: ChatHistoryItem[] = [];
|
||||
await Promise.all(
|
||||
(Array.isArray(agentList) ? agentList : []).map(async (agent: any) => {
|
||||
try {
|
||||
const hRes = await fetch(`/api/chat/sessions?agent_id=${agent.id}`, { headers: getAuthHeaders() });
|
||||
if (hRes.ok) {
|
||||
const sessions = await hRes.json();
|
||||
for (const s of sessions) {
|
||||
allHistories.push({ ...s, agent_id: agent.id, agent_name: agent.name });
|
||||
}
|
||||
const sessions = await requestJson<any[]>(`/api/chat/sessions?agent_id=${agent.id}`, { headers: getAuthHeaders() });
|
||||
for (const s of (Array.isArray(sessions) ? sessions : [])) {
|
||||
allHistories.push({ ...s, agent_id: agent.id, agent_name: agent.name });
|
||||
}
|
||||
} catch {}
|
||||
})
|
||||
@@ -1214,7 +1143,7 @@ const handleWecomDeeplinkContext = async () => {
|
||||
if (traceId && isLoggedIn.value) {
|
||||
try {
|
||||
const api = config.auth?.wecom?.deeplinkTraceApi || '/api/user/wecom/deeplink-opened';
|
||||
await fetch(api, {
|
||||
await requestJson(api, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify({ trace_id: traceId }),
|
||||
@@ -1242,14 +1171,18 @@ const handleWecomDeeplinkContext = async () => {
|
||||
|
||||
// Favorites
|
||||
const toggleFavorite = async (agentId: number) => {
|
||||
if (favoriteAgentIds.value.includes(agentId)) {
|
||||
// Remove
|
||||
await fetch(`/api/user/favorites/${agentId}`, { method: 'DELETE', headers: getAuthHeaders() });
|
||||
favoriteAgentIds.value = favoriteAgentIds.value.filter(id => id !== agentId);
|
||||
} else {
|
||||
// Add
|
||||
await fetch(`/api/user/favorites/${agentId}`, { method: 'POST', headers: getAuthHeaders() });
|
||||
favoriteAgentIds.value.push(agentId);
|
||||
try {
|
||||
if (favoriteAgentIds.value.includes(agentId)) {
|
||||
// Remove
|
||||
await requestJson(`/api/user/favorites/${agentId}`, { method: 'DELETE', headers: getAuthHeaders() });
|
||||
favoriteAgentIds.value = favoriteAgentIds.value.filter(id => id !== agentId);
|
||||
} else {
|
||||
// Add
|
||||
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 res = await fetch(url, {
|
||||
method: method,
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify(newQuestion.value),
|
||||
});
|
||||
|
||||
if (res.ok) {
|
||||
try {
|
||||
await requestJson(url, {
|
||||
method: method,
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify(newQuestion.value),
|
||||
});
|
||||
await fetchHome();
|
||||
isAddingQuestion.value = false;
|
||||
editingQuestionId.value = null;
|
||||
} else {
|
||||
msg.error(t('workspace.quickQuestions.msg.saveFailed'));
|
||||
} catch (e) {
|
||||
msg.error((e as Error)?.message || t('workspace.quickQuestions.msg.saveFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1316,10 +1248,14 @@ const removeQuickQuestion = async (id: number) => {
|
||||
|
||||
const confirmRemoveQuickQuestion = async () => {
|
||||
if (pendingDeleteQuickQuestionId.value === null) return;
|
||||
await fetch(`/api/user/quick-questions/${pendingDeleteQuickQuestionId.value}`, { method: 'DELETE', headers: getAuthHeaders() });
|
||||
await fetchHome();
|
||||
pendingDeleteQuickQuestionId.value = null;
|
||||
showDeleteQuickQuestionDialog.value = false;
|
||||
try {
|
||||
await requestJson(`/api/user/quick-questions/${pendingDeleteQuickQuestionId.value}`, { method: 'DELETE', headers: getAuthHeaders() });
|
||||
await fetchHome();
|
||||
pendingDeleteQuickQuestionId.value = null;
|
||||
showDeleteQuickQuestionDialog.value = false;
|
||||
} catch (e) {
|
||||
msg.error((e as Error)?.message || t('workspace.quickQuestions.msg.saveFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
const cancelRemoveQuickQuestion = () => {
|
||||
@@ -1330,13 +1266,17 @@ const cancelRemoveQuickQuestion = () => {
|
||||
// Drag & Drop
|
||||
const toggleSectionCollapse = async (section: LayoutSection) => {
|
||||
section.collapsed = !section.collapsed;
|
||||
|
||||
|
||||
// Save layout state
|
||||
await fetch('/api/user/homepage-layout', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify({ layout: { sections: layoutSections.value } })
|
||||
});
|
||||
try {
|
||||
await requestJson('/api/user/homepage-layout', {
|
||||
method: 'PUT',
|
||||
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) => {
|
||||
@@ -1354,13 +1294,17 @@ const onDrop = async (index: number) => {
|
||||
layoutSections.value.splice(draggedSectionIndex.value, 1);
|
||||
layoutSections.value.splice(index, 0, draggedItem);
|
||||
draggedSectionIndex.value = null;
|
||||
|
||||
|
||||
// Save layout
|
||||
await fetch('/api/user/homepage-layout', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify({ layout: { sections: layoutSections.value } })
|
||||
});
|
||||
try {
|
||||
await requestJson('/api/user/homepage-layout', {
|
||||
method: 'PUT',
|
||||
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) => {
|
||||
|
||||
Reference in new issue
Block a user