refactor(backend): 重构后端代码 wave 3
This commit is contained in:
1 parent
affe139bf9
commit
8415653365
97 files changed
+4673
-6164
No files matched your search
+3
-1
@@ -13,6 +13,8 @@ backend/local_test.db
|
||||
deploy
|
||||
docs/*
|
||||
!docs/
|
||||
!docs/(表+字段).md
|
||||
!docs/integrations/
|
||||
!docs/integrations/erp/
|
||||
!docs/integrations/erp/text2sql_schema.md
|
||||
tmp_restore
|
||||
tests
|
||||
Vendored
+1
-1
@@ -288,7 +288,7 @@ pipeline {
|
||||
// 目录级变更识别:用于前后端增量构建 / Directory-level change detection for incremental builds
|
||||
def frontendChanged = changedFiles.any { it.startsWith('frontend/') }
|
||||
def backendChanged = changedFiles.any {
|
||||
it.startsWith('backend/') || it == 'docs/(表+字段).md'
|
||||
it.startsWith('backend/') || it == 'docs/integrations/erp/text2sql_schema.md'
|
||||
}
|
||||
def deployConfigChanged = changedFiles.any {
|
||||
it == 'docker-compose.yml' ||
|
||||
|
||||
+3
-3
@@ -62,10 +62,10 @@ RUN --mount=type=cache,target=/root/.cache/pip \
|
||||
pyclipper Shapely six onnxruntime && \
|
||||
python -c "import cv2; from rapidocr_onnxruntime import RapidOCR; import networkx, openpyxl"
|
||||
|
||||
# Copy backend code and the Text2SQL schema required at runtime
|
||||
# Copy backend code and the ERP schema required by Text2SQL at runtime.
|
||||
COPY backend/ .
|
||||
RUN mkdir -p /app/docs
|
||||
COPY docs/(表+字段).md /app/docs/(表+字段).md
|
||||
RUN mkdir -p /app/docs/integrations/erp
|
||||
COPY docs/integrations/erp/text2sql_schema.md /app/docs/integrations/erp/text2sql_schema.md
|
||||
|
||||
|
||||
# Expose port 5000
|
||||
|
||||
@@ -21,7 +21,7 @@ def register_blueprints(app: Flask) -> None:
|
||||
from app.api.chat import chat_bp
|
||||
from app.api.admin import admin_bp
|
||||
from app.api.agents import agents_bp
|
||||
from app.api.user import user_bp
|
||||
from app.api.user import auth_bp, user_bp
|
||||
from app.api.integration import integration_bp
|
||||
from app.api.internal_jobs import internal_jobs_bp
|
||||
from app.api.maintenance import maintenance_bp
|
||||
@@ -48,6 +48,7 @@ def register_blueprints(app: Flask) -> None:
|
||||
app.register_blueprint(admin_bp, url_prefix='/api/admin')
|
||||
app.register_blueprint(agents_bp, url_prefix='/api/agents')
|
||||
app.register_blueprint(user_bp, url_prefix='/api/user')
|
||||
app.register_blueprint(auth_bp, url_prefix='/api/user')
|
||||
app.register_blueprint(training_user_bp, url_prefix='/api/user')
|
||||
app.register_blueprint(knowledge_base_bp, url_prefix='/api/kb')
|
||||
app.register_blueprint(integration_bp, url_prefix='/api/integration')
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,20 @@
|
||||
"""
|
||||
api/chat/__init__.py
|
||||
|
||||
用途:聊天域 Blueprint 的统一入口。
|
||||
依赖:chat 各职责路由模块、app.api.chat_turns。
|
||||
逻辑:创建唯一的 chat_bp,导入子模块完成路由注册,并挂载 Chat Turn 流式接口。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import Blueprint
|
||||
|
||||
chat_bp = Blueprint('chat', __name__)
|
||||
|
||||
# 子模块导入时在同一 Blueprint 上注册原有 URL。
|
||||
from . import assets, completions, directory, feedback, previews, sessions, uploads # noqa: E402, F401
|
||||
from app.api.chat_turns import register_chat_turn_routes # noqa: E402
|
||||
|
||||
register_chat_turn_routes(chat_bp)
|
||||
|
||||
__all__ = ['chat_bp']
|
||||
@@ -0,0 +1,129 @@
|
||||
"""
|
||||
api/chat/assets.py
|
||||
|
||||
用途:提供查询结果预览和固定资产文件、图片解析接口。
|
||||
依赖:chat.shared、Text2SQLService、FixedAssetHistoryService、FixedAssetImageService。
|
||||
逻辑:校验当前用户与 Agent 上下文后调用领域服务,返回分页数据或安全的预览元数据。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from . import chat_bp
|
||||
|
||||
|
||||
@chat_bp.route('/query-preview/<int:chat_log_id>', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_chat_query_preview(chat_log_id: int):
|
||||
page = request.args.get('page', type=int) or 1
|
||||
page_size = request.args.get('page_size', type=int) or 100
|
||||
page = max(1, page)
|
||||
page_size = max(1, min(200, page_size))
|
||||
|
||||
log = db.session.query(ChatLog).filter(
|
||||
ChatLog.id == chat_log_id,
|
||||
ChatLog.user_id == getattr(g.current_user, 'id', 0),
|
||||
ChatLog.agent_id == getattr(g.current_agent, 'id', 0),
|
||||
).first()
|
||||
if not log:
|
||||
raise NotFoundError('query preview not found')
|
||||
|
||||
payload = log.payload if isinstance(log.payload, dict) else {}
|
||||
if payload.get('kind') != 'text2sql_result_preview':
|
||||
raise ValidationError('current message does not support query preview')
|
||||
|
||||
sql = str(payload.get('sql') or '').strip()
|
||||
query = str(payload.get('query') or log.query or '').strip()
|
||||
if not sql:
|
||||
raise ValidationError('query preview sql is missing')
|
||||
|
||||
from app.services.text2sql import Text2SQLService
|
||||
total_count = payload.get('total_count')
|
||||
try:
|
||||
total_count = int(total_count) if total_count is not None else None
|
||||
except (TypeError, ValueError):
|
||||
total_count = None
|
||||
|
||||
columns, rows, resolved_total = Text2SQLService.get_preview_page(
|
||||
sql=sql,
|
||||
query=query,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
agent=g.current_agent,
|
||||
total_count=total_count,
|
||||
user_context=Text2SQLService._normalize_user_context(g.current_user),
|
||||
)
|
||||
if columns == ["Error"]:
|
||||
raise AppError(code='CHAT.QUERY_PREVIEW_FAILED', message=str(rows[0][0] if rows and rows[0] else 'query preview failed'), http_status=500)
|
||||
|
||||
total = resolved_total if resolved_total is not None else len(rows)
|
||||
return jsonify({
|
||||
'columns': columns,
|
||||
'rows': [list(row) for row in rows],
|
||||
'page': page,
|
||||
'page_size': page_size,
|
||||
'total': total,
|
||||
'has_more': page * page_size < total,
|
||||
'query': query,
|
||||
})
|
||||
|
||||
@chat_bp.route('/asset-history/search', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def search_asset_history_files():
|
||||
"""
|
||||
检索固定资产履历文件。
|
||||
|
||||
用途:聊天结果表格点击“资产编号”时,返回共享盘中的候选履历文件列表。
|
||||
约束:至少提供资产编号或资产名称之一;不直接返回文件内容,只返回预览所需路径元数据。
|
||||
"""
|
||||
asset_id = (request.args.get('asset_id') or '').strip()
|
||||
asset_name = (request.args.get('asset_name') or '').strip()
|
||||
limit = request.args.get('limit', type=int) or 20
|
||||
limit = max(1, min(limit, 50))
|
||||
|
||||
if not asset_id and not asset_name:
|
||||
raise ValidationError('asset_id or asset_name is required')
|
||||
|
||||
from app.services.fixed_asset_history import FixedAssetHistoryService
|
||||
|
||||
if not FixedAssetHistoryService.is_enabled():
|
||||
raise ServiceUnavailableError('asset history share is not configured')
|
||||
|
||||
items = FixedAssetHistoryService.search_history_files(
|
||||
asset_id=asset_id,
|
||||
asset_name=asset_name,
|
||||
limit=limit,
|
||||
)
|
||||
return jsonify({
|
||||
'asset_id': asset_id,
|
||||
'asset_name': asset_name,
|
||||
'total': len(items),
|
||||
'items': items,
|
||||
})
|
||||
|
||||
@chat_bp.route('/asset-image/resolve', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def resolve_asset_image_preview():
|
||||
"""
|
||||
解析固定资产图片预览链接。
|
||||
|
||||
用途:聊天结果表格点击“图片 -> 查看”时,后端自动登录外部文档库并返回最佳图片的可预览元数据。
|
||||
约束:至少提供资产编号或资产名称之一;只返回当前最佳命中的单张图片,不向前端暴露文档库登录态。
|
||||
"""
|
||||
asset_id = (request.args.get('asset_id') or '').strip()
|
||||
asset_name = (request.args.get('asset_name') or '').strip()
|
||||
if not asset_id and not asset_name:
|
||||
raise ValidationError('asset_id or asset_name is required')
|
||||
|
||||
from app.services.fixed_asset_image import FixedAssetImageService
|
||||
|
||||
result = FixedAssetImageService.resolve_images(
|
||||
asset_id=asset_id,
|
||||
asset_name=asset_name,
|
||||
)
|
||||
return jsonify({
|
||||
'asset_id': asset_id,
|
||||
'asset_name': asset_name,
|
||||
'item': result.get('item'),
|
||||
'items': result.get('items', []),
|
||||
'total': result.get('total', 0),
|
||||
})
|
||||
@@ -0,0 +1,331 @@
|
||||
"""
|
||||
api/chat/completions.py
|
||||
|
||||
用途:处理聊天 SSE completions 请求与上游事件转发。
|
||||
依赖:chat.shared、chat.core、services.chat.router、DifyService。
|
||||
逻辑:解析 HTTP 请求并建立本地会话,按 Chat Router 分流后保持原 SSE 契约输出。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from . import chat_bp
|
||||
from .core import (
|
||||
_build_chat_adapter_hints,
|
||||
_ensure_chat_session,
|
||||
_get_chat_session,
|
||||
_should_reset_provider_conversation_for_asset_query,
|
||||
_update_chat_session,
|
||||
)
|
||||
|
||||
|
||||
@chat_bp.route('/completions', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def chat_completions():
|
||||
"""
|
||||
SSE 流式聊天接口
|
||||
用途:接收前端问题,调用 DifyService.stream_chat,并以 text/event-stream 形式返回
|
||||
核心逻辑:
|
||||
1. 从请求体中读取 query / agent_id / conversation_id
|
||||
2. 通过装饰器已完成权限校验,并在 g 中注入 current_user / current_agent
|
||||
3. 使用 Flask 的 stream_with_context 包裹生成器,实现流式推送
|
||||
传入参数:
|
||||
无(从 request.json 读取)
|
||||
返回值:
|
||||
Flask Response 对象,mimetype=text/event-stream
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
query = data.get('query')
|
||||
display_query = str(data.get('display_query') or query or '').strip()
|
||||
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
||||
conversation_id = data.get('conversation_id')
|
||||
shipping_task_id = str(data.get('task_id') or '').strip()
|
||||
shipping_batch_no = str(data.get('batch_no') or '').strip()
|
||||
kb_type = data.get('kb_type', '企业知识库')
|
||||
files = data.get('files')
|
||||
request_id = uuid.uuid4().hex[:12]
|
||||
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)
|
||||
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))
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
||||
|
||||
from app.services.agent_registry.resolver import resolve_runtime_provider
|
||||
|
||||
if resolve_runtime_provider(agent) == 'iframe':
|
||||
raise ValidationError('Embedded iframe agents do not support chat completions')
|
||||
|
||||
user_id = getattr(user, 'id', None)
|
||||
agent_id = getattr(agent, 'id', None)
|
||||
|
||||
from types import SimpleNamespace
|
||||
from app.services.agent_directory import serialize_directory_members
|
||||
|
||||
is_aggregate = bool(getattr(agent, 'is_aggregate', False))
|
||||
directory_members = serialize_directory_members(agent_id, active_only=True) if is_aggregate else []
|
||||
agent_proxy = SimpleNamespace(
|
||||
id=agent_id,
|
||||
name=getattr(agent, 'name', None),
|
||||
type=getattr(agent, 'type', None),
|
||||
dify_api_key=getattr(agent, 'dify_api_key', None),
|
||||
api_base_url=getattr(agent, 'api_base_url', None),
|
||||
extra_config=getattr(agent, 'extra_config', None) or {},
|
||||
agent_code=getattr(agent, 'agent_code', None),
|
||||
runtime_provider=getattr(agent, 'runtime_provider', None),
|
||||
conversation_mode=getattr(agent, 'conversation_mode', None),
|
||||
dify_app_type=getattr(agent, 'dify_app_type', None),
|
||||
capabilities=getattr(agent, 'capabilities', None),
|
||||
bound_schedule_task_id=getattr(agent, 'bound_schedule_task_id', None),
|
||||
handler_config=getattr(agent, 'handler_config', None),
|
||||
is_aggregate=is_aggregate,
|
||||
directory_members=directory_members,
|
||||
)
|
||||
user_proxy = SimpleNamespace(
|
||||
id=user_id,
|
||||
username=getattr(user, 'username', None),
|
||||
employee_id=getattr(user, 'employee_id', None),
|
||||
real_name=getattr(user, 'real_name', None),
|
||||
role=getattr(user, 'role', None),
|
||||
)
|
||||
|
||||
from app.services.dify import DifyService
|
||||
|
||||
external_conversation_id = None
|
||||
if conversation_id:
|
||||
existing_session = _get_chat_session(user_id, agent_id, conversation_id)
|
||||
if existing_session:
|
||||
session = _ensure_chat_session(
|
||||
user_id,
|
||||
agent_id,
|
||||
existing_session.session_id,
|
||||
title=display_query,
|
||||
status='running',
|
||||
)
|
||||
external_conversation_id = session.external_conversation_id
|
||||
if external_conversation_id and _should_reset_provider_conversation_for_asset_query(query, agent_proxy):
|
||||
current_app.logger.info(
|
||||
'[chat-api] reset provider conversation for asset query request_id=%s session_id=%s old_provider_conversation_id=%s query=%s',
|
||||
request_id,
|
||||
session.session_id,
|
||||
external_conversation_id,
|
||||
query,
|
||||
)
|
||||
session.external_conversation_id = None
|
||||
session.updated_at = datetime.utcnow()
|
||||
session.last_active_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
external_conversation_id = None
|
||||
else:
|
||||
session = _ensure_chat_session(
|
||||
user_id,
|
||||
agent_id,
|
||||
conversation_id,
|
||||
title=display_query,
|
||||
status='running',
|
||||
external_conversation_id=conversation_id,
|
||||
)
|
||||
external_conversation_id = session.external_conversation_id
|
||||
else:
|
||||
session = _ensure_chat_session(user_id, agent_id, None, title=display_query, status='running')
|
||||
|
||||
normalized_files: list[dict] | None = None
|
||||
if files is not None:
|
||||
if not isinstance(files, list):
|
||||
raise ValidationError('files must be a list')
|
||||
normalized_files = []
|
||||
for item in files:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
transfer_method = str(item.get('transfer_method') or '').strip()
|
||||
ftype = str(item.get('type') or '').strip()
|
||||
if transfer_method not in ('local_file', 'remote_url'):
|
||||
continue
|
||||
if ftype not in ('image', 'document', 'audio', 'video', 'custom'):
|
||||
continue
|
||||
if transfer_method == 'local_file':
|
||||
upload_file_id = str(item.get('upload_file_id') or '').strip()
|
||||
if not upload_file_id:
|
||||
continue
|
||||
normalized_files.append({'type': ftype, 'transfer_method': 'local_file', 'upload_file_id': upload_file_id})
|
||||
else:
|
||||
url = str(item.get('url') or '').strip()
|
||||
if not url:
|
||||
continue
|
||||
normalized_files.append({'type': ftype, 'transfer_method': 'remote_url', 'url': url})
|
||||
if not normalized_files:
|
||||
normalized_files = None
|
||||
|
||||
from app.services.agent_registry.handlers.base import ChatStreamContext
|
||||
|
||||
relay_stream_ctx = ChatStreamContext(
|
||||
query=query,
|
||||
display_query=display_query,
|
||||
user=user_proxy,
|
||||
agent=agent_proxy,
|
||||
session=session,
|
||||
external_conversation_id=external_conversation_id,
|
||||
request_id=request_id,
|
||||
normalized_files=normalized_files,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
kb_type=kb_type,
|
||||
)
|
||||
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
from app.services.chat.router import try_fast_route
|
||||
|
||||
leave_supported = HRLeaveSQLServerService.supports(query)
|
||||
|
||||
fast_route = try_fast_route(
|
||||
user=user_proxy,
|
||||
agent=agent_proxy,
|
||||
query=query,
|
||||
agent_id=agent_id,
|
||||
session_id=session.session_id,
|
||||
external_conversation_id=external_conversation_id,
|
||||
normalized_files=normalized_files,
|
||||
kb_type=kb_type,
|
||||
leave_supported=leave_supported,
|
||||
)
|
||||
if fast_route is not None:
|
||||
generator = fast_route.generator
|
||||
elif leave_supported:
|
||||
generator = DifyService.stream_chat(
|
||||
query,
|
||||
user_proxy.id,
|
||||
agent_proxy,
|
||||
external_conversation_id,
|
||||
request_id=request_id,
|
||||
session_id=session.session_id,
|
||||
files=normalized_files,
|
||||
inputs=build_chat_dify_inputs(
|
||||
agent_proxy,
|
||||
session_id=session.session_id,
|
||||
request_id=request_id,
|
||||
trigger_source="frontend_chat",
|
||||
user_role=user_proxy.role,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
),
|
||||
)
|
||||
else:
|
||||
from app.services.chat.executors import stream_chat_via_executor
|
||||
|
||||
generator = stream_chat_via_executor(relay_stream_ctx)
|
||||
|
||||
def relay_stream():
|
||||
from app.services.chat_perf import chat_perf_enabled
|
||||
|
||||
relay_started = time.perf_counter()
|
||||
relay_first_chunk_at: float | None = None
|
||||
created_event = {
|
||||
'event': 'session_created',
|
||||
'conversation_id': session.session_id,
|
||||
'provider_conversation_id': session.external_conversation_id,
|
||||
'session_status': session.status,
|
||||
}
|
||||
yield f"data: {json.dumps(created_event, ensure_ascii=False)}\n\n"
|
||||
|
||||
known_provider_conversation_id = session.external_conversation_id
|
||||
known_status = session.status
|
||||
emitted_handler_state_keys: set[str] = set()
|
||||
|
||||
from app.services.chat.stream_relay import (
|
||||
iter_handler_preface_sse,
|
||||
iter_handler_terminal_sse,
|
||||
)
|
||||
|
||||
for preface_line in iter_handler_preface_sse(relay_stream_ctx, emitted_keys=emitted_handler_state_keys):
|
||||
yield preface_line
|
||||
|
||||
try:
|
||||
for chunk in generator:
|
||||
if relay_first_chunk_at is None:
|
||||
relay_first_chunk_at = time.perf_counter()
|
||||
if not isinstance(chunk, str) or not chunk.startswith('data: '):
|
||||
yield chunk
|
||||
continue
|
||||
|
||||
raw_payload = chunk[6:].strip()
|
||||
try:
|
||||
event_data = json.loads(raw_payload)
|
||||
except Exception:
|
||||
yield chunk
|
||||
continue
|
||||
|
||||
provider_conversation_id = str(event_data.get('conversation_id') or known_provider_conversation_id or '').strip() or None
|
||||
event_name = event_data.get('event')
|
||||
should_touch = False
|
||||
if provider_conversation_id and provider_conversation_id != known_provider_conversation_id:
|
||||
known_provider_conversation_id = provider_conversation_id
|
||||
should_touch = True
|
||||
if event_name in ('message_end', 'workflow_finished'):
|
||||
known_status = 'done'
|
||||
should_touch = True
|
||||
elif event_name == 'error':
|
||||
known_status = 'error'
|
||||
should_touch = True
|
||||
|
||||
if should_touch:
|
||||
updated_session = _update_chat_session(
|
||||
user_id,
|
||||
agent_id,
|
||||
session.session_id,
|
||||
status=known_status,
|
||||
external_conversation_id=known_provider_conversation_id,
|
||||
touch=True,
|
||||
)
|
||||
if updated_session:
|
||||
known_status = updated_session.status
|
||||
|
||||
event_data['provider_conversation_id'] = provider_conversation_id
|
||||
event_data['conversation_id'] = session.session_id
|
||||
event_data['session_status'] = known_status
|
||||
if chat_perf_enabled() and event_name in ('message_end', 'workflow_finished'):
|
||||
relay_first_ms = int((relay_first_chunk_at - relay_started) * 1000) if relay_first_chunk_at else None
|
||||
relay_total_ms = int((time.perf_counter() - relay_started) * 1000)
|
||||
current_app.logger.info(
|
||||
'[chat-perf] relay request_id=%s session_id=%s first_chunk_ms=%s total_relay_ms=%s event=%s',
|
||||
request_id,
|
||||
session.session_id,
|
||||
relay_first_ms,
|
||||
relay_total_ms,
|
||||
event_name,
|
||||
)
|
||||
event_data['hxops_relay'] = {
|
||||
'first_chunk_ms': relay_first_ms,
|
||||
'total_relay_ms': relay_total_ms,
|
||||
}
|
||||
yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n"
|
||||
if event_name in ('message_end', 'workflow_finished'):
|
||||
for terminal_line in iter_handler_terminal_sse(
|
||||
relay_stream_ctx,
|
||||
event_data,
|
||||
emitted_keys=emitted_handler_state_keys,
|
||||
):
|
||||
yield terminal_line
|
||||
except Exception as exc:
|
||||
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id)
|
||||
payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'}
|
||||
yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
||||
|
||||
# 返回 SSE 响应,mimetype 设为 text/event-stream
|
||||
return Response(
|
||||
stream_with_context(
|
||||
relay_stream()
|
||||
),
|
||||
mimetype='text/event-stream',
|
||||
headers={
|
||||
'Cache-Control': 'no-cache',
|
||||
'Content-Type': 'text/event-stream; charset=utf-8',
|
||||
'Connection': 'keep-alive',
|
||||
# 对于 Nginx 反向代理,需要关闭缓冲以支持实时流式传输
|
||||
'X-Accel-Buffering': 'no'
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,218 @@
|
||||
"""
|
||||
api/chat/core.py
|
||||
|
||||
用途:提供聊天 API 内部共享的会话、标题和日志辅助操作。
|
||||
依赖:chat.shared、ChatSession、ChatLog、services.chat.session_service。
|
||||
逻辑:供 completions 与 sessions 路由复用,集中维护本地会话和上游 conversation_id 的映射。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
|
||||
|
||||
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None:
|
||||
"""
|
||||
构建聊天入口分发给领域 adapter 的提示字典。
|
||||
|
||||
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
|
||||
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
|
||||
"""
|
||||
task_id = str(shipping_task_id or '').strip()
|
||||
batch_no = str(shipping_batch_no or '').strip()
|
||||
if not task_id and not batch_no:
|
||||
return None
|
||||
return {
|
||||
'shipping_notice': {
|
||||
'task_id': task_id or None,
|
||||
'batch_no': batch_no or None,
|
||||
}
|
||||
}
|
||||
|
||||
def _should_reset_provider_conversation_for_asset_query(query: str, agent_proxy) -> bool:
|
||||
"""
|
||||
判断固资管理里的当前问题是否应当切断上游 Dify 会话上下文。
|
||||
|
||||
核心逻辑:
|
||||
- 仅对“固资管理”Agent 生效;
|
||||
- 仅当用户本轮问题可脱离上一轮上下文独立完成时触发;
|
||||
- 这样可以保留本地同一历史会话,又避免把上一轮超大结果继续带给上游模型,导致 context length 爆掉。
|
||||
"""
|
||||
from app.services.text2sql import Text2SQLService
|
||||
|
||||
return Text2SQLService._should_reset_provider_conversation(query, agent_proxy)
|
||||
|
||||
def _session_title_from_text(text: str) -> str:
|
||||
value = str(text or '').strip()
|
||||
if not value:
|
||||
return ''
|
||||
return value[:30] + ('...' if len(value) > 30 else '')
|
||||
|
||||
def _looks_like_review_auto_title(title: str) -> bool:
|
||||
"""
|
||||
判断会话标题是否为审查结果 headline(误用作历史标题)。
|
||||
|
||||
Args:
|
||||
title: ChatSession.title。
|
||||
|
||||
Returns:
|
||||
True 表示标题像「模板比对完成…」这类自动摘要,而非用户提问。
|
||||
"""
|
||||
value = str(title or '').strip()
|
||||
return value.startswith(('模板比对完成', '单份审核完成', '采购合同审查结果'))
|
||||
|
||||
def _fallback_title_from_contract_review_log(log: ChatLog | None) -> str:
|
||||
"""
|
||||
从合同审查日志推导可读会话标题(优先 query,其次合同文件名)。
|
||||
|
||||
Args:
|
||||
log: procurement-contract-review 类型的 ChatLog。
|
||||
|
||||
Returns:
|
||||
截断后的标题;无法推导时返回空串。
|
||||
"""
|
||||
if not log:
|
||||
return ''
|
||||
query = str(log.query or '').strip()
|
||||
if query:
|
||||
return _session_title_from_text(query)
|
||||
payload = log.payload if isinstance(log.payload, dict) else {}
|
||||
file_name = str(payload.get('contract_file_name') or '').strip()
|
||||
if file_name:
|
||||
return _session_title_from_text(f'请对《{file_name}》进行审查')
|
||||
return ''
|
||||
|
||||
def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str:
|
||||
"""
|
||||
将内部 Agent 编排提示转换成业务用户可见话术。
|
||||
|
||||
Args:
|
||||
text: chat_logs.query 中保存的用户侧文本。
|
||||
agent_code: 当前 Agent 应用类型;仅 shipping_notice 做工具名净化。
|
||||
Returns:
|
||||
可直接展示在聊天历史里的用户问题。
|
||||
"""
|
||||
value = str(text or '').strip()
|
||||
if not value or str(agent_code or '').strip() != SHIPPING_NOTICE_AGENT_CODE:
|
||||
return value
|
||||
import re
|
||||
|
||||
task_match = re.search(r'(SN-\d{8}-[A-Z0-9]+)', value, re.I)
|
||||
task_no = task_match.group(1).upper() if task_match else ''
|
||||
if 'create_task' in value or 'get_task_status' in value or 'parse_notice' in value:
|
||||
return f'继续处理当前发货任务 {task_no}'.strip()
|
||||
return value
|
||||
|
||||
def _serialize_session(session: ChatSession) -> dict:
|
||||
last_active = session.last_active_at or session.created_at
|
||||
return {
|
||||
'id': session.id,
|
||||
'conversation_id': session.session_id,
|
||||
'title': session.title or '',
|
||||
'created_at': last_active.isoformat() if last_active else '',
|
||||
'status': session.status,
|
||||
}
|
||||
|
||||
def _get_chat_session(user_id: int, agent_id: int, session_id: str | None):
|
||||
session_key = str(session_id or '').strip()
|
||||
if not session_key:
|
||||
return None
|
||||
return db.session.query(ChatSession).filter_by(
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
session_id=session_key,
|
||||
).first()
|
||||
|
||||
def _chat_logs_for_session(user_id: int, agent_id: int, session: ChatSession):
|
||||
match_ids = {session.session_id}
|
||||
external_id = str(session.external_conversation_id or '').strip()
|
||||
if external_id:
|
||||
match_ids.add(external_id)
|
||||
return db.session.query(ChatLog).filter(
|
||||
ChatLog.user_id == user_id,
|
||||
ChatLog.agent_id == agent_id,
|
||||
or_(
|
||||
ChatLog.session_id.in_(match_ids),
|
||||
ChatLog.conversation_id.in_(match_ids),
|
||||
),
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
def _ensure_chat_session(
|
||||
user_id: int,
|
||||
agent_id: int,
|
||||
session_id: str | None,
|
||||
title: str = '',
|
||||
status: str = 'running',
|
||||
external_conversation_id: str | None = None,
|
||||
):
|
||||
session_key = str(session_id or '').strip()
|
||||
external_id = str(external_conversation_id or '').strip() or None
|
||||
session = _get_chat_session(user_id, agent_id, session_key)
|
||||
changed = False
|
||||
if not session:
|
||||
session = ChatSession(
|
||||
session_id=session_key or uuid.uuid4().hex,
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
title=_session_title_from_text(title),
|
||||
status=status,
|
||||
external_conversation_id=external_id,
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
last_active_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(session)
|
||||
db.session.commit()
|
||||
return session
|
||||
|
||||
if not session.title and title:
|
||||
session.title = _session_title_from_text(title)
|
||||
changed = True
|
||||
if status and session.status != status:
|
||||
session.status = status
|
||||
changed = True
|
||||
if external_id and session.external_conversation_id != external_id:
|
||||
session.external_conversation_id = external_id
|
||||
changed = True
|
||||
session.last_active_at = datetime.utcnow()
|
||||
session.updated_at = datetime.utcnow()
|
||||
changed = True
|
||||
if changed:
|
||||
db.session.commit()
|
||||
return session
|
||||
|
||||
def _update_chat_session(
|
||||
user_id: int,
|
||||
agent_id: int,
|
||||
session_id: str,
|
||||
*,
|
||||
status: str | None = None,
|
||||
external_conversation_id: str | None = None,
|
||||
title: str | None = None,
|
||||
touch: bool = False,
|
||||
):
|
||||
session = _get_chat_session(user_id, agent_id, session_id)
|
||||
if not session:
|
||||
return None
|
||||
|
||||
changed = False
|
||||
if title and not session.title:
|
||||
session.title = _session_title_from_text(title)
|
||||
changed = True
|
||||
|
||||
external_id = str(external_conversation_id or '').strip() or None
|
||||
if external_id and session.external_conversation_id != external_id:
|
||||
session.external_conversation_id = external_id
|
||||
changed = True
|
||||
|
||||
if status and session.status != status:
|
||||
session.status = status
|
||||
changed = True
|
||||
|
||||
if touch or changed:
|
||||
session.last_active_at = datetime.utcnow()
|
||||
session.updated_at = datetime.utcnow()
|
||||
changed = True
|
||||
|
||||
if changed:
|
||||
db.session.commit()
|
||||
return session
|
||||
@@ -0,0 +1,55 @@
|
||||
"""
|
||||
api/chat/directory.py
|
||||
|
||||
用途:提供聊天表单所需的 OA 员工、部门和分部名称查询接口。
|
||||
依赖:chat.shared、OASQLServerService、chat_bp。
|
||||
逻辑:解析分页或 ID 参数后调用 OA 集成服务,并保持原 `/api/chat/oa/*` 响应格式。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from . import chat_bp
|
||||
|
||||
|
||||
@chat_bp.route('/oa/employees', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_oa_employees():
|
||||
"""
|
||||
获取 OA 系统中的员工列表(分页/搜索)
|
||||
"""
|
||||
keyword = request.args.get('keyword', '').strip()
|
||||
try:
|
||||
page = int(request.args.get('page', 1))
|
||||
page_size = int(request.args.get('page_size', 20))
|
||||
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}')
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
||||
|
||||
@chat_bp.route('/oa/resolve-names', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def resolve_oa_names():
|
||||
dept_ids = request.args.get('department_ids', '').strip()
|
||||
sub_ids = request.args.get('subcompany_ids', '').strip()
|
||||
result = {}
|
||||
try:
|
||||
from app.services.oa_sqlserver import OASQLServerService
|
||||
if dept_ids:
|
||||
for did in dept_ids.split(','):
|
||||
did = did.strip()
|
||||
if did:
|
||||
result[f'dept_{did}'] = OASQLServerService.get_department_name(did)
|
||||
if sub_ids:
|
||||
for sid in sub_ids.split(','):
|
||||
sid = sid.strip()
|
||||
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}')
|
||||
return jsonify(result)
|
||||
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
api/chat/feedback.py
|
||||
|
||||
用途:处理用户对聊天回答的评分与文字反馈。
|
||||
依赖:chat.shared、ChatLog、Feedback、chat_bp。
|
||||
逻辑:定位当前用户和 Agent 的最近一条会话日志,创建或更新对应反馈记录。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from . import chat_bp
|
||||
|
||||
|
||||
@chat_bp.route('/feedback', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def submit_feedback():
|
||||
"""
|
||||
提交对回答的评分与评论
|
||||
用途:在对话结束后,由前端发送评分(1~5)和文字意见
|
||||
核心逻辑:
|
||||
1. 从请求体中读取 score/comment/conversation_id
|
||||
2. 根据当前 user/agent 与 conversation_id 查找最近一条 ChatLog
|
||||
3. 为该 ChatLog 创建或更新 Feedback 记录
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
score = data.get('score')
|
||||
comment = data.get('comment') or ''
|
||||
conversation_id = data.get('conversation_id')
|
||||
if not current_app.config.get('FEEDBACK_ENABLED', True):
|
||||
raise ForbiddenError('feedback is disabled')
|
||||
if score is None:
|
||||
raise ValidationError('score is required')
|
||||
try:
|
||||
score_value = int(score)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('score must be an integer')
|
||||
if score_value < 1 or score_value > 5:
|
||||
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:
|
||||
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(
|
||||
or_(ChatLog.session_id == conversation_id, ChatLog.conversation_id == conversation_id)
|
||||
)
|
||||
|
||||
# 取最新一条对话日志
|
||||
chat_log = chat_logs_query.order_by(ChatLog.created_at.desc()).first()
|
||||
if not chat_log:
|
||||
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)
|
||||
db.session.add(fb)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
@@ -0,0 +1,611 @@
|
||||
"""
|
||||
api/chat/preview_support.py
|
||||
|
||||
用途:提供聊天文件预览所需的来源校验、文件获取和格式转换操作。
|
||||
依赖:chat.shared、requests、LibreOffice、openpyxl、共享盘配置。
|
||||
逻辑:由 previews 路由调用,限制可访问路径与 URL,并将 Office/Excel 内容转换为可预览格式。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
|
||||
|
||||
def _normalize_allowed_share_path(path_value: str) -> tuple[str, str]:
|
||||
"""
|
||||
统一归一化 Windows UNC / Windows 本地盘符 / Linux 挂载目录路径。
|
||||
|
||||
Returns:
|
||||
(path_kind, normalized_path)
|
||||
- path_kind: 'windows' | 'posix' | ''
|
||||
- normalized_path: 归一化后的绝对路径文本
|
||||
"""
|
||||
raw_value = str(path_value or '').strip().strip('"')
|
||||
if not raw_value:
|
||||
return ('', '')
|
||||
if raw_value.startswith('\\\\'):
|
||||
normalized = raw_value.replace('/', '\\')
|
||||
normalized = '\\\\' + normalized[2:].rstrip('\\')
|
||||
return ('windows', normalized)
|
||||
if len(raw_value) >= 3 and raw_value[1] == ':' and raw_value[2] in ('\\', '/'):
|
||||
normalized = ntpath.normpath(raw_value.replace('/', '\\')).rstrip('\\')
|
||||
return ('windows', normalized)
|
||||
if raw_value.startswith('/'):
|
||||
normalized = posixpath.normpath(raw_value.replace('\\', '/'))
|
||||
return ('posix', normalized.rstrip('/'))
|
||||
return ('', '')
|
||||
|
||||
def _is_path_within_allowed_root(target_path: str, root_path: str) -> bool:
|
||||
target_kind, normalized_target = _normalize_allowed_share_path(target_path)
|
||||
root_kind, normalized_root = _normalize_allowed_share_path(root_path)
|
||||
if not normalized_target or not normalized_root or target_kind != root_kind:
|
||||
return False
|
||||
if target_kind == 'windows':
|
||||
target_lower = normalized_target.lower()
|
||||
root_lower = normalized_root.lower()
|
||||
return target_lower == root_lower or target_lower.startswith(root_lower.rstrip('\\') + '\\')
|
||||
return normalized_target == normalized_root or normalized_target.startswith(normalized_root.rstrip('/') + '/')
|
||||
|
||||
def _is_allowed_share_path(target_url: str) -> bool:
|
||||
target_kind, normalized_target = _normalize_allowed_share_path(target_url)
|
||||
if not normalized_target:
|
||||
return False
|
||||
history_share_root = ''
|
||||
history_local_root = ''
|
||||
if has_request_context():
|
||||
history_share_root = str(current_app.config.get('FIXED_ASSET_HISTORY_SHARE_ROOT') or '').strip()
|
||||
history_local_root = str(current_app.config.get('FIXED_ASSET_HISTORY_LOCAL_ROOT') or '').strip()
|
||||
if not history_share_root:
|
||||
history_share_root = str(Config.FIXED_ASSET_HISTORY_SHARE_ROOT or '').strip()
|
||||
if not history_local_root:
|
||||
history_local_root = str(Config.FIXED_ASSET_HISTORY_LOCAL_ROOT or '').strip()
|
||||
roots = [
|
||||
PLM_PREVIEW_SHARE_ROOT,
|
||||
history_share_root,
|
||||
history_local_root,
|
||||
]
|
||||
return any(root and _is_path_within_allowed_root(normalized_target, root) for root in roots)
|
||||
|
||||
def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
"""
|
||||
预览代理 URL 白名单校验。
|
||||
仅允许:
|
||||
1) 配置中的集成服务主机;
|
||||
2) 本机地址;
|
||||
3) 私网 IP 或常见内网域名(.local/.lan)。
|
||||
"""
|
||||
try:
|
||||
if _is_allowed_share_path(target_url):
|
||||
return True
|
||||
parsed = urlparse(target_url)
|
||||
if parsed.scheme not in ('http', 'https'):
|
||||
return False
|
||||
host = (parsed.hostname or '').strip().lower()
|
||||
if not host:
|
||||
return False
|
||||
integration_base = (IntegrationApiService.get_base_url() or '').strip()
|
||||
if integration_base:
|
||||
integration_host = (urlparse(integration_base).hostname or '').strip().lower()
|
||||
if integration_host and host == integration_host:
|
||||
return True
|
||||
|
||||
# 放行当前请求的 Host (前端能够访问本接口说明 Host 是受信任的自身域名/IP)
|
||||
if has_request_context():
|
||||
req_host = (request.host.split(':')[0] or "").strip().lower()
|
||||
if host == req_host:
|
||||
return True
|
||||
|
||||
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
|
||||
except ValueError:
|
||||
# 非 IP 主机:仅放行内网风格本地域名。
|
||||
return host.endswith(".local") or host.endswith(".lan") or host.endswith(".well-trust.com")
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 * 1024):
|
||||
"""
|
||||
从上游文件 URL 拉取二进制内容(供预览接口复用)。
|
||||
如果 file_url 是内部 integration API 下载链接且包含过期 token,则尝试重新获取最新链接。
|
||||
返回: (content_bytes, content_type, error_tuple)
|
||||
其中 error_tuple = (message, status_code);成功时为 None。
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import time
|
||||
import sqlalchemy as sa
|
||||
from urllib.parse import parse_qs
|
||||
if _is_allowed_share_path(file_url):
|
||||
_path_kind, normalized_path = _normalize_allowed_share_path(file_url)
|
||||
try:
|
||||
if not os.path.isfile(normalized_path):
|
||||
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))
|
||||
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))
|
||||
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)
|
||||
try:
|
||||
from app.services.fixed_asset_image import FixedAssetImageService
|
||||
content, content_type, asset_image_err = FixedAssetImageService.fetch_preview_bytes(
|
||||
file_url,
|
||||
max_size=max_size,
|
||||
)
|
||||
if content is not None or asset_image_err is not None:
|
||||
return (content, content_type, asset_image_err)
|
||||
except Exception as exc:
|
||||
current_app.logger.warning('[file-preview] fixed asset image fetch failed url=%s err=%s', file_url, exc)
|
||||
headers = {}
|
||||
base_url = IntegrationApiService.get_base_url()
|
||||
api_key = IntegrationApiService.get_api_key()
|
||||
|
||||
def _resolve_latest_integration_url(raw_url: str):
|
||||
dataset_id = ''
|
||||
remote_document_id = ''
|
||||
try:
|
||||
parsed = urlparse(raw_url)
|
||||
qs = parse_qs(parsed.query)
|
||||
token = (qs.get('token') or [''])[0]
|
||||
if token:
|
||||
parts = token.split('.')
|
||||
if len(parts) >= 2:
|
||||
payload_b64 = parts[1]
|
||||
payload_b64 += '=' * (-len(payload_b64) % 4)
|
||||
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
|
||||
dataset_id = str(payload_data.get('dataset_id') or '').strip()
|
||||
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')
|
||||
log = db.session.query(ChatLog).filter(stmt).params(url=f'%{raw_url}%').order_by(ChatLog.created_at.desc()).first()
|
||||
if log and log.retriever_resources:
|
||||
for r in log.retriever_resources:
|
||||
if not isinstance(r, dict):
|
||||
continue
|
||||
source_url = str(r.get('source_download_url') or '')
|
||||
if source_url == raw_url or (source_url and source_url.split('&token=')[0] == raw_url.split('&token=')[0]):
|
||||
resolved_dataset_id, resolved_remote_document_id = DifyService._extract_dify_ids(r)
|
||||
dataset_id = dataset_id or str(resolved_dataset_id or '').strip()
|
||||
remote_document_id = remote_document_id or str(resolved_remote_document_id or '').strip()
|
||||
if dataset_id and remote_document_id:
|
||||
break
|
||||
except Exception as e:
|
||||
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)
|
||||
return new_info['source_download_url']
|
||||
return raw_url
|
||||
|
||||
def _build_headers(raw_url: str):
|
||||
next_headers = {}
|
||||
|
||||
is_trusted = False
|
||||
if base_url and raw_url.startswith(base_url):
|
||||
is_trusted = True
|
||||
elif _is_allowed_preview_url(raw_url):
|
||||
is_trusted = True
|
||||
else:
|
||||
try:
|
||||
parsed = urlparse(raw_url)
|
||||
host = (parsed.hostname or "").strip().lower()
|
||||
if has_request_context():
|
||||
req_host = (request.host.split(':')[0] or "").strip().lower()
|
||||
if host == req_host:
|
||||
is_trusted = True
|
||||
if host in ("localhost", "127.0.0.1", "::1"):
|
||||
is_trusted = True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
current_app.logger.info(f"[_build_headers] raw_url={raw_url}, is_trusted={is_trusted}")
|
||||
if is_trusted:
|
||||
if api_key:
|
||||
next_headers['X-Integration-Key'] = api_key
|
||||
if has_request_context():
|
||||
auth_header = (request.headers.get('Authorization') or '').strip()
|
||||
cookie_header = (request.headers.get('Cookie') or '').strip()
|
||||
if auth_header:
|
||||
next_headers['Authorization'] = auth_header
|
||||
if cookie_header:
|
||||
next_headers['Cookie'] = cookie_header
|
||||
|
||||
return next_headers
|
||||
|
||||
def _should_refresh_from_response(resp) -> bool:
|
||||
ctype = (resp.headers.get('content-type') or '').split(';')[0].strip().lower()
|
||||
if resp.status_code == 401:
|
||||
return True
|
||||
if resp.status_code in (403, 404) and 'token=' in file_url:
|
||||
return True
|
||||
if ctype == 'application/json':
|
||||
body = (resp.content or b'')[:512].decode('utf-8', errors='ignore').lower()
|
||||
if 'unauthorized' in body or '"error"' in body:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _retry_with_refreshed_url(raw_url: str):
|
||||
refreshed_url = _resolve_latest_integration_url(raw_url)
|
||||
if not refreshed_url or refreshed_url == raw_url:
|
||||
return None, raw_url
|
||||
retry_headers = _build_headers(refreshed_url)
|
||||
try:
|
||||
return requests.get(refreshed_url, headers=retry_headers, timeout=(5, 20)), refreshed_url
|
||||
except requests.RequestException as e:
|
||||
current_app.logger.warning('[file-preview] refreshed upstream request failed: %s', e)
|
||||
return None, refreshed_url
|
||||
|
||||
if 'token=' in file_url:
|
||||
try:
|
||||
parsed = urlparse(file_url)
|
||||
qs = parse_qs(parsed.query)
|
||||
token = (qs.get('token') or [''])[0]
|
||||
if token:
|
||||
parts = token.split('.')
|
||||
if len(parts) >= 2:
|
||||
payload_b64 = parts[1]
|
||||
payload_b64 += '=' * (-len(payload_b64) % 4)
|
||||
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
|
||||
exp = payload_data.get('exp', 0)
|
||||
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)
|
||||
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))
|
||||
if 'token=' in file_url and _should_refresh_from_response(upstream):
|
||||
refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url)
|
||||
if refreshed_upstream is not None:
|
||||
upstream = refreshed_upstream
|
||||
file_url = refreshed_url
|
||||
if upstream.status_code != 200:
|
||||
if 'token=' in file_url:
|
||||
refreshed_upstream, refreshed_url = _retry_with_refreshed_url(file_url)
|
||||
if refreshed_upstream is not None:
|
||||
upstream = refreshed_upstream
|
||||
file_url = refreshed_url
|
||||
current_app.logger.warning(f"[file-preview] upstream returned status {upstream.status_code} for {file_url}")
|
||||
if upstream.status_code == 404:
|
||||
return None, None, ('source file not found', 404)
|
||||
return None, None, (f'upstream returned status {upstream.status_code}', 502)
|
||||
|
||||
content = upstream.content or b''
|
||||
if max_size is not None and len(content) > max_size:
|
||||
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)
|
||||
|
||||
def _extract_placeholder_text(content: bytes) -> str:
|
||||
sample = content[:2048]
|
||||
for enc in ('utf-16le', 'utf-8', 'utf-8-sig', 'gb18030', 'latin-1'):
|
||||
try:
|
||||
text = sample.decode(enc).replace('\x00', '').strip()
|
||||
except Exception:
|
||||
continue
|
||||
if not text:
|
||||
continue
|
||||
lines = [line.strip() for line in text.splitlines() if line.strip()]
|
||||
if not lines:
|
||||
continue
|
||||
first_line = lines[0][:160]
|
||||
if any((token in first_line for token in ('该文件', '机密文件', '未经允许', '法律风险', '禁止', '保密'))):
|
||||
return first_line
|
||||
return ''
|
||||
|
||||
def _fetch_dify_text_document(dataset_id: str, remote_document_id: str) -> str | None:
|
||||
"""
|
||||
对于 Dify 中以 text_model / txt 形式存储的文档,
|
||||
直接拼接 segments 内容,避免依赖可能失效的 file-preview 签名链接。
|
||||
"""
|
||||
if not dataset_id or not remote_document_id:
|
||||
return None
|
||||
try:
|
||||
from app.services.knowledge_cleaning.dify_sync_service import KbDifySyncService
|
||||
service = KbDifySyncService()
|
||||
document_payload = service.get_document(
|
||||
dataset_id=str(dataset_id),
|
||||
document_id=str(remote_document_id),
|
||||
)
|
||||
if not isinstance(document_payload, dict):
|
||||
return None
|
||||
|
||||
upload_info = (
|
||||
((document_payload.get('data_source_info') or {}).get('upload_file'))
|
||||
if isinstance(document_payload.get('data_source_info'), dict)
|
||||
else {}
|
||||
) or {}
|
||||
source_ext = str(upload_info.get('extension') or '').strip().lower()
|
||||
doc_form = str(document_payload.get('doc_form') or '').strip().lower()
|
||||
mime_type = str(upload_info.get('mime_type') or '').strip().lower()
|
||||
is_text_doc = (
|
||||
source_ext in ('txt', 'md', 'markdown', 'csv', 'html', 'htm', 'properties', 'vtt')
|
||||
or doc_form == 'text_model'
|
||||
or mime_type.startswith('text/')
|
||||
)
|
||||
if not is_text_doc:
|
||||
return None
|
||||
|
||||
segments_payload = service._request(
|
||||
'GET',
|
||||
f'/datasets/{dataset_id}/documents/{remote_document_id}/segments?limit=1000',
|
||||
)
|
||||
rows = []
|
||||
if isinstance(segments_payload, dict):
|
||||
rows = segments_payload.get('data') or []
|
||||
elif isinstance(segments_payload, list):
|
||||
rows = segments_payload
|
||||
if not isinstance(rows, list) or not rows:
|
||||
return None
|
||||
|
||||
ordered_rows = sorted(
|
||||
[row for row in rows if isinstance(row, dict)],
|
||||
key=lambda row: (int(row.get('position') or 0), str(row.get('id') or '')),
|
||||
)
|
||||
parts: list[str] = []
|
||||
for row in ordered_rows:
|
||||
text = str(row.get('content') or '').strip()
|
||||
if text:
|
||||
parts.append(text)
|
||||
return '\n\n'.join(parts).strip() or None
|
||||
except Exception as e:
|
||||
current_app.logger.warning(
|
||||
'[source-file-text] failed to fetch dify text document dataset=%s doc=%s err=%s',
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
e,
|
||||
)
|
||||
return None
|
||||
|
||||
def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
|
||||
"""
|
||||
使用 LibreOffice 或 WPS/MS Office 将 office 文件转为 PDF
|
||||
"""
|
||||
import shutil
|
||||
temp_dir = tempfile.mkdtemp()
|
||||
try:
|
||||
input_path = os.path.join(temp_dir, f"input.{ext}")
|
||||
with open(input_path, 'wb') as f:
|
||||
f.write(content)
|
||||
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)
|
||||
if process.returncode == 0:
|
||||
success = True
|
||||
break
|
||||
else:
|
||||
current_app.logger.warning(f"LibreOffice command {cmd} failed: {process.stderr.decode('utf-8', errors='ignore')}")
|
||||
except (FileNotFoundError, subprocess.TimeoutExpired):
|
||||
continue
|
||||
if not success and os.name == 'nt':
|
||||
app = None
|
||||
doc_obj = None
|
||||
pythoncom = None
|
||||
try:
|
||||
import win32com.client
|
||||
import pythoncom
|
||||
pythoncom.CoInitialize()
|
||||
output_path = os.path.join(temp_dir, 'input.pdf')
|
||||
if ext in ('doc', 'docx'):
|
||||
try:
|
||||
from pathlib import Path
|
||||
from edkb_system.skills.word_bridge import convert_with_word
|
||||
|
||||
convert_with_word(Path(input_path), Path(output_path), 17)
|
||||
success = True
|
||||
except Exception as word_bridge_exc:
|
||||
current_app.logger.warning("Word bridge conversion failed: %s", word_bridge_exc)
|
||||
|
||||
if not success and ext in ('doc', 'docx'):
|
||||
try:
|
||||
# 对旧版 .doc,MS Word 的 PDF 导出兼容性通常优于 WPS
|
||||
app = win32com.client.Dispatch("Word.Application")
|
||||
except Exception:
|
||||
app = win32com.client.Dispatch("KWPS.Application")
|
||||
app.Visible = False
|
||||
app.DisplayAlerts = False
|
||||
input_abs = os.path.abspath(input_path)
|
||||
output_abs = os.path.abspath(output_path)
|
||||
try:
|
||||
doc_obj = app.Documents.Open(
|
||||
FileName=input_abs,
|
||||
ConfirmConversions=False,
|
||||
ReadOnly=True,
|
||||
AddToRecentFiles=False,
|
||||
Visible=False,
|
||||
NoEncodingDialog=True,
|
||||
OpenAndRepair=True,
|
||||
)
|
||||
except TypeError:
|
||||
doc_obj = app.Documents.Open(input_abs, ReadOnly=True)
|
||||
|
||||
try:
|
||||
# 旧版 WPS/Word 对 ExportAsFixedFormat 的兼容通常优于 SaveAs(FileFormat=17)
|
||||
doc_obj.ExportAsFixedFormat(output_abs, 17) # 17 = wdExportFormatPDF
|
||||
except Exception:
|
||||
doc_obj.SaveAs(output_abs, 17) # 17 = wdFormatPDF
|
||||
success = True
|
||||
elif ext in ('ppt', 'pptx'):
|
||||
try:
|
||||
app = win32com.client.Dispatch('KWPP.Application')
|
||||
except Exception:
|
||||
app = win32com.client.Dispatch('PowerPoint.Application')
|
||||
app.Visible = False
|
||||
try:
|
||||
app.DisplayAlerts = False
|
||||
except Exception:
|
||||
pass
|
||||
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')
|
||||
except Exception:
|
||||
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.')
|
||||
except Exception as e:
|
||||
current_app.logger.warning(f"WPS/MS Office COM conversion failed: {e}")
|
||||
finally:
|
||||
if doc_obj is not None:
|
||||
try:
|
||||
doc_obj.Close(False)
|
||||
except Exception:
|
||||
pass
|
||||
if app is not None:
|
||||
try:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
if pythoncom is not None:
|
||||
try:
|
||||
pythoncom.CoUninitialize()
|
||||
except Exception:
|
||||
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')
|
||||
if os.path.exists(output_path):
|
||||
with open(output_path, 'rb') as f:
|
||||
return f.read()
|
||||
else:
|
||||
raise Exception("PDF output not found after conversion")
|
||||
finally:
|
||||
shutil.rmtree(temp_dir, ignore_errors=True)
|
||||
|
||||
def _convert_excel_to_xlsx(content: bytes, ext: str) -> bytes:
|
||||
"""
|
||||
使用 LibreOffice 将老式 `.xls` 转为 `.xlsx`,供在线预览解析。
|
||||
"""
|
||||
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')
|
||||
with open(input_path, 'wb') as f:
|
||||
f.write(content)
|
||||
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)
|
||||
except (FileNotFoundError, subprocess.TimeoutExpired) as 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}'}")
|
||||
|
||||
allow_windows_excel_preview = (
|
||||
os.getenv('ENABLE_WINDOWS_EXCEL_PREVIEW_CONVERSION', '').strip().lower() in ('1', 'true', 'yes', 'on')
|
||||
)
|
||||
if allow_windows_excel_preview:
|
||||
if _convert_excel_via_windows_office(input_path, output_path):
|
||||
with open(output_path, 'rb') as f:
|
||||
return f.read()
|
||||
errors.append("windows-office: failed to convert xls via WPS/MS Excel")
|
||||
else:
|
||||
errors.append("windows-office: disabled for preview to avoid interactive Office dialogs")
|
||||
|
||||
joined = "; ".join(errors) if errors else "no converter attempted"
|
||||
raise RuntimeError(f"failed to convert xls to xlsx: {joined}")
|
||||
|
||||
def _convert_excel_via_windows_office(input_path: str, output_path: str) -> bool:
|
||||
"""
|
||||
在 Windows 环境下使用 WPS/MS Excel 将 `.xls` 转为 `.xlsx`。
|
||||
LibreOffice 不存在时,给在线预览提供兜底转换能力。
|
||||
"""
|
||||
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.')
|
||||
return False
|
||||
app = None
|
||||
workbook = None
|
||||
pythoncom.CoInitialize()
|
||||
try:
|
||||
try:
|
||||
app = win32com.client.Dispatch('KET.Application')
|
||||
except Exception:
|
||||
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)
|
||||
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)
|
||||
return False
|
||||
finally:
|
||||
try:
|
||||
if workbook is not None:
|
||||
workbook.Close(False)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if app is not None:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
pythoncom.CoUninitialize()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _detect_excel_format(content: bytes, ext: str) -> str:
|
||||
"""
|
||||
根据文件头兜底判断 Excel 实际格式,避免只依赖 URL/文件名扩展名。
|
||||
- OLE 复合文档头: 老式 `.xls`
|
||||
- ZIP 头: `.xlsx`
|
||||
"""
|
||||
normalized_ext = (ext or '').strip().lower()
|
||||
head = content[:8] if content else b''
|
||||
if head.startswith(b'PK\x03\x04'):
|
||||
return 'xlsx'
|
||||
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)
|
||||
@@ -0,0 +1,330 @@
|
||||
"""
|
||||
api/chat/previews.py
|
||||
|
||||
用途:处理聊天来源文件、Excel、文本及原始文件预览路由。
|
||||
依赖:chat.shared、chat.preview_support、Dify 与共享盘数据源。
|
||||
逻辑:校验预览来源后获取文件内容,按格式转换并返回安全的预览响应。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from . import chat_bp
|
||||
from .preview_support import (
|
||||
_convert_office_to_pdf,
|
||||
_detect_excel_format,
|
||||
_extract_placeholder_text,
|
||||
_fetch_dify_text_document,
|
||||
_fetch_preview_source_bytes,
|
||||
_is_allowed_preview_url,
|
||||
_load_excel_workbook,
|
||||
)
|
||||
|
||||
|
||||
@chat_bp.route('/source-file', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def resolve_source_file():
|
||||
"""
|
||||
Resolve original source download URL by Dify dataset/document IDs.
|
||||
"""
|
||||
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))
|
||||
raise ValidationError('dataset_id and remote_document_id are required')
|
||||
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
|
||||
if not payload:
|
||||
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')
|
||||
|
||||
return jsonify({
|
||||
'dataset_id': dataset_id,
|
||||
'remote_document_id': remote_document_id,
|
||||
'source_filename': payload.get('source_filename'),
|
||||
'source_ext': source_ext,
|
||||
'source_download_url': source_download_url,
|
||||
'download_url_expires_at': payload.get('download_url_expires_at'),
|
||||
})
|
||||
|
||||
@chat_bp.route('/source-file-text', methods=['GET'])
|
||||
@require_agent_permission
|
||||
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:
|
||||
raise ValidationError('dataset_id and remote_document_id are required')
|
||||
|
||||
text = _fetch_dify_text_document(dataset_id, remote_document_id)
|
||||
if not text:
|
||||
raise NotFoundError('failed to resolve text source file')
|
||||
|
||||
filename = f'{remote_document_id}.txt'
|
||||
return Response(
|
||||
text,
|
||||
status=200,
|
||||
mimetype='text/plain; charset=utf-8',
|
||||
headers={
|
||||
'Content-Disposition': f'inline; filename="{filename}"',
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
)
|
||||
|
||||
@chat_bp.route('/preview-excel', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def preview_excel():
|
||||
"""
|
||||
内网 Excel 预览接口(简版可上线)。
|
||||
说明:
|
||||
- xlsx 直接解析;
|
||||
- xls 先转为 xlsx 后再解析。
|
||||
"""
|
||||
file_url = (request.args.get('url') or '').strip()
|
||||
if not file_url:
|
||||
raise ValidationError('url is required')
|
||||
if not _is_allowed_preview_url(file_url):
|
||||
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
|
||||
raise_for_status(msg, code)
|
||||
|
||||
detected_ext = _detect_excel_format(content or b'', ext)
|
||||
if detected_ext not in ('xlsx', 'xls'):
|
||||
raise_for_status(f'unsupported file extension: {ext or detected_ext or "unknown"}', 415)
|
||||
|
||||
try:
|
||||
wb = _load_excel_workbook(content, detected_ext)
|
||||
except Exception as e:
|
||||
current_app.logger.warning(
|
||||
"[excel-preview] parse workbook failed ext=%s detected_ext=%s size=%s name=%s url=%s err=%r",
|
||||
ext,
|
||||
detected_ext,
|
||||
len(content or b''),
|
||||
name,
|
||||
file_url,
|
||||
e,
|
||||
)
|
||||
details: dict = {}
|
||||
if current_app.config.get('DEBUG') or os.getenv('ENV_NAME', 'dev').strip().lower() == 'dev':
|
||||
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:
|
||||
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 = []
|
||||
for cell in row:
|
||||
if cell is None:
|
||||
normalized.append('')
|
||||
elif isinstance(cell, (int, float, bool)):
|
||||
normalized.append(cell)
|
||||
else:
|
||||
normalized.append(str(cell))
|
||||
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})
|
||||
|
||||
@chat_bp.route('/preview-text', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def preview_text():
|
||||
"""
|
||||
文本类文件预览接口(内网代理)。
|
||||
支持:md/markdown/txt/csv/vtt/properties/html/htm
|
||||
"""
|
||||
file_url = (request.args.get('url') or '').strip()
|
||||
if not file_url:
|
||||
raise ValidationError('url is required')
|
||||
if not _is_allowed_preview_url(file_url):
|
||||
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()
|
||||
explicit_ext = (request.args.get('ext') or '').strip().lower()
|
||||
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:
|
||||
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
|
||||
raise_for_status(msg, code)
|
||||
text = None
|
||||
for enc in ('utf-8', 'utf-8-sig', 'gb18030', 'latin-1'):
|
||||
try:
|
||||
text = content.decode(enc)
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
if text is None:
|
||||
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:
|
||||
"""
|
||||
根据文件内容(Magic Bytes)纠正可能的错误扩展名
|
||||
"""
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
if not content:
|
||||
return default_ext
|
||||
if content.startswith(b'%PDF-'):
|
||||
return 'pdf'
|
||||
if content.startswith(b'PK\x03\x04'):
|
||||
# ZIP 归档,进一步检查内部目录判断是 docx/xlsx/pptx。
|
||||
try:
|
||||
with zipfile.ZipFile(io.BytesIO(content)) as zf:
|
||||
names = {name.lower() for name in zf.namelist()}
|
||||
if any(name.startswith('word/') for name in names):
|
||||
return 'docx'
|
||||
if any(name.startswith('xl/') for name in names):
|
||||
return 'xlsx'
|
||||
if any(name.startswith('ppt/') for name in names):
|
||||
return 'pptx'
|
||||
except Exception:
|
||||
pass
|
||||
if default_ext == 'doc':
|
||||
return 'docx'
|
||||
if default_ext == 'xls':
|
||||
return 'xlsx'
|
||||
if default_ext == 'ppt':
|
||||
return 'pptx'
|
||||
if default_ext in ('docx', 'xlsx', 'pptx'):
|
||||
return default_ext
|
||||
return 'docx'
|
||||
if content.startswith(b'\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1'):
|
||||
# OLE 复合文件,通常是 doc, xls, ppt 等。
|
||||
if default_ext == 'docx': return 'doc'
|
||||
if default_ext == 'xlsx': return 'xls'
|
||||
if default_ext == 'pptx': return 'ppt'
|
||||
if default_ext in ('doc', 'xls', 'ppt'): return default_ext
|
||||
return 'doc'
|
||||
return default_ext
|
||||
|
||||
@chat_bp.route('/preview-file-raw', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def preview_file_raw():
|
||||
"""
|
||||
二进制文件内网代理预览接口。
|
||||
用途:
|
||||
- 为 pdf/doc/docx 生成可被前端 iframe 访问的同源地址;
|
||||
- 尽量使用 inline 响应头,避免强制下载。
|
||||
"""
|
||||
file_url = (request.args.get('url') or '').strip()
|
||||
if not file_url:
|
||||
raise ValidationError('url is required')
|
||||
if not _is_allowed_preview_url(file_url):
|
||||
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()
|
||||
original_ext = url_path_ext or name_ext
|
||||
ext = original_ext
|
||||
is_download = request.args.get('download') == '1'
|
||||
max_size = None if is_download else 15 * 1024 * 1024
|
||||
content, content_type, err = _fetch_preview_source_bytes(file_url, max_size=max_size)
|
||||
if err:
|
||||
msg, code = err
|
||||
raise_for_status(msg, code)
|
||||
|
||||
# 根据文件二进制头部纠正扩展名,防止文件本身是 docx 却被命名为 doc,导致转换或下载后乱码
|
||||
real_ext = _guess_ext_from_content(content, ext)
|
||||
if real_ext != ext:
|
||||
current_app.logger.info(f"[file-preview] corrected extension from {ext} to {real_ext}")
|
||||
ext = real_ext
|
||||
if name and '.' in name:
|
||||
name = f"{name.rsplit('.', 1)[0]}.{ext}"
|
||||
elif name:
|
||||
name = f"{name}.{ext}"
|
||||
|
||||
# 仅当文件真实格式仍然是旧版 Office/PPT 时才转 PDF。
|
||||
# 如果原始文件名是 .doc 但内容实际是 .docx,则交给前端 Office 组件渲染,
|
||||
# 避免在服务端走旧版转换链路导致长时间卡住。
|
||||
needs_pdf_conversion = (
|
||||
request.args.get('download') != '1'
|
||||
and ext in ('doc', 'ppt', 'pptx')
|
||||
)
|
||||
if needs_pdf_conversion:
|
||||
try:
|
||||
content = _convert_office_to_pdf(content, ext)
|
||||
ext = 'pdf'
|
||||
content_type = 'application/pdf'
|
||||
if name and '.' in name:
|
||||
name = f"{name.rsplit('.', 1)[0]}.pdf"
|
||||
elif name:
|
||||
name = f"{name}.pdf"
|
||||
except Exception as e:
|
||||
current_app.logger.error("[file-preview] LibreOffice conversion failed: %s", e)
|
||||
placeholder_text = _extract_placeholder_text(content)
|
||||
if placeholder_text:
|
||||
content = placeholder_text.encode('utf-8')
|
||||
ext = 'txt'
|
||||
content_type = 'text/plain; charset=utf-8'
|
||||
if name and '.' in name:
|
||||
name = f"{name.rsplit('.', 1)[0]}.txt"
|
||||
elif name:
|
||||
name = f"{name}.txt"
|
||||
current_app.logger.info('[file-preview] office preview degraded to text placeholder for %s', file_url)
|
||||
else:
|
||||
raise AppError(
|
||||
code='VALIDATION.UNPROCESSABLE',
|
||||
message='failed to convert office file for preview',
|
||||
http_status=422,
|
||||
)
|
||||
|
||||
fallback_types = {
|
||||
'pdf': 'application/pdf',
|
||||
'doc': 'application/msword',
|
||||
'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'xls': 'application/vnd.ms-excel',
|
||||
'csv': 'text/csv',
|
||||
'txt': 'text/plain',
|
||||
'md': 'text/markdown',
|
||||
'markdown': 'text/markdown',
|
||||
'html': 'text/html',
|
||||
'htm': 'text/html',
|
||||
}
|
||||
if ext == 'pdf' and not content.startswith(b'%PDF-'):
|
||||
placeholder_text = _extract_placeholder_text(content)
|
||||
if placeholder_text:
|
||||
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'}"
|
||||
encoded_filename = quote(filename)
|
||||
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['Cache-Control'] = 'no-store'
|
||||
resp.headers['X-Preview-Actual-Ext'] = ext or ''
|
||||
resp.headers['X-Preview-Original-Ext'] = original_ext or ''
|
||||
return resp
|
||||
@@ -0,0 +1,315 @@
|
||||
"""
|
||||
api/chat/sessions.py
|
||||
|
||||
用途:处理聊天会话、历史消息与本地结构化消息路由。
|
||||
依赖:chat.shared、chat.core、ChatSession、ChatLog。
|
||||
逻辑:校验当前用户和 Agent 后读写会话及日志,保持历史数据兼容查询。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from . import chat_bp
|
||||
from .core import (
|
||||
_chat_logs_for_session,
|
||||
_ensure_chat_session,
|
||||
_fallback_title_from_contract_review_log,
|
||||
_get_chat_session,
|
||||
_looks_like_review_auto_title,
|
||||
_serialize_session,
|
||||
_session_title_from_text,
|
||||
_user_facing_chat_query,
|
||||
)
|
||||
|
||||
|
||||
@chat_bp.route('/sessions', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_chat_sessions():
|
||||
"""
|
||||
获取当前用户与当前 Agent 的历史会话列表
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
|
||||
session_rows = db.session.query(ChatSession).filter(
|
||||
ChatSession.user_id == user.id,
|
||||
ChatSession.agent_id == agent.id,
|
||||
or_(
|
||||
ChatSession.status == 'running',
|
||||
exists().where(
|
||||
and_(
|
||||
ChatLog.session_id == ChatSession.session_id,
|
||||
ChatLog.user_id == user.id,
|
||||
ChatLog.agent_id == agent.id,
|
||||
)
|
||||
),
|
||||
),
|
||||
).order_by(desc(ChatSession.last_active_at), desc(ChatSession.id)).limit(20).all()
|
||||
|
||||
# 纠偏历史:审查结果卡曾把 headline 写成标题时,改用合同文件名展示
|
||||
title_repaired = False
|
||||
for item in session_rows:
|
||||
if not _looks_like_review_auto_title(item.title or ''):
|
||||
continue
|
||||
review_log = (
|
||||
db.session.query(ChatLog)
|
||||
.filter(
|
||||
ChatLog.user_id == user.id,
|
||||
ChatLog.agent_id == agent.id,
|
||||
ChatLog.message_type == 'procurement-contract-review',
|
||||
or_(
|
||||
ChatLog.session_id == item.session_id,
|
||||
ChatLog.conversation_id == item.session_id,
|
||||
),
|
||||
)
|
||||
.order_by(desc(ChatLog.created_at), desc(ChatLog.id))
|
||||
.first()
|
||||
)
|
||||
better = _fallback_title_from_contract_review_log(review_log)
|
||||
if better:
|
||||
item.title = better
|
||||
title_repaired = True
|
||||
if title_repaired:
|
||||
db.session.commit()
|
||||
|
||||
sessions = [_serialize_session(item) for item in session_rows]
|
||||
session_ids = {item['conversation_id'] for item in sessions}
|
||||
|
||||
# 兼容旧数据:未迁移到 chat_sessions 的历史记录继续从 chat_logs 聚合出来。
|
||||
subquery = db.session.query(
|
||||
ChatLog.conversation_id,
|
||||
func.max(ChatLog.created_at).label('last_active')
|
||||
).filter(
|
||||
ChatLog.user_id == user.id,
|
||||
ChatLog.agent_id == agent.id,
|
||||
ChatLog.session_id.is_(None),
|
||||
ChatLog.conversation_id.isnot(None),
|
||||
ChatLog.conversation_id != '',
|
||||
).group_by(ChatLog.conversation_id).subquery()
|
||||
|
||||
legacy_rows = db.session.query(
|
||||
subquery.c.conversation_id,
|
||||
subquery.c.last_active,
|
||||
).order_by(desc(subquery.c.last_active)).limit(20).all()
|
||||
|
||||
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()
|
||||
title = (latest_query_row[0] if latest_query_row and latest_query_row[0] else '').strip()
|
||||
sessions.append({
|
||||
'id': 0,
|
||||
'conversation_id': row.conversation_id,
|
||||
'title': title[:30] + ('...' if len(title) > 30 else '') if title else '',
|
||||
'created_at': row.last_active.isoformat(),
|
||||
'status': 'done',
|
||||
})
|
||||
|
||||
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():
|
||||
"""
|
||||
删除当前用户与当前 Agent 的所有历史会话
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
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:
|
||||
from app.models import GeneralFeedback
|
||||
db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(ChatSession).filter_by(user_id=user.id, agent_id=agent.id).delete(synchronize_session=False)
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@chat_bp.route('/sessions/<conversation_id>', methods=['DELETE'])
|
||||
@require_agent_permission
|
||||
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:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
|
||||
|
||||
session = _get_chat_session(user.id, agent.id, conversation_id)
|
||||
if session:
|
||||
chat_logs = db.session.query(ChatLog).filter(
|
||||
ChatLog.user_id == user.id,
|
||||
ChatLog.agent_id == agent.id,
|
||||
or_(
|
||||
ChatLog.session_id == session.session_id,
|
||||
ChatLog.conversation_id == session.external_conversation_id,
|
||||
)
|
||||
).all()
|
||||
else:
|
||||
chat_logs = db.session.query(ChatLog).filter_by(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=conversation_id
|
||||
).all()
|
||||
|
||||
chat_log_ids = [log.id for log in chat_logs]
|
||||
if chat_log_ids:
|
||||
from app.models import GeneralFeedback
|
||||
db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False)
|
||||
if session:
|
||||
db.session.delete(session)
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@chat_bp.route('/messages', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def get_chat_messages():
|
||||
"""
|
||||
获取指定会话的消息记录
|
||||
"""
|
||||
conversation_id = request.args.get('conversation_id')
|
||||
if not conversation_id:
|
||||
return jsonify([])
|
||||
|
||||
session = _get_chat_session(getattr(g.current_user, 'id', 0), getattr(g.current_agent, 'id', 0), conversation_id)
|
||||
if session:
|
||||
logs = _chat_logs_for_session(g.current_user.id, g.current_agent.id, session)
|
||||
else:
|
||||
logs = db.session.query(ChatLog).filter(
|
||||
ChatLog.user_id == g.current_user.id,
|
||||
ChatLog.agent_id == g.current_agent.id,
|
||||
ChatLog.conversation_id == conversation_id,
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
messages = []
|
||||
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
|
||||
for log in logs:
|
||||
if log.query:
|
||||
messages.append({'role': 'user', 'content': _user_facing_chat_query(log.query, agent_code=agent_code)})
|
||||
if (
|
||||
not log.answer
|
||||
and not log.message_type
|
||||
and not log.payload
|
||||
):
|
||||
continue
|
||||
if (
|
||||
log.query
|
||||
and log.answer == log.query
|
||||
and (not log.message_type or log.message_type == 'text')
|
||||
and not log.payload
|
||||
):
|
||||
continue
|
||||
assistant_msg = {
|
||||
'role': 'assistant',
|
||||
'content': DifyService._dedupe_exact_doubled_text(log.answer or ''),
|
||||
'chat_log_id': log.id,
|
||||
'retriever_resources': log.retriever_resources or [],
|
||||
'attribution_parts': log.attribution_parts or [],
|
||||
}
|
||||
if log.run_id:
|
||||
assistant_msg['run_id'] = log.run_id
|
||||
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():
|
||||
"""
|
||||
保存前端本地生成的聊天记录(如表单、确认弹窗、合同审查结果卡等)。
|
||||
|
||||
核心逻辑:user 角色用 content/query 落库;纯文本 assistant 忽略 query 防重复气泡;
|
||||
结构化 typed 消息(leave-form / procurement-contract-review 等)保留 query,供历史回放与会话标题。
|
||||
"""
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
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()
|
||||
role = (data.get('role') or 'assistant').strip()
|
||||
message_type = data.get('type')
|
||||
content = data.get('content', '')
|
||||
payload = data.get('payload')
|
||||
user_query = data.get('query', '')
|
||||
if role == 'user':
|
||||
user_query = user_query or content
|
||||
content = ''
|
||||
else:
|
||||
# [STEP] 纯文本助手消息忽略误传的 query,避免与已落库用户气泡重复(见回归测试)
|
||||
# 结构化结果卡必须保留 query,否则刷新后用户提问与历史标题都会丢失
|
||||
if not message_type or message_type == 'text':
|
||||
user_query = ''
|
||||
|
||||
if not message_type:
|
||||
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
|
||||
session = _ensure_chat_session(
|
||||
user.id,
|
||||
agent.id,
|
||||
conversation_id or None,
|
||||
title=title,
|
||||
status='done',
|
||||
external_conversation_id=external_conversation_id,
|
||||
)
|
||||
conversation_id = session.session_id
|
||||
# 纠偏:已有会话若误用审查 headline 作标题,有用户提问时改回提问摘要
|
||||
if user_query and _looks_like_review_auto_title(session.title or ''):
|
||||
session.title = _session_title_from_text(user_query)
|
||||
|
||||
# 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录
|
||||
# 这样能保证前端表单状态(例如已确认)被持久化
|
||||
local_id = payload.get('formId') if payload and isinstance(payload, dict) else None
|
||||
chat_log = None
|
||||
if local_id:
|
||||
# 在 payload 中查找是否已存在相同 formId 的同类型消息
|
||||
# SQLite / Postgres 对 JSON 过滤有差异,为了简单,我们可以取出当前会话的所有该类型消息并在内存中匹配
|
||||
logs = db.session.query(ChatLog).filter_by(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
session_id=conversation_id,
|
||||
message_type=message_type
|
||||
).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):
|
||||
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):
|
||||
chat_log.query = user_query
|
||||
else:
|
||||
chat_log = ChatLog(
|
||||
user_id=user.id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.external_conversation_id or conversation_id,
|
||||
session_id=conversation_id,
|
||||
query=user_query,
|
||||
answer=content,
|
||||
message_type=message_type,
|
||||
payload=payload
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
session.status = 'done'
|
||||
session.last_active_at = datetime.utcnow()
|
||||
session.updated_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'chat_log_id': chat_log.id, 'conversation_id': conversation_id})
|
||||
@@ -0,0 +1,47 @@
|
||||
"""
|
||||
api/chat/shared.py
|
||||
|
||||
用途:汇总聊天 API 子模块共同使用的框架对象、模型、服务和常量。
|
||||
依赖:Flask、SQLAlchemy、DifyService、IntegrationApiService、聊天数据模型。
|
||||
逻辑:各 chat 路由模块从本文件复用基础依赖;Blueprint 仅由 api/chat/__init__.py 创建,避免重复注册。
|
||||
"""
|
||||
import io
|
||||
import ipaddress
|
||||
import mimetypes
|
||||
import ntpath
|
||||
import posixpath
|
||||
import tempfile
|
||||
import os
|
||||
import subprocess
|
||||
import uuid
|
||||
import json
|
||||
import time
|
||||
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_, exists, and_
|
||||
from openpyxl import load_workbook
|
||||
from app.services.agent_runtime_context.dify_inputs import build_chat_dify_inputs
|
||||
from app.services.dify import DifyService
|
||||
from app.core.config.settings import Config
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
from app.core.decorators import require_agent_permission
|
||||
from app.models import Agent, ChatLog, ChatSession, Feedback
|
||||
from app import db
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'
|
||||
|
||||
|
||||
PLM_PREVIEW_SHARE_ROOT = (os.getenv('PLM_PREVIEW_SHARE_ROOT') or '\\\\192.168.0.11\\dss\\dssroot\\').strip()
|
||||
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
"""
|
||||
api/chat/uploads.py
|
||||
|
||||
用途:处理聊天附件上传并转发至当前 Agent 对应的 Dify 应用。
|
||||
依赖:chat.shared、DifyService、Config、requests、chat_bp。
|
||||
逻辑:校验文件类型、上传方式和大小限制后调用 Dify 文件接口,返回标准化文件元数据。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from . import chat_bp
|
||||
|
||||
|
||||
@chat_bp.route('/files/upload', methods=['POST'])
|
||||
@require_agent_permission
|
||||
def upload_chat_file():
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
if user is None or agent is None:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing user or agent context', http_status=500)
|
||||
if str(getattr(agent, 'type', '') or '').strip().lower() != 'api':
|
||||
raise ValidationError('This agent does not support file upload')
|
||||
if not getattr(agent, 'dify_api_key', None):
|
||||
raise ValidationError('This agent does not support file upload')
|
||||
|
||||
upload = request.files.get('file')
|
||||
if not upload:
|
||||
raise ValidationError('file is required')
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.core.config.settings import Config
|
||||
|
||||
params = DifyService.get_app_parameters(agent, force_refresh=True)
|
||||
file_upload_cfg = (params or {}).get('file_upload') if isinstance(params, dict) else {}
|
||||
system_params = (params or {}).get('system_parameters') if isinstance(params, dict) else {}
|
||||
|
||||
filename = str(getattr(upload, 'filename', '') or '').strip()
|
||||
mimetype = str(getattr(upload, 'mimetype', '') or '').lower().strip()
|
||||
detected_type, ext = DifyService.detect_file_type(filename, mimetype)
|
||||
file_type = None
|
||||
normalized_allowed_types = None
|
||||
normalized_allowed_methods = None
|
||||
normalized_allowed_exts = None
|
||||
is_new_schema = False
|
||||
if isinstance(file_upload_cfg, dict) and file_upload_cfg.get('enabled') is True and isinstance(file_upload_cfg.get('allowed_file_types'), list):
|
||||
is_new_schema = True
|
||||
normalized_allowed_types = set(
|
||||
(
|
||||
str(v or '').strip().lower()
|
||||
for v in (file_upload_cfg.get('allowed_file_types') or [])
|
||||
if str(v or '').strip()
|
||||
)
|
||||
)
|
||||
normalized_allowed_methods = set(
|
||||
(
|
||||
str(v or '').strip().lower()
|
||||
for v in (file_upload_cfg.get('allowed_file_upload_methods') or [])
|
||||
if str(v or '').strip()
|
||||
)
|
||||
)
|
||||
exts = []
|
||||
for v in (file_upload_cfg.get('allowed_file_extensions') or []):
|
||||
s = str(v or '').strip()
|
||||
if not s:
|
||||
continue
|
||||
if s.startswith('.'):
|
||||
s = s[1:]
|
||||
s = s.lower().strip()
|
||||
if s:
|
||||
exts.append(s)
|
||||
normalized_allowed_exts = set(exts) if exts else None
|
||||
|
||||
if detected_type:
|
||||
file_type = detected_type
|
||||
else:
|
||||
if is_new_schema and normalized_allowed_types and 'custom' in normalized_allowed_types and (not DifyService.is_known_file_extension(ext)):
|
||||
file_type = 'custom'
|
||||
else:
|
||||
custom_cfg = file_upload_cfg.get('custom') if isinstance(file_upload_cfg, dict) else None
|
||||
if isinstance(custom_cfg, dict) and custom_cfg.get('enabled') and (not DifyService.is_known_file_extension(ext)):
|
||||
file_type = 'custom'
|
||||
else:
|
||||
raise ValidationError(f'Unsupported file type (ext={ext or ""}, mime={mimetype or ""})')
|
||||
|
||||
def _effective_type_methods(target_type: str) -> set[str]:
|
||||
if not isinstance(file_upload_cfg, dict):
|
||||
return set(normalized_allowed_methods or set())
|
||||
cfg = file_upload_cfg.get(target_type)
|
||||
transfer_methods = []
|
||||
if isinstance(cfg, dict):
|
||||
transfer_methods = cfg.get('transfer_methods') or cfg.get('transfer_methods'.replace('_', '-')) or []
|
||||
if isinstance(transfer_methods, str):
|
||||
transfer_methods = [transfer_methods]
|
||||
if isinstance(transfer_methods, list) and len(transfer_methods) > 0:
|
||||
return set(str(m or '').strip().lower() for m in transfer_methods if str(m or '').strip())
|
||||
return set(normalized_allowed_methods or set())
|
||||
|
||||
def _is_type_enabled_in_new_schema(target_type: str) -> bool:
|
||||
if not (is_new_schema and normalized_allowed_types):
|
||||
return False
|
||||
if not isinstance(file_upload_cfg, dict):
|
||||
return target_type in normalized_allowed_types
|
||||
cfg = file_upload_cfg.get(target_type)
|
||||
if isinstance(cfg, dict) and isinstance(cfg.get('enabled'), bool):
|
||||
if cfg.get('enabled') is False:
|
||||
return False
|
||||
if cfg.get('enabled') is True:
|
||||
return True
|
||||
return target_type in normalized_allowed_types
|
||||
|
||||
if is_new_schema and normalized_allowed_types:
|
||||
if not _is_type_enabled_in_new_schema(file_type):
|
||||
raise ValidationError(f'File type not enabled: {file_type}')
|
||||
type_methods = _effective_type_methods(file_type)
|
||||
if 'local_file' not in type_methods:
|
||||
raise ValidationError('local_file upload is not enabled')
|
||||
if normalized_allowed_exts:
|
||||
allowed_for_type = set()
|
||||
for e in normalized_allowed_exts:
|
||||
t, _ = DifyService.detect_file_type(f'file.{e}', None)
|
||||
if t is None:
|
||||
if _is_type_enabled_in_new_schema('custom') and (not DifyService.is_known_file_extension(e)):
|
||||
allowed_for_type.add(e)
|
||||
continue
|
||||
if t == file_type:
|
||||
allowed_for_type.add(e)
|
||||
if allowed_for_type and (not ext or ext not in allowed_for_type):
|
||||
raise ValidationError(f'Unsupported file extension: .{ext or ""}')
|
||||
else:
|
||||
# legacy schema checks
|
||||
type_cfg = file_upload_cfg.get(file_type) if isinstance(file_upload_cfg, dict) else None
|
||||
if not isinstance(type_cfg, dict) or not type_cfg.get('enabled'):
|
||||
raise ValidationError(f'File type not enabled: {file_type}')
|
||||
transfer_methods = type_cfg.get('transfer_methods') or type_cfg.get('transfer_methods'.replace('_', '-')) or []
|
||||
if isinstance(transfer_methods, str):
|
||||
transfer_methods = [transfer_methods]
|
||||
if 'local_file' not in set((str(m).strip() for m in transfer_methods if m is not None)):
|
||||
raise ValidationError('local_file upload is not enabled')
|
||||
|
||||
def _mb_limit_for_type() -> float | None:
|
||||
merged = {}
|
||||
if isinstance(system_params, dict):
|
||||
merged.update(system_params)
|
||||
if isinstance(file_upload_cfg, dict) and isinstance(file_upload_cfg.get('fileUploadConfig'), dict):
|
||||
merged.update(file_upload_cfg.get('fileUploadConfig') or {})
|
||||
if file_type == 'image':
|
||||
return merged.get('image_file_size_limit') or merged.get('file_size_limit')
|
||||
if file_type == 'audio':
|
||||
return merged.get('audio_file_size_limit') or merged.get('file_size_limit')
|
||||
if file_type == 'video':
|
||||
return merged.get('video_file_size_limit') or merged.get('file_size_limit')
|
||||
return merged.get('file_size_limit')
|
||||
|
||||
size_limit_mb = _mb_limit_for_type()
|
||||
if size_limit_mb is not None:
|
||||
try:
|
||||
import os
|
||||
stream = getattr(upload, 'stream', None)
|
||||
if stream and hasattr(stream, 'tell') and hasattr(stream, 'seek'):
|
||||
cur = stream.tell()
|
||||
stream.seek(0, os.SEEK_END)
|
||||
size_bytes = stream.tell()
|
||||
stream.seek(cur)
|
||||
limit_bytes = int(float(size_limit_mb) * 1024 * 1024)
|
||||
if size_bytes > limit_bytes:
|
||||
raise ValidationError(f'File too large (limit {size_limit_mb}MB)')
|
||||
except ValidationError:
|
||||
raise
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
base_url = agent.api_base_url if getattr(agent, 'api_base_url', None) else Config.DIFY_API_BASE
|
||||
dify_url = DifyService._build_files_upload_url(base_url)
|
||||
headers = {'Authorization': f'Bearer {agent.dify_api_key}'}
|
||||
|
||||
try:
|
||||
try:
|
||||
upload.stream.seek(0)
|
||||
except Exception:
|
||||
pass
|
||||
resp = requests.post(
|
||||
dify_url,
|
||||
headers=headers,
|
||||
files={'file': (filename or 'upload', upload.stream, mimetype or 'application/octet-stream')},
|
||||
data={'user': str(getattr(user, 'id', 'system'))},
|
||||
timeout=(5, 300),
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
raise ServiceUnavailableError(f'Upload failed: {exc}')
|
||||
|
||||
if not resp.ok:
|
||||
body = (resp.text or '')[:1500]
|
||||
header_snapshot = {}
|
||||
try:
|
||||
for k in ('x-request-id', 'x-requestid', 'request-id', 'trace-id', 'cf-ray', 'server', 'date'):
|
||||
v = resp.headers.get(k) or resp.headers.get(k.title())
|
||||
if v:
|
||||
header_snapshot[k] = v
|
||||
except Exception:
|
||||
header_snapshot = {}
|
||||
current_app.logger.warning(
|
||||
'[chat-upload] dify upload failed status=%s url=%s headers=%s body=%s',
|
||||
resp.status_code,
|
||||
dify_url,
|
||||
header_snapshot,
|
||||
body,
|
||||
)
|
||||
raise AppError(
|
||||
code='DIFY.UPLOAD_FAILED',
|
||||
message='Upload failed',
|
||||
http_status=502,
|
||||
details={'status': resp.status_code, 'body': body, 'url': dify_url, 'headers': header_snapshot},
|
||||
)
|
||||
|
||||
data = resp.json() if resp.content else {}
|
||||
return jsonify({
|
||||
'id': data.get('id'),
|
||||
'name': data.get('name') or filename,
|
||||
'size': data.get('size'),
|
||||
'extension': data.get('extension') or ext,
|
||||
'mime_type': data.get('mime_type') or mimetype,
|
||||
'type': file_type,
|
||||
})
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
api/user/__init__.py
|
||||
|
||||
用途:导出用户域与认证域 Blueprint,并维护历史测试替身兼容入口。
|
||||
依赖:handlers、auth 及其共享认证操作。
|
||||
逻辑:register_blueprints 将两个 Blueprint 挂载到 `/api/user`;兼容代理确保迁包前的替身点仍然生效。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from types import ModuleType
|
||||
|
||||
from . import handlers
|
||||
from . import auth
|
||||
from .auth import auth_bp
|
||||
|
||||
|
||||
user_bp = handlers.user_bp
|
||||
|
||||
# The documented Wave 3 compatibility export supports existing tests and callers.
|
||||
_get_current_user = handlers._get_current_user
|
||||
|
||||
|
||||
class _UserApiCompatModule(ModuleType):
|
||||
"""Forward historic private test replacement points to the canonical handlers."""
|
||||
|
||||
def __setattr__(self, name: str, value: object) -> None:
|
||||
super().__setattr__(name, value)
|
||||
if hasattr(handlers, name):
|
||||
setattr(handlers, name, value)
|
||||
if hasattr(auth, name):
|
||||
setattr(auth, name, value)
|
||||
|
||||
|
||||
sys.modules[__name__].__class__ = _UserApiCompatModule
|
||||
|
||||
|
||||
def __getattr__(name: str):
|
||||
"""Expose historic test symbols from their formal auth or user module."""
|
||||
if hasattr(auth, name):
|
||||
return getattr(auth, name)
|
||||
return getattr(handlers, name)
|
||||
|
||||
|
||||
__all__ = ['auth_bp', 'user_bp']
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
api/user/auth.py
|
||||
|
||||
用途:用户认证 Blueprint 的兼容门面与路由装配入口。
|
||||
依赖:auth_local、auth_casdoor、auth_wecom、auth_password_reset、auth_support。
|
||||
逻辑:api/user/__init__.py 从此模块导出 auth_bp;各职责路由在独立模块注册,历史测试仍可替换本模块私有符号。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from types import ModuleType
|
||||
|
||||
from flask import Blueprint
|
||||
|
||||
from . import auth_support as _support
|
||||
|
||||
auth_bp = Blueprint('user_auth', __name__)
|
||||
|
||||
|
||||
class _AuthCompatModule(ModuleType):
|
||||
"""将历史 monkeypatch 同步到共享认证操作,保持测试替身入口稳定。"""
|
||||
|
||||
def __setattr__(self, name: str, value: object) -> None:
|
||||
super().__setattr__(name, value)
|
||||
if hasattr(_support, name):
|
||||
setattr(_support, name, value)
|
||||
|
||||
|
||||
sys.modules[__name__].__class__ = _AuthCompatModule
|
||||
|
||||
|
||||
def __getattr__(name: str):
|
||||
"""兼容导出共享认证操作与历史测试替身点。"""
|
||||
return getattr(_support, name)
|
||||
|
||||
|
||||
# Importing modules registers their narrow route groups on the shared Blueprint.
|
||||
from . import auth_casdoor, auth_local, auth_password_reset, auth_wecom # noqa: E402, F401
|
||||
|
||||
__all__ = ['auth_bp']
|
||||
@@ -0,0 +1,125 @@
|
||||
"""
|
||||
api/user/auth_casdoor.py
|
||||
|
||||
用途:Casdoor 密码、授权码与刷新令牌认证路由。
|
||||
依赖:auth.auth_bp、auth_support 兼容操作、services/auth/hxops。
|
||||
逻辑:HTTP 参数与公开 URL 在本模块分组;登录编排仍复用已有 Casdoor 服务适配器。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, UnauthorizedError, ValidationError
|
||||
from app.services.auth.hxops.casdoor_authorize import CasdoorAuthorizeOptions
|
||||
|
||||
from . import auth as _compat
|
||||
from .auth import auth_bp
|
||||
|
||||
|
||||
@auth_bp.post('/casdoor/password-login', endpoint='casdoor_password_login')
|
||||
def password_login():
|
||||
"""使用 Casdoor password grant 登录,并返回 HXOPS 本地 API 会话。"""
|
||||
if (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() != 'casdoor':
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_PASSWORD_LOGIN_DISABLED',
|
||||
message='Casdoor password login is disabled by AUTH_LOGIN_MODE',
|
||||
http_status=403,
|
||||
)
|
||||
data = request.get_json() or {}
|
||||
username = _compat._clean_str(data.get('username'))
|
||||
password = data.get('password') or ''
|
||||
if not username or not password:
|
||||
raise ValidationError('Username and password are required')
|
||||
try:
|
||||
result = _compat._hxops_login_service().password(username, password)
|
||||
db.session.commit()
|
||||
return jsonify(result.login_payload())
|
||||
except _compat.WeComLoginError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
_compat._raise_casdoor_auth_error(exc, context='password')
|
||||
|
||||
|
||||
@auth_bp.get('/casdoor/authorize-url', endpoint='casdoor_authorize_url')
|
||||
def authorize_url():
|
||||
"""生成包含状态参数的 Casdoor 授权码登录地址。"""
|
||||
try:
|
||||
options = CasdoorAuthorizeOptions(
|
||||
redirect_uri=request.args.get('redirect_uri'),
|
||||
provider_hint=request.args.get('provider_hint'),
|
||||
default_provider=request.args.get('default_provider'),
|
||||
silent_signin=request.args.get('silent_signin'),
|
||||
)
|
||||
return jsonify(_compat._build_casdoor_authorize_payload(options))
|
||||
except Exception as exc:
|
||||
raise AppError(
|
||||
code='SYSTEM.INTERNAL_ERROR',
|
||||
message=f'Failed to build Casdoor authorize url: {exc}',
|
||||
http_status=500,
|
||||
) from exc
|
||||
|
||||
|
||||
@auth_bp.post('/casdoor/login', endpoint='casdoor_login')
|
||||
def authorization_code_login():
|
||||
"""交换授权码、映射本地用户并签发 HXOPS API 会话。"""
|
||||
data = request.get_json() or {}
|
||||
code = _compat._clean_str(data.get('code'))
|
||||
state = _compat._clean_str(data.get('state'))
|
||||
if not code:
|
||||
raise ValidationError('code is required')
|
||||
current_app.logger.info('[casdoor_login] start code_len=%s state=%s', len(code), state[:24] if state else '')
|
||||
redirect_uri = _compat._consume_casdoor_state(state)
|
||||
if not redirect_uri:
|
||||
current_app.logger.warning('[casdoor_login] invalid_state state=%s', state[:24] if state else '')
|
||||
raise ValidationError('Invalid or expired Casdoor state')
|
||||
try:
|
||||
result = _compat._hxops_login_service().authorization_code(code, redirect_uri)
|
||||
current_app.logger.info('[casdoor_login] user_resolved username=%s id=%s', result.user.username, result.user.id)
|
||||
db.session.commit()
|
||||
return jsonify(result.login_payload())
|
||||
except _compat.WeComLoginError:
|
||||
db.session.rollback()
|
||||
current_app.logger.warning('[casdoor_login] business_reject')
|
||||
raise
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
current_app.logger.exception('[casdoor_login] failed state=%s redirect_uri=%s', state[:24] if state else '', redirect_uri)
|
||||
_compat._raise_casdoor_auth_error(exc, context='code')
|
||||
|
||||
|
||||
@auth_bp.post('/casdoor/refresh', endpoint='casdoor_refresh')
|
||||
def refresh():
|
||||
"""以 Casdoor refresh token 换取新的 HXOPS API 会话。"""
|
||||
data = request.get_json() or {}
|
||||
refresh_token = _compat._clean_str(data.get('refresh_token'))
|
||||
if not refresh_token:
|
||||
raise ValidationError('refresh_token is required')
|
||||
current_app.logger.info('[casdoor_refresh] start refresh=%s', _compat._token_brief(refresh_token))
|
||||
try:
|
||||
result = _compat._hxops_login_service().refresh(refresh_token)
|
||||
current_app.logger.info(
|
||||
'[casdoor_refresh] token_refresh_ok next_refresh=%s user_id=%s',
|
||||
_compat._token_brief(result.refresh_token), result.user.id,
|
||||
)
|
||||
return jsonify(result.refresh_payload())
|
||||
except AppError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
message = str(exc)
|
||||
if 'unsupported_grant_type' in message or 'refresh_token is not supported' in message:
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
|
||||
message='Casdoor refresh token is not supported by current application config',
|
||||
http_status=400,
|
||||
) from exc
|
||||
current_app.logger.exception('[casdoor_refresh] failed refresh=%s', _compat._token_brief(refresh_token))
|
||||
raise UnauthorizedError(f'Casdoor refresh failed: {exc}') from exc
|
||||
@@ -0,0 +1,128 @@
|
||||
"""
|
||||
api/user/auth_local.py
|
||||
|
||||
用途:注册、传统密码登录与改密 HTTP 路由。
|
||||
依赖:auth.auth_bp、auth_support 的共享认证操作。
|
||||
逻辑:本模块仅装配本地密码职责;业务处理暂由兼容实现承接,后续迁移不改变公开 URL。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import current_app, jsonify, request
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ServiceUnavailableError, UnauthorizedError, ValidationError
|
||||
|
||||
from . import auth as _compat
|
||||
from .auth import auth_bp
|
||||
|
||||
|
||||
@auth_bp.post('/register', endpoint='register')
|
||||
def register():
|
||||
"""校验必填和唯一字段后创建本地用户,保持原有注册响应。"""
|
||||
data = request.get_json() or {}
|
||||
required_fields = ['username', 'password', 'email', 'real_name', 'employee_id', 'phone_number']
|
||||
for field in required_fields:
|
||||
if not data.get(field):
|
||||
raise ValidationError(f'{field} is required')
|
||||
if db.session.query(_compat.User).filter_by(username=data['username']).first():
|
||||
raise ValidationError('Username already exists')
|
||||
if db.session.query(_compat.User).filter_by(email=data['email']).first():
|
||||
raise ValidationError('Email already exists')
|
||||
if db.session.query(_compat.User).filter_by(employee_id=data['employee_id']).first():
|
||||
raise ValidationError('Employee ID already exists')
|
||||
try:
|
||||
user = _compat.User(
|
||||
username=data['username'], email=data['email'], real_name=data['real_name'],
|
||||
employee_id=data['employee_id'], phone_number=data['phone_number'],
|
||||
department=data.get('department'), role='user', status='active',
|
||||
)
|
||||
user.set_password(data['password'])
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Registration successful', 'id': user.id}), 201
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500) from exc
|
||||
|
||||
|
||||
@auth_bp.post('/login', endpoint='login')
|
||||
def login():
|
||||
"""处理兼容的本地用户名密码登录;委托原有审计与重试逻辑。"""
|
||||
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', True)):
|
||||
raise AppError(
|
||||
code='AUTH.PASSWORD_LOGIN_DISABLED',
|
||||
message='Password login is disabled. Please use Casdoor login.',
|
||||
http_status=403,
|
||||
)
|
||||
|
||||
def attempt_login():
|
||||
"""校验本地密码并写入登录审计;用于可恢复数据库失败的一次重试。"""
|
||||
data = request.get_json() or {}
|
||||
username = data.get('username')
|
||||
password = data.get('password')
|
||||
if not username or not password:
|
||||
_compat._write_login_audit('password', 'failed', username=username, reason='missing_credentials')
|
||||
raise ValidationError('Username and password are required')
|
||||
user = db.session.query(_compat.User).filter_by(username=username).first()
|
||||
if not user:
|
||||
_compat._write_login_audit('password', 'failed', username=username, reason='user_not_found')
|
||||
db.session.commit()
|
||||
raise AppError(code='AUTH.USER_NOT_FOUND', message='User not found', http_status=404)
|
||||
if not user.check_password(password):
|
||||
_compat._write_login_audit('password', 'failed', user=user, reason='incorrect_password')
|
||||
db.session.commit()
|
||||
raise AppError(code='AUTH.INCORRECT_PASSWORD', message='Incorrect password', http_status=401)
|
||||
if user.status != 'active':
|
||||
_compat._write_login_audit('password', 'failed', user=user, reason='account_disabled')
|
||||
db.session.commit()
|
||||
raise AppError(code='AUTH.ACCOUNT_DISABLED', message='Account is disabled', http_status=403)
|
||||
_compat._write_login_audit('password', 'success', user=user)
|
||||
db.session.commit()
|
||||
return jsonify(_compat._build_login_payload(user, 'password'))
|
||||
|
||||
try:
|
||||
return attempt_login()
|
||||
except (OperationalError, DatabaseError):
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
return attempt_login()
|
||||
except (OperationalError, DatabaseError) as retry_exc:
|
||||
current_app.logger.warning('Password login retry failed: %s', retry_exc)
|
||||
raise ServiceUnavailableError('Database connection failed') from retry_exc
|
||||
except AppError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
current_app.logger.exception('Login error: %s', exc)
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Internal server error', http_status=500) from exc
|
||||
|
||||
|
||||
@auth_bp.post('/change-password', endpoint='change_password')
|
||||
def change_password():
|
||||
"""校验当前身份并同步更新本地与 Casdoor 密码。"""
|
||||
user = _compat._get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
current_password = data.get('current_password')
|
||||
new_password = data.get('new_password')
|
||||
if not current_password or not new_password:
|
||||
raise ValidationError('Current and new password are required')
|
||||
try:
|
||||
_compat._verify_current_password_for_change(user, current_password)
|
||||
_compat._sync_casdoor_password(user.username, current_password, new_password)
|
||||
user.set_password(new_password)
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Password changed successfully'})
|
||||
except AppError:
|
||||
raise
|
||||
except RuntimeError as exc:
|
||||
db.session.rollback()
|
||||
if _compat._is_casdoor_password_error(str(exc)):
|
||||
_compat._raise_incorrect_current_password()
|
||||
_compat._raise_casdoor_set_password_error(exc)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500) from exc
|
||||
@@ -0,0 +1,147 @@
|
||||
"""
|
||||
api/user/auth_password_reset.py
|
||||
|
||||
用途:密码找回与确认重置 HTTP 路由。
|
||||
依赖:auth.auth_bp、auth_support 的企微配置与 Casdoor 密码同步操作。
|
||||
逻辑:密码重置从常规登录路由分离;保留原有 URL、通用提示语和令牌有效期语义。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
import uuid
|
||||
|
||||
from flask import current_app, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ValidationError
|
||||
from app.services.wecom_notify import send_wecom_event_message
|
||||
|
||||
from . import auth as _compat
|
||||
from .auth import auth_bp
|
||||
|
||||
_RATE_CACHE: dict[str, datetime] = {}
|
||||
_GENERIC_MESSAGE = 'If the account exists and WeCom is bound, a reset link has been sent to your WeCom.'
|
||||
|
||||
|
||||
def _base_url() -> str:
|
||||
"""读取密码重置的公网基地址,避免将内部服务地址发给企业微信用户。"""
|
||||
for key in ('WECOM_PUBLIC_BASE_URL', 'PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'):
|
||||
base = _compat._clean_str(current_app.config.get(key))
|
||||
if base:
|
||||
return base.rstrip('/')
|
||||
return ''
|
||||
|
||||
|
||||
def _rate_limit(employee_id: str, *, window_seconds: int = 300) -> tuple[bool, int]:
|
||||
"""按工号和来源 IP 限制找回请求,返回是否允许及剩余等待秒数。"""
|
||||
client_ip = request.headers.get('X-Forwarded-For', request.remote_addr) or 'unknown'
|
||||
key = f'{employee_id}:{client_ip}'
|
||||
now = datetime.utcnow()
|
||||
last = _RATE_CACHE.get(key)
|
||||
if last:
|
||||
elapsed = (now - last).total_seconds()
|
||||
if elapsed < window_seconds:
|
||||
return False, max(1, int(window_seconds - elapsed))
|
||||
_RATE_CACHE[key] = now
|
||||
return True, 0
|
||||
|
||||
|
||||
def _sync_casdoor_password(user, new_password: str) -> None:
|
||||
"""令牌重置无需旧密码;Casdoor 启用时仍须同步 IdP 密码。"""
|
||||
if not _compat._is_casdoor_configured():
|
||||
return
|
||||
try:
|
||||
_compat._casdoor_set_password(_compat._casdoor_user_owner(), user.username, '', new_password)
|
||||
except RuntimeError as exc:
|
||||
if _compat._is_casdoor_user_missing_error(str(exc)):
|
||||
_compat._raise_casdoor_user_not_in_idp(exc)
|
||||
_compat._raise_casdoor_set_password_error(exc)
|
||||
|
||||
|
||||
@auth_bp.post('/reset-password-by-wecom', endpoint='reset_password_by_wecom')
|
||||
def request_by_wecom():
|
||||
"""向已绑定企业微信的用户发送限时重置链接。"""
|
||||
if not _compat._is_wecom_configured():
|
||||
raise AppError(code='WECOM.RESET_NOT_CONFIGURED', message='WeCom password reset is not configured', http_status=503, details={'missing': _compat._get_wecom_config_missing_fields()})
|
||||
if not bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)):
|
||||
raise AppError(code='WECOM.NOTIFY_DISABLED', message='WeCom notification is disabled', http_status=503)
|
||||
base_url = _base_url()
|
||||
if not base_url:
|
||||
raise AppError(code='WECOM.RESET_URL_NOT_CONFIGURED', message='Password reset public base URL is not configured', http_status=503)
|
||||
data = request.get_json() or {}
|
||||
employee_id = _compat._clean_str(data.get('employee_id'))
|
||||
username = _compat._clean_str(data.get('username'))
|
||||
if not employee_id:
|
||||
raise ValidationError('Employee ID is required')
|
||||
if not username:
|
||||
raise ValidationError('Username is required')
|
||||
allowed, retry_after_seconds = _rate_limit(employee_id)
|
||||
if not allowed:
|
||||
raise AppError(code='AUTH.PASSWORD_RESET_RATE_LIMITED', message='Password reset requests are too frequent', http_status=429, details={'retry_after_seconds': retry_after_seconds, 'retry_after_minutes': max(1, (retry_after_seconds + 59) // 60)}, retryable=True)
|
||||
user = db.session.query(_compat.User).filter(_compat.User.employee_id == employee_id).first()
|
||||
if not user or user.username != username or user.status != 'active' or not user.wecom_userid:
|
||||
return jsonify({'message': _GENERIC_MESSAGE})
|
||||
token = str(uuid.uuid4())
|
||||
user.reset_token = token
|
||||
user.reset_token_expiry = datetime.utcnow() + timedelta(hours=1)
|
||||
db.session.flush()
|
||||
try:
|
||||
result = send_wecom_event_message(event_type='password_reset', user=user, title='和信AI智能工作台 密码重置', content='您发起了和信AI智能工作台密码重置请求。\n请在 1 小时内点击下方按钮设置新密码。\n如非本人操作,请忽略本消息。', jump_url=f'{base_url}/reset-password?token={token}')
|
||||
if not result.get('ok'):
|
||||
db.session.rollback()
|
||||
return jsonify({'message': _GENERIC_MESSAGE})
|
||||
db.session.commit()
|
||||
return jsonify({'message': _GENERIC_MESSAGE})
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
current_app.logger.exception('[password_reset] unexpected failure user_id=%s: %s', user.id, exc)
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Failed to request password reset', http_status=500) from exc
|
||||
|
||||
|
||||
@auth_bp.post('/reset-password-by-email', endpoint='reset_password_request')
|
||||
def request_by_email():
|
||||
"""保留邮件找回兼容接口及其既有响应格式。"""
|
||||
data = request.get_json() or {}
|
||||
email = data.get('email')
|
||||
if not email:
|
||||
raise ValidationError('Email is required')
|
||||
user = db.session.query(_compat.User).filter_by(email=email).first()
|
||||
if not user:
|
||||
return jsonify({'message': 'If the email exists, a reset link has been sent.'})
|
||||
user.reset_token = str(uuid.uuid4())
|
||||
user.reset_token_expiry = datetime.utcnow() + timedelta(hours=1)
|
||||
db.session.commit()
|
||||
# Legacy development contract: the email channel is mocked by logging its reset link.
|
||||
reset_link = f'http://localhost:5173/reset-password?token={user.reset_token}'
|
||||
print('============================================')
|
||||
print(f'MOCK EMAIL TO: {email}')
|
||||
print('SUBJECT: Password Reset Request')
|
||||
print(f'LINK: {reset_link}')
|
||||
print('============================================')
|
||||
return jsonify({'message': 'If the email exists, a reset link has been sent.'})
|
||||
|
||||
|
||||
@auth_bp.post('/reset-password-confirm', endpoint='reset_password_confirm')
|
||||
def confirm():
|
||||
"""校验重置令牌后同步更新本地与 Casdoor 密码。"""
|
||||
data = request.get_json() or {}
|
||||
token = _compat._clean_str(data.get('token'))
|
||||
new_password = data.get('new_password')
|
||||
if not token or not new_password:
|
||||
raise ValidationError('Token and new password are required')
|
||||
user = db.session.query(_compat.User).filter_by(reset_token=token).first()
|
||||
if not user or not user.reset_token_expiry or user.reset_token_expiry < datetime.utcnow():
|
||||
raise AppError(code='AUTH.RESET_TOKEN_INVALID', message='Invalid or expired token', http_status=400)
|
||||
try:
|
||||
_sync_casdoor_password(user, new_password)
|
||||
user.set_password(new_password)
|
||||
user.reset_token = None
|
||||
user.reset_token_expiry = None
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Password has been reset successfully'})
|
||||
except AppError:
|
||||
db.session.rollback()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500) from exc
|
||||
@@ -0,0 +1,628 @@
|
||||
"""
|
||||
api/user/auth_support.py
|
||||
|
||||
用途:承载用户认证域的共享操作,包括 Casdoor 兼容适配、企微身份匹配、登录审计和短时状态。
|
||||
依赖:services/auth、services/wecom_auth_service、models.User/LoginAudit/WecomCallbackAudit。
|
||||
逻辑:auth_* 路由模块调用本文件完成领域协作;auth.py 兼容门面转发历史测试替身,不再保留路由实现。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import request, jsonify, current_app
|
||||
from app import db
|
||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog
|
||||
from app.services.feedback_notify import send_feedback_group_notification
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.agent_registry.serialization import serialize_registry_fields
|
||||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
from app.services.wecom_crypto import sha1_hex, decrypt_wecom_aes, extract_encrypt_field
|
||||
from app.core.auth.jwt import get_current_user as _auth_current_user
|
||||
from sqlalchemy.exc import DatabaseError, IntegrityError, OperationalError
|
||||
from sqlalchemy import and_, or_, inspect, insert
|
||||
from datetime import datetime, timedelta
|
||||
import uuid
|
||||
import requests
|
||||
from urllib.parse import quote
|
||||
import re
|
||||
import ast
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ConflictError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
ServiceUnavailableError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
raise_for_status,
|
||||
)
|
||||
from app.services.auth import casdoor_service as _casdoor_svc
|
||||
from app.services.auth.hxops.casdoor_authorize import CasdoorAuthorizeOptions
|
||||
from app.services.auth.hxops.login_service import HxopsLoginService
|
||||
from app.services.auth.hxops import casdoor_route_adapter as _casdoor_route_adapter
|
||||
from app.services.auth import wecom_auth_service as _wecom_svc
|
||||
_WECOM_ACCESS_TOKEN_CACHE = _wecom_svc.ACCESS_TOKEN_CACHE
|
||||
_WECOM_STATE_CACHE = _wecom_svc.STATE_CACHE
|
||||
_WECOM_BIND_SESSION_CACHE = _wecom_svc.BIND_SESSION_CACHE
|
||||
_PASSWORD_RESET_RATE_CACHE = {}
|
||||
_PASSWORD_RESET_GENERIC_MESSAGE = 'If the account exists and WeCom is bound, a reset link has been sent to your WeCom.'
|
||||
_ALLOWED_WECOM_MATCH_FIELDS = {'employee_id', 'mobile', 'email'}
|
||||
_LOGIN_AUDIT_COLUMNS_CACHE = None
|
||||
|
||||
|
||||
def _token_brief(token: str) -> str:
|
||||
if not token:
|
||||
return 'empty'
|
||||
text = str(token)
|
||||
if len(text) <= 16:
|
||||
return f'len={len(text)}:{text}'
|
||||
return f'len={len(text)}:{text[:8]}...{text[-8:]}'
|
||||
|
||||
def _is_users_pk_sequence_error(exc: Exception) -> bool:
|
||||
message = str(exc)
|
||||
return 'null value in column "id"' in message and 'relation "users"' in message
|
||||
|
||||
class WeComLoginError(AppError):
|
||||
def __init__(self, error: str, error_code: str, status_code: int, reason: str = None, extra: dict = None):
|
||||
details = dict(extra or {})
|
||||
if reason:
|
||||
details['reason'] = reason
|
||||
super().__init__(code=error_code, message=error, http_status=status_code, details=details)
|
||||
self.error = error
|
||||
self.error_code = error_code
|
||||
self.status_code = status_code
|
||||
self.reason = reason
|
||||
self.extra = extra or {}
|
||||
|
||||
def _write_login_audit(source: str, status: str, user: User=None, username: str=None, reason: str=None, wecom_userid: str=None, error_code: str=None, match_rules: list=None, match_operator: str=None, match_result: str=None):
|
||||
payload = {'user_id': user.id if user else None, 'username': username or (user.username if user else None), 'source': source, 'status': status, 'reason': reason, 'error_code': error_code, 'match_rules': ','.join(match_rules) if isinstance(match_rules, list) else match_rules, 'match_operator': match_operator, 'match_result': match_result, 'wecom_userid': wecom_userid, 'ip': request.headers.get('X-Forwarded-For', request.remote_addr), 'user_agent': (request.user_agent.string or '')[:255], 'created_at': datetime.utcnow()}
|
||||
try:
|
||||
supported_columns = _get_login_audit_supported_columns()
|
||||
if not supported_columns:
|
||||
return
|
||||
filtered_payload = {key: value for key, value in payload.items() if key in supported_columns}
|
||||
if not filtered_payload:
|
||||
return
|
||||
_execute_login_audit_insert(filtered_payload)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _get_login_audit_supported_columns():
|
||||
global _LOGIN_AUDIT_COLUMNS_CACHE
|
||||
if _LOGIN_AUDIT_COLUMNS_CACHE is not None:
|
||||
return _LOGIN_AUDIT_COLUMNS_CACHE
|
||||
try:
|
||||
columns = {column['name'] for column in inspect(db.engine).get_columns(LoginAudit.__tablename__)}
|
||||
except Exception:
|
||||
columns = set()
|
||||
_LOGIN_AUDIT_COLUMNS_CACHE = columns
|
||||
return columns
|
||||
|
||||
def _execute_login_audit_insert(payload: dict):
|
||||
nested = db.session.begin_nested()
|
||||
try:
|
||||
db.session.execute(insert(LoginAudit.__table__).values(**payload))
|
||||
db.session.flush()
|
||||
nested.commit()
|
||||
except Exception:
|
||||
nested.rollback()
|
||||
raise
|
||||
|
||||
def _get_current_user():
|
||||
"""
|
||||
Resolve current authenticated user for API handlers.
|
||||
|
||||
Behavior:
|
||||
1) Prefer JWT Bearer token validation (Casdoor JWKS).
|
||||
2) Optional legacy header fallback depends on AUTH_LEGACY_HEADER_ENABLED.
|
||||
3) Returns None when authentication cannot be established.
|
||||
"""
|
||||
return _auth_current_user()
|
||||
|
||||
def _run_db_with_retry(operation, *, label: str):
|
||||
try:
|
||||
return operation()
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('%s failed on first attempt: %s', label, exc)
|
||||
db.session.rollback()
|
||||
db.session.remove()
|
||||
try:
|
||||
db.engine.dispose()
|
||||
except Exception as dispose_exc:
|
||||
current_app.logger.warning('%s dispose engine failed: %s', label, dispose_exc)
|
||||
return operation()
|
||||
|
||||
def _get_wecom_config_missing_fields() -> list[str]:
|
||||
return _wecom_svc.get_config_missing_fields()
|
||||
|
||||
|
||||
def _is_wecom_configured() -> bool:
|
||||
return _wecom_svc.is_configured()
|
||||
|
||||
def _issue_casdoor_state(redirect_uri: str):
|
||||
"""兼容旧调用点:签发格式不变的 Casdoor state。"""
|
||||
return _casdoor_route_adapter.issue_casdoor_state(redirect_uri)
|
||||
|
||||
def _consume_casdoor_state(state: str):
|
||||
"""兼容旧调用点:校验 Casdoor state 并恢复签名绑定的 redirect_uri。"""
|
||||
return _casdoor_route_adapter.consume_casdoor_state(state)
|
||||
|
||||
def _get_casdoor_oidc_metadata():
|
||||
"""兼容旧调用点:委托公共 CasdoorClient 获取 discovery 文档。"""
|
||||
return _casdoor_route_adapter.get_oidc_metadata()
|
||||
|
||||
|
||||
def _build_casdoor_authorize_payload(options: CasdoorAuthorizeOptions) -> dict[str, str]:
|
||||
"""兼容入口:使用旧 discovery/state 替换点构造 Casdoor 授权响应。"""
|
||||
return _casdoor_route_adapter.build_authorize_payload(
|
||||
options,
|
||||
oidc_metadata=_get_casdoor_oidc_metadata,
|
||||
issue_state=_issue_casdoor_state,
|
||||
)
|
||||
|
||||
def _resolve_user_from_casdoor_claims(claims: dict):
|
||||
"""兼容旧调用点:通过公共身份对象映射 HXOPS 用户。"""
|
||||
from app.services.auth.casdoor.identity import identity_from_claims
|
||||
from app.services.auth.common import IdentityValidationError
|
||||
from app.services.auth.hxops.user_resolver import HxopsIdentityMappingError, resolve_hxops_user
|
||||
|
||||
try:
|
||||
identity = identity_from_claims(
|
||||
claims,
|
||||
expected_issuer=str(current_app.config.get('AUTH_JWT_ISSUER') or ''),
|
||||
)
|
||||
return resolve_hxops_user(identity)
|
||||
except IdentityValidationError as exc:
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_IDENTITY_INVALID',
|
||||
message='Casdoor identity is missing issuer or subject',
|
||||
http_status=401,
|
||||
) from exc
|
||||
except HxopsIdentityMappingError as exc:
|
||||
raise WeComLoginError(error=str(exc), error_code=exc.code, status_code=exc.status) from exc
|
||||
|
||||
|
||||
def _issue_casdoor_api_token(user: User, claims: dict) -> str:
|
||||
"""
|
||||
为已通过 Casdoor 认证的用户签发 HXOPS API 会话 JWT。
|
||||
|
||||
Args:
|
||||
user: 已映射成功的 HXOPS 本地用户。
|
||||
claims: Casdoor ID token 或 userinfo 返回的可信身份声明。
|
||||
|
||||
Returns:
|
||||
HXOPS 本地签名 JWT,其中保留 Casdoor issuer/subject 供跨系统 SSO 使用。
|
||||
|
||||
Raises:
|
||||
AppError: Casdoor 未返回稳定 subject,不能建立可复用身份。
|
||||
"""
|
||||
from app.services.auth.casdoor.identity import identity_from_claims
|
||||
from app.services.auth.common import IdentityValidationError
|
||||
from app.services.auth.hxops.session_token import issue_hxops_access_token
|
||||
|
||||
try:
|
||||
identity = identity_from_claims(
|
||||
claims,
|
||||
expected_issuer=str(current_app.config.get('AUTH_JWT_ISSUER') or claims.get('iss') or ''),
|
||||
)
|
||||
except IdentityValidationError as exc:
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_IDENTITY_INVALID',
|
||||
message='Casdoor identity is missing issuer or subject',
|
||||
http_status=401,
|
||||
) from exc
|
||||
return issue_hxops_access_token(user, identity)
|
||||
|
||||
def _casdoor_exchange_code(code: str, redirect_uri: str):
|
||||
"""兼容旧测试替换点:委托公共客户端执行 authorization code grant。"""
|
||||
return _casdoor_route_adapter.authorization_code_login(code, redirect_uri)
|
||||
|
||||
def _casdoor_refresh_token(refresh_token: str):
|
||||
"""兼容旧测试替换点:委托公共客户端执行 refresh grant。"""
|
||||
return _casdoor_route_adapter.refresh_token(refresh_token)
|
||||
|
||||
def _casdoor_userinfo(access_token: str):
|
||||
"""兼容旧测试替换点:委托公共客户端读取 userinfo。"""
|
||||
return _casdoor_route_adapter.userinfo(access_token)
|
||||
|
||||
def _casdoor_password_login(username: str, password: str):
|
||||
"""
|
||||
Resource-owner password login against Casdoor token endpoint.
|
||||
Requires the Casdoor application to enable password grant.
|
||||
"""
|
||||
return _casdoor_route_adapter.password_login(username, password)
|
||||
|
||||
|
||||
def _hxops_login_service() -> HxopsLoginService:
|
||||
"""创建使用当前兼容代理的登录服务,使既有 monkeypatch 测试和调用方式保持有效。"""
|
||||
return _casdoor_route_adapter.create_login_service(
|
||||
write_login_audit=_write_login_audit,
|
||||
password_operation=_casdoor_password_login,
|
||||
code_operation=_casdoor_exchange_code,
|
||||
refresh_operation=_casdoor_refresh_token,
|
||||
userinfo_operation=_casdoor_userinfo,
|
||||
)
|
||||
|
||||
def _is_casdoor_login_mode() -> bool:
|
||||
return (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() == 'casdoor'
|
||||
|
||||
def _is_casdoor_configured() -> bool:
|
||||
return _casdoor_svc.is_casdoor_configured()
|
||||
|
||||
def _casdoor_user_owner() -> str:
|
||||
return _casdoor_svc.casdoor_user_owner()
|
||||
|
||||
def _verify_casdoor_password(username: str, password: str):
|
||||
_casdoor_password_login(username, password)
|
||||
|
||||
def _casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str):
|
||||
return _casdoor_svc.casdoor_set_password(user_owner, user_name, old_password, new_password)
|
||||
|
||||
def _is_casdoor_user_exists_error(message: str) -> bool:
|
||||
return _casdoor_svc.is_user_exists_error(message)
|
||||
|
||||
def _raise_casdoor_add_user_error(source) -> None:
|
||||
_casdoor_svc.raise_add_user_error(source)
|
||||
|
||||
def _casdoor_add_user(user_payload: dict):
|
||||
return _casdoor_svc.casdoor_add_user(user_payload)
|
||||
|
||||
def _sync_casdoor_create_user(*, username: str, password: str, email: str, employee_id: str | None = None, real_name=None, phone_number=None, status='active', department=None):
|
||||
"""兼容入口:同步创建 Casdoor 用户,并传递认证主映射工号。"""
|
||||
return _casdoor_svc.sync_create_user(username=username, password=password, employee_id=employee_id, email=email, real_name=real_name, phone_number=phone_number, status=status, department=department)
|
||||
|
||||
def _raise_casdoor_update_user_error(source) -> None:
|
||||
_casdoor_svc.raise_update_user_error(source)
|
||||
|
||||
def _casdoor_update_user(user_payload: dict):
|
||||
return _casdoor_svc.casdoor_update_user(user_payload)
|
||||
|
||||
def _sync_casdoor_admin_set_password(user: User, new_password: str):
|
||||
return _casdoor_svc.sync_admin_set_password(user, new_password)
|
||||
|
||||
def _sync_casdoor_update_user(user: User, *, new_password: str | None = None):
|
||||
return _casdoor_svc.sync_update_user(user, new_password=new_password)
|
||||
|
||||
def _is_casdoor_password_error(message: str) -> bool:
|
||||
return _casdoor_svc.is_password_error(message)
|
||||
|
||||
def _is_casdoor_user_missing_error(message: str) -> bool:
|
||||
return _casdoor_svc.is_user_missing_error(message)
|
||||
|
||||
def _raise_casdoor_user_not_in_idp(source=None) -> None:
|
||||
_casdoor_svc.raise_user_not_in_idp(source)
|
||||
|
||||
def _extract_casdoor_error_payload(source) -> dict:
|
||||
return _casdoor_svc.extract_error_payload(source)
|
||||
|
||||
def _raise_casdoor_auth_error(source, *, context: str, status_code: int = 401) -> None:
|
||||
_casdoor_svc.raise_auth_error(source, context=context, status_code=status_code)
|
||||
|
||||
def _raise_casdoor_set_password_error(source) -> None:
|
||||
_casdoor_svc.raise_set_password_error(source)
|
||||
|
||||
def _raise_incorrect_current_password():
|
||||
raise AppError(
|
||||
code='AUTH.INCORRECT_CURRENT_PASSWORD',
|
||||
message='Incorrect current password',
|
||||
http_status=403,
|
||||
)
|
||||
|
||||
def _verify_current_password_for_change(user, current_password: str):
|
||||
if user.check_password(current_password):
|
||||
return
|
||||
if not _is_casdoor_configured():
|
||||
_raise_incorrect_current_password()
|
||||
try:
|
||||
_verify_casdoor_password(user.username, current_password)
|
||||
except AppError as e:
|
||||
if e.code == 'CASDOOR_INVALID_CREDENTIALS':
|
||||
_raise_incorrect_current_password()
|
||||
raise
|
||||
except RuntimeError as e:
|
||||
if _is_casdoor_password_error(str(e)):
|
||||
_raise_incorrect_current_password()
|
||||
raise
|
||||
|
||||
def _sync_casdoor_password(username: str, current_password: str, new_password: str):
|
||||
if not _is_casdoor_configured():
|
||||
return
|
||||
user_owner = _casdoor_user_owner()
|
||||
try:
|
||||
_casdoor_set_password(user_owner, username, current_password, new_password)
|
||||
except AppError as first_error:
|
||||
if first_error.code in ('CASDOOR_INVALID_CREDENTIALS', 'AUTH.INCORRECT_CURRENT_PASSWORD'):
|
||||
_raise_incorrect_current_password()
|
||||
raise
|
||||
except RuntimeError as first_error:
|
||||
if _is_casdoor_user_missing_error(str(first_error)):
|
||||
_raise_casdoor_user_not_in_idp(first_error)
|
||||
if _is_casdoor_password_error(str(first_error)):
|
||||
_raise_incorrect_current_password()
|
||||
try:
|
||||
_casdoor_set_password(user_owner, username, '', new_password)
|
||||
except RuntimeError:
|
||||
raise first_error
|
||||
|
||||
def _cleanup_wecom_state_cache():
|
||||
now = datetime.utcnow()
|
||||
expired = [k for k, v in _WECOM_STATE_CACHE.items() if not v or v < now]
|
||||
for k in expired:
|
||||
_WECOM_STATE_CACHE.pop(k, None)
|
||||
|
||||
def _issue_wecom_state():
|
||||
_cleanup_wecom_state_cache()
|
||||
state = f'hxops_wecom_{uuid.uuid4().hex}'
|
||||
_WECOM_STATE_CACHE[state] = datetime.utcnow() + timedelta(minutes=10)
|
||||
return state
|
||||
|
||||
def _consume_wecom_state(state: str):
|
||||
if not state:
|
||||
return False
|
||||
_cleanup_wecom_state_cache()
|
||||
exp = _WECOM_STATE_CACHE.pop(state, None)
|
||||
return bool(exp and exp > datetime.utcnow())
|
||||
|
||||
def _cleanup_wecom_bind_session_cache():
|
||||
now = datetime.utcnow()
|
||||
expired = [key for key, item in _WECOM_BIND_SESSION_CACHE.items() if not isinstance(item, dict) or not item.get('expires_at') or item['expires_at'] < now]
|
||||
for key in expired:
|
||||
_WECOM_BIND_SESSION_CACHE.pop(key, None)
|
||||
|
||||
def _issue_wecom_bind_session(identity: dict):
|
||||
_cleanup_wecom_bind_session_cache()
|
||||
token = f'hxops_wecom_bind_{uuid.uuid4().hex}'
|
||||
_WECOM_BIND_SESSION_CACHE[token] = {'expires_at': datetime.utcnow() + timedelta(minutes=10), 'identity': dict(identity or {})}
|
||||
return token
|
||||
|
||||
def _get_wecom_bind_session(token: str):
|
||||
if not token:
|
||||
return None
|
||||
_cleanup_wecom_bind_session_cache()
|
||||
item = _WECOM_BIND_SESSION_CACHE.get(token)
|
||||
if not isinstance(item, dict):
|
||||
return None
|
||||
expires_at = item.get('expires_at')
|
||||
if not expires_at or expires_at < datetime.utcnow():
|
||||
_WECOM_BIND_SESSION_CACHE.pop(token, None)
|
||||
return None
|
||||
identity = item.get('identity')
|
||||
return identity if isinstance(identity, dict) else None
|
||||
|
||||
def _consume_wecom_bind_session(token: str):
|
||||
identity = _get_wecom_bind_session(token)
|
||||
if identity is None:
|
||||
return None
|
||||
_WECOM_BIND_SESSION_CACHE.pop(token, None)
|
||||
return identity
|
||||
|
||||
def _parse_wecom_field_list(raw_value, default_fields: list[str]):
|
||||
return _wecom_svc.parse_field_list(raw_value, default_fields)
|
||||
|
||||
def _verify_wecom_msg_signature(msg_signature: str, token: str, timestamp: str, nonce: str, encrypt: str) -> bool:
|
||||
if not msg_signature or not token or (not encrypt):
|
||||
return False
|
||||
expected = sha1_hex([token, str(timestamp or ''), str(nonce or ''), encrypt])
|
||||
return expected == msg_signature
|
||||
|
||||
def _extract_xml_field(xml_text: str, tag: str):
|
||||
if not xml_text:
|
||||
return None
|
||||
m = re.search(f'<{tag}><!\\[CDATA\\[(.*?)\\]\\]></{tag}>', xml_text, re.DOTALL)
|
||||
if m:
|
||||
return m.group(1).strip()
|
||||
m2 = re.search(f'<{tag}>(.*?)</{tag}>', xml_text, re.DOTALL)
|
||||
if m2:
|
||||
return m2.group(1).strip()
|
||||
return None
|
||||
|
||||
def _persist_wecom_callback_audit(*, msg_signature, timestamp, nonce, encrypt_raw, decrypted_xml=None, msg_type=None, event=None, from_user=None, agent_id=None, msg_id=None, error_message=None):
|
||||
try:
|
||||
row = WecomCallbackAudit(msg_signature=msg_signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_raw, decrypted_xml=decrypted_xml, msg_type=msg_type, event=event, from_user=from_user, agent_id=agent_id, msg_id=msg_id, error_message=error_message)
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
|
||||
def _get_wecom_access_token():
|
||||
return _wecom_svc.get_access_token()
|
||||
|
||||
def _build_login_payload(user: User, source: str='password', bind_status: str=None):
|
||||
payload = {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'role': user.role,
|
||||
'default_agent_id': user.default_agent_id,
|
||||
'feature_permissions': user.get_feature_permissions(),
|
||||
'source': source,
|
||||
'access_token': issue_local_access_token(user),
|
||||
'token_type': 'Bearer',
|
||||
}
|
||||
if bind_status:
|
||||
payload['bind_status'] = bind_status
|
||||
return payload
|
||||
|
||||
def _clean_str(value):
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, str):
|
||||
value = value.strip()
|
||||
return value or None
|
||||
return str(value).strip() or None
|
||||
|
||||
def _parse_leave_int_flag(value, field_label: str):
|
||||
if value in (0, 1):
|
||||
return int(value)
|
||||
text = _clean_str(value)
|
||||
if text in ('0', '1'):
|
||||
return int(text)
|
||||
raise OALeaveWorkflowError(f'{field_label} 取值无效,应为 0 或 1。')
|
||||
|
||||
def _normalize_mobile(mobile: str):
|
||||
mobile = _clean_str(mobile)
|
||||
if not mobile:
|
||||
return None
|
||||
digits = re.sub('\\D', '', mobile)
|
||||
if not digits:
|
||||
return mobile
|
||||
if digits.startswith('0086'):
|
||||
digits = digits[4:]
|
||||
elif digits.startswith('86') and len(digits) > 11:
|
||||
digits = digits[2:]
|
||||
return digits
|
||||
|
||||
def _extract_wecom_extattr_value(wecom_user: dict, key: str):
|
||||
extattr = wecom_user.get('extattr') or {}
|
||||
attrs = extattr.get('attrs') if isinstance(extattr, dict) else None
|
||||
if not isinstance(attrs, list):
|
||||
return None
|
||||
for attr in attrs:
|
||||
if not isinstance(attr, dict):
|
||||
continue
|
||||
if _clean_str(attr.get('name')) != key:
|
||||
continue
|
||||
raw = attr.get('value')
|
||||
if isinstance(raw, dict):
|
||||
raw = raw.get('text') or raw.get('web') or raw.get('value')
|
||||
return _clean_str(raw)
|
||||
return None
|
||||
|
||||
def _get_wecom_match_config():
|
||||
return _wecom_svc.get_match_config()
|
||||
|
||||
def _get_wecom_first_login_bind_mode():
|
||||
return _wecom_svc.get_first_login_bind_mode()
|
||||
|
||||
def _get_wecom_first_login_input_fields():
|
||||
return _wecom_svc.get_first_login_input_fields()
|
||||
|
||||
def _extract_wecom_identity(wecom_user: dict):
|
||||
return _wecom_svc.extract_identity(wecom_user)
|
||||
|
||||
def _mobile_candidates(identity: dict):
|
||||
values = []
|
||||
for item in [identity.get('mobile'), identity.get('mobile_raw')]:
|
||||
item = _clean_str(item)
|
||||
if item and item not in values:
|
||||
values.append(item)
|
||||
return values
|
||||
|
||||
def _find_users_by_input_field(field: str, value):
|
||||
field = _clean_str(field)
|
||||
if field not in _ALLOWED_WECOM_MATCH_FIELDS:
|
||||
return ([], 'invalid_field')
|
||||
if field == 'employee_id':
|
||||
needle = _clean_str(value)
|
||||
if not needle:
|
||||
return ([], 'employee_id')
|
||||
return (db.session.query(User).filter(User.employee_id == needle).all(), None)
|
||||
if field == 'email':
|
||||
needle = _clean_str(value)
|
||||
if not needle:
|
||||
return ([], 'email')
|
||||
return (db.session.query(User).filter(User.email == needle).all(), None)
|
||||
if field == 'mobile':
|
||||
raw_mobile = _clean_str(value)
|
||||
normalized_mobile = _normalize_mobile(raw_mobile)
|
||||
candidates = []
|
||||
for item in [normalized_mobile, raw_mobile]:
|
||||
item = _clean_str(item)
|
||||
if item and item not in candidates:
|
||||
candidates.append(item)
|
||||
if not candidates:
|
||||
return ([], 'mobile')
|
||||
return (db.session.query(User).filter(User.phone_number.in_(candidates)).all(), None)
|
||||
return ([], 'invalid_field')
|
||||
|
||||
def _find_users_by_match_rules(identity: dict, rules: list, operator: str):
|
||||
return _wecom_svc.find_users_by_match_rules(identity, rules, operator)
|
||||
|
||||
def _assert_wecom_binding_not_occupied(user: User, identity: dict):
|
||||
wecom_userid = identity.get('wecom_userid')
|
||||
wecom_unionid = identity.get('wecom_unionid')
|
||||
if wecom_userid:
|
||||
dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first()
|
||||
if dup:
|
||||
raise WeComLoginError(error=f'Current WeCom account has been bound to user: {dup.username}', error_code='WECOM_BIND_CONFLICT', status_code=409, reason='bind_conflict')
|
||||
if wecom_unionid:
|
||||
dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first()
|
||||
if dup_union:
|
||||
raise WeComLoginError(error=f'Current WeCom unionid has been bound to user: {dup_union.username}', error_code='WECOM_BIND_CONFLICT', status_code=409, reason='bind_conflict')
|
||||
|
||||
def _sync_user_from_wecom_identity(user: User, identity: dict):
|
||||
_assert_wecom_binding_not_occupied(user, identity)
|
||||
if identity.get('wecom_userid'):
|
||||
user.wecom_userid = identity['wecom_userid']
|
||||
if identity.get('wecom_unionid') and (not user.wecom_unionid):
|
||||
user.wecom_unionid = identity['wecom_unionid']
|
||||
if identity.get('name') and (not user.real_name):
|
||||
user.real_name = identity['name']
|
||||
if identity.get('email') and (not user.email):
|
||||
dup_email = db.session.query(User).filter(User.email == identity['email'], User.id != user.id).first()
|
||||
if not dup_email:
|
||||
user.email = identity['email']
|
||||
if identity.get('mobile') and (not user.phone_number):
|
||||
candidates = _mobile_candidates(identity)
|
||||
dup_mobile = db.session.query(User).filter(User.phone_number.in_(candidates), User.id != user.id).first()
|
||||
if not dup_mobile:
|
||||
user.phone_number = identity['mobile']
|
||||
if identity.get('employee_id') and (not user.employee_id):
|
||||
dup_employee = db.session.query(User).filter(User.employee_id == identity['employee_id'], User.id != user.id).first()
|
||||
if not dup_employee:
|
||||
user.employee_id = identity['employee_id']
|
||||
|
||||
def _create_user_from_wecom_identity(identity: dict) -> User:
|
||||
base_username = (identity.get('wecom_userid') or identity.get('email') or identity.get('mobile') or f'wecom_{uuid.uuid4().hex[:8]}').replace('@', '_')
|
||||
candidate = base_username
|
||||
suffix = 1
|
||||
while db.session.query(User).filter_by(username=candidate).first():
|
||||
candidate = f'{base_username}_{suffix}'
|
||||
suffix += 1
|
||||
safe_email = identity.get('email') or f'{candidate}@wecom.local'
|
||||
if db.session.query(User).filter_by(email=safe_email).first():
|
||||
safe_email = f'{candidate}_{uuid.uuid4().hex[:6]}@wecom.local'
|
||||
employee_id = identity.get('employee_id')
|
||||
if employee_id and db.session.query(User).filter_by(employee_id=employee_id).first():
|
||||
employee_id = None
|
||||
phone_number = identity.get('mobile')
|
||||
if phone_number:
|
||||
candidates = _mobile_candidates(identity)
|
||||
dup_mobile = db.session.query(User).filter(User.phone_number.in_(candidates)).first()
|
||||
if dup_mobile:
|
||||
phone_number = None
|
||||
user = User(username=candidate, email=safe_email, role='user', status='active', real_name=identity.get('name'), employee_id=employee_id, phone_number=phone_number, wecom_userid=identity.get('wecom_userid'), wecom_unionid=identity.get('wecom_unionid'))
|
||||
user.set_password(uuid.uuid4().hex)
|
||||
db.session.add(user)
|
||||
return user
|
||||
|
||||
def _issue_wecom_input_bind_prompt(identity: dict):
|
||||
allowed_fields = _get_wecom_first_login_input_fields()
|
||||
binding_token = _issue_wecom_bind_session(identity)
|
||||
raise WeComLoginError(error='First WeCom login requires verification input to bind a local account.', error_code='WECOM_BIND_INPUT_REQUIRED', status_code=409, reason='input_bind_required', extra={'binding_token': binding_token, 'allowed_fields': allowed_fields, 'wecom_name': identity.get('name'), 'wecom_userid': identity.get('wecom_userid')})
|
||||
|
||||
def _sync_or_create_user_from_wecom(wecom_user: dict):
|
||||
identity = _extract_wecom_identity(wecom_user)
|
||||
rules, operator = _get_wecom_match_config()
|
||||
rule_info = {'operator': operator, 'fields': rules}
|
||||
bind_mode = _get_wecom_first_login_bind_mode()
|
||||
user = None
|
||||
if identity.get('wecom_userid'):
|
||||
user = db.session.query(User).filter_by(wecom_userid=identity['wecom_userid']).first()
|
||||
if user:
|
||||
_sync_user_from_wecom_identity(user, identity)
|
||||
return (user, 'already_bound', rule_info)
|
||||
if bind_mode == 'input_verify':
|
||||
_issue_wecom_input_bind_prompt(identity)
|
||||
matched_users, missing_fields = _find_users_by_match_rules(identity, rules, operator)
|
||||
if missing_fields:
|
||||
missing_field = missing_fields[0]
|
||||
raise WeComLoginError(error=f'Required match attribute missing: {missing_field}', error_code='WECOM_MATCH_ATTR_MISSING', status_code=422, reason=f'missing_attr:{missing_field}', extra={'missing_field': missing_field, 'match_rules': rule_info})
|
||||
if len(matched_users) == 1:
|
||||
user = matched_users[0]
|
||||
_sync_user_from_wecom_identity(user, identity)
|
||||
return (user, 'matched_and_bound', rule_info)
|
||||
if len(matched_users) > 1:
|
||||
raise WeComLoginError(error='Multiple local users matched', error_code='WECOM_MATCH_AMBIGUOUS', status_code=409, reason='ambiguous_match', extra={'candidate_count': len(matched_users), 'match_rules': rule_info})
|
||||
if not current_app.config.get('WECOM_AUTO_CREATE_USER', True):
|
||||
raise WeComLoginError(error='No linked account found. Contact admin to bind WeCom account.', error_code='WECOM_BIND_REQUIRED', status_code=403, reason='bind_required', extra={'match_rules': rule_info})
|
||||
user = _create_user_from_wecom_identity(identity)
|
||||
return (user, 'auto_created', rule_info)
|
||||
@@ -0,0 +1,196 @@
|
||||
"""
|
||||
api/user/auth_wecom.py
|
||||
|
||||
用途:企业微信 OAuth、绑定与回调 HTTP 路由。
|
||||
依赖:auth.auth_bp、auth_support 的企微签名、身份匹配和审计操作。
|
||||
逻辑:将企微认证入口同本地/Casdoor 路由隔离,保持企业微信回调 URL 不变。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from urllib.parse import quote
|
||||
|
||||
import requests
|
||||
from flask import current_app, jsonify, request
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError, ForbiddenError, UnauthorizedError, ValidationError
|
||||
from app.services.wecom_crypto import decrypt_wecom_aes, extract_encrypt_field
|
||||
|
||||
from . import auth as _compat
|
||||
from .auth import auth_bp
|
||||
|
||||
|
||||
@auth_bp.get('/wecom/authorize-url', endpoint='wecom_authorize_url')
|
||||
def authorize_url():
|
||||
"""生成企业微信 OAuth 授权地址。"""
|
||||
if not _compat._is_wecom_configured():
|
||||
raise ValidationError('WeCom login is not configured')
|
||||
redirect_uri = request.args.get('redirect_uri') or current_app.config.get('WECOM_REDIRECT_URI')
|
||||
if not redirect_uri:
|
||||
raise ValidationError('redirect_uri is required')
|
||||
state = _compat._issue_wecom_state()
|
||||
corp_id = current_app.config.get('WECOM_CORP_ID')
|
||||
agent_id = current_app.config.get('WECOM_AGENT_ID')
|
||||
url = f"https://open.weixin.qq.com/connect/oauth2/authorize?appid={corp_id}&redirect_uri={quote(redirect_uri, safe='')}&response_type=code&scope=snsapi_base&state={quote(state, safe='')}&agentid={agent_id}#wechat_redirect"
|
||||
return jsonify({'url': url, 'state': state})
|
||||
|
||||
|
||||
@auth_bp.post('/wecom/login', endpoint='wecom_login')
|
||||
def login():
|
||||
"""完成企业微信 OAuth 登录并映射或绑定本地用户。"""
|
||||
if not _compat._is_wecom_configured():
|
||||
raise ValidationError('WeCom login is not configured')
|
||||
data = request.get_json() or {}
|
||||
code, state = data.get('code'), data.get('state')
|
||||
if not code:
|
||||
_compat._write_login_audit('wecom', 'failed', reason='missing_code')
|
||||
db.session.commit()
|
||||
raise ValidationError('code is required')
|
||||
if not _compat._consume_wecom_state(state):
|
||||
_compat._write_login_audit('wecom', 'failed', reason='invalid_state')
|
||||
db.session.commit()
|
||||
raise ValidationError('Invalid or expired WeCom state')
|
||||
wecom_userid = None
|
||||
try:
|
||||
access_token = _compat._get_wecom_access_token()
|
||||
info = requests.get('https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo', params={'access_token': access_token, 'code': code}, timeout=8).json()
|
||||
wecom_userid = info.get('userid') or info.get('UserId')
|
||||
if info.get('errcode') != 0:
|
||||
raise UnauthorizedError(f"WeCom auth failed: {info.get('errmsg', 'unknown error')}")
|
||||
if not wecom_userid:
|
||||
raise AppError(code='WECOM_NOT_IN_AGENT_SCOPE', message='当前企业微信账号未授权登录该应用:账号不在自建应用的可见范围内,或不是本企业成员。请管理员到「企业微信后台 → 应用管理 → 该应用 → 可见范围」中加入该成员所在的部门或个人。', http_status=401)
|
||||
wecom_user = requests.get('https://qyapi.weixin.qq.com/cgi-bin/user/get', params={'access_token': access_token, 'userid': wecom_userid}, timeout=8).json()
|
||||
if wecom_user.get('errcode') != 0:
|
||||
raise UnauthorizedError(f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}")
|
||||
user, bind_status, rule_info = _compat._sync_or_create_user_from_wecom(wecom_user)
|
||||
if user.status != 'active':
|
||||
raise ForbiddenError('Account is disabled')
|
||||
_compat._write_login_audit('wecom', 'success', user=user, wecom_userid=wecom_userid, match_rules=rule_info.get('fields'), match_operator=rule_info.get('operator'), match_result=bind_status)
|
||||
db.session.commit()
|
||||
return jsonify(_compat._build_login_payload(user, 'wecom', bind_status=bind_status))
|
||||
except _compat.WeComLoginError as exc:
|
||||
db.session.rollback()
|
||||
_compat._write_login_audit('wecom', 'failed', reason=exc.reason or 'wecom_login_error', wecom_userid=wecom_userid, error_code=exc.error_code)
|
||||
db.session.commit()
|
||||
raise
|
||||
except AppError as exc:
|
||||
db.session.rollback()
|
||||
_compat._write_login_audit('wecom', 'failed', reason=str(exc)[:160], wecom_userid=wecom_userid, error_code=exc.code)
|
||||
db.session.commit()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
if _compat._is_users_pk_sequence_error(exc):
|
||||
_compat._write_login_audit('wecom', 'failed', reason='db_sequence_misconfig', wecom_userid=wecom_userid, error_code='DB_SEQUENCE_MISCONFIG')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.DB_SEQUENCE_MISCONFIG', message='数据库主键自增配置异常,当前环境缺少 users.id 的自动序列。请执行数据库迁移后重试。', http_status=500) from exc
|
||||
_compat._write_login_audit('wecom', 'failed', reason=f'exception:{str(exc)[:160]}', wecom_userid=wecom_userid)
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'WeCom login failed: {exc}', http_status=500) from exc
|
||||
|
||||
|
||||
@auth_bp.post('/wecom/complete-bind', endpoint='wecom_complete_bind')
|
||||
def complete_bind():
|
||||
"""提交首登人工绑定信息并完成企业微信账号绑定。"""
|
||||
if not _compat._is_wecom_configured():
|
||||
raise ValidationError('WeCom login is not configured')
|
||||
data = request.get_json() or {}
|
||||
token, field, value = _compat._clean_str(data.get('binding_token')), _compat._clean_str(data.get('field')), data.get('value')
|
||||
identity = _compat._get_wecom_bind_session(token)
|
||||
if not identity:
|
||||
raise AppError(code='WECOM_BIND_SESSION_EXPIRED', message='WeCom binding session expired. Please restart WeCom login.', http_status=400)
|
||||
allowed_fields = _compat._get_wecom_first_login_input_fields()
|
||||
if field not in allowed_fields:
|
||||
raise AppError(code='WECOM_BIND_FIELD_NOT_ALLOWED', message='Selected bind field is not allowed', http_status=400, details={'allowed_fields': allowed_fields})
|
||||
matched_users, missing_field = _compat._find_users_by_input_field(field, value)
|
||||
if missing_field:
|
||||
raise AppError(code='WECOM_BIND_INPUT_VALUE_REQUIRED', message=f'{field} is required', http_status=400, details={'field': field})
|
||||
if not matched_users:
|
||||
raise AppError(code='WECOM_BIND_INPUT_NOT_FOUND', message='No local account matched the verification value.', http_status=404, details={'field': field})
|
||||
if len(matched_users) > 1:
|
||||
raise ConflictError('Multiple local accounts matched the verification value.', code='WECOM_BIND_INPUT_AMBIGUOUS', details={'field': field, 'candidate_count': len(matched_users)})
|
||||
user = matched_users[0]
|
||||
if user.status != 'active':
|
||||
raise ForbiddenError('Account is disabled')
|
||||
try:
|
||||
_compat._sync_user_from_wecom_identity(user, identity)
|
||||
_compat._write_login_audit('wecom', 'success', user=user, wecom_userid=identity.get('wecom_userid'), match_rules=[field], match_operator='AND', match_result='input_verified_and_bound')
|
||||
db.session.commit()
|
||||
_compat._WECOM_BIND_SESSION_CACHE.pop(token, None)
|
||||
return jsonify(_compat._build_login_payload(user, 'wecom', bind_status='input_verified_and_bound'))
|
||||
except _compat.WeComLoginError as exc:
|
||||
db.session.rollback()
|
||||
_compat._write_login_audit('wecom', 'failed', user=user, reason=exc.reason or 'wecom_input_bind_error', wecom_userid=identity.get('wecom_userid'), error_code=exc.error_code, match_rules=[field], match_operator='AND')
|
||||
db.session.commit()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
_compat._write_login_audit('wecom', 'failed', user=user, reason=f'exception:{str(exc)[:160]}', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_BIND_INPUT_EXCEPTION', match_rules=[field], match_operator='AND')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'WeCom bind failed: {exc}', http_status=500) from exc
|
||||
|
||||
|
||||
@auth_bp.route('/wecom/callback', methods=['GET', 'POST'], endpoint='wecom_callback')
|
||||
def callback():
|
||||
"""处理企业微信 URL 验证及加密事件回调。"""
|
||||
signature = request.args.get('msg_signature') or request.args.get('signature')
|
||||
timestamp, nonce = request.args.get('timestamp', ''), request.args.get('nonce', '')
|
||||
token = current_app.config.get('WECOM_CALLBACK_TOKEN') or ''
|
||||
aes_key, corp_id = current_app.config.get('WECOM_ENCODING_AES_KEY') or '', current_app.config.get('WECOM_CORP_ID') or ''
|
||||
if not token:
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='callback token not configured', http_status=500)
|
||||
if request.method == 'GET':
|
||||
echostr = request.args.get('echostr', '') or ''
|
||||
if not _compat._verify_wecom_msg_signature(signature, token, timestamp, nonce, echostr):
|
||||
raise ForbiddenError('invalid callback signature')
|
||||
try:
|
||||
plain = decrypt_wecom_aes(echostr, aes_key, corp_id) if aes_key else echostr
|
||||
except Exception as exc:
|
||||
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=echostr, error_message=f'decrypt_failed:{str(exc)[:200]}')
|
||||
raise ValidationError('decrypt failed') from exc
|
||||
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=echostr, decrypted_xml=plain, msg_type='url_verify' if aes_key else 'url_verify_plain')
|
||||
return plain, 200, {'Content-Type': 'text/plain; charset=utf-8'}
|
||||
payload = request.get_data(as_text=True) or ''
|
||||
encrypt_field = extract_encrypt_field(payload) or ''
|
||||
if not encrypt_field:
|
||||
raise ValidationError('missing Encrypt field')
|
||||
if not _compat._verify_wecom_msg_signature(signature, token, timestamp, nonce, encrypt_field):
|
||||
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_field, error_message='invalid_msg_signature')
|
||||
raise ForbiddenError('invalid callback signature')
|
||||
decrypted = None
|
||||
if aes_key:
|
||||
try:
|
||||
decrypted = decrypt_wecom_aes(encrypt_field, aes_key, corp_id)
|
||||
except Exception as exc:
|
||||
_compat._persist_wecom_callback_audit(msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_field, error_message=f'decrypt_failed:{str(exc)[:200]}')
|
||||
raise ValidationError('decrypt failed') from exc
|
||||
_compat._persist_wecom_callback_audit(
|
||||
msg_signature=signature, timestamp=timestamp, nonce=nonce, encrypt_raw=encrypt_field,
|
||||
decrypted_xml=decrypted, msg_type=_compat._extract_xml_field(decrypted, 'MsgType') if decrypted else None,
|
||||
event=_compat._extract_xml_field(decrypted, 'Event') if decrypted else None,
|
||||
from_user=_compat._extract_xml_field(decrypted, 'FromUserName') if decrypted else None,
|
||||
agent_id=_compat._extract_xml_field(decrypted, 'AgentID') if decrypted else None,
|
||||
msg_id=_compat._extract_xml_field(decrypted, 'MsgId') if decrypted else None,
|
||||
)
|
||||
return 'success', 200, {'Content-Type': 'text/plain; charset=utf-8'}
|
||||
|
||||
|
||||
@auth_bp.get('/wecom/binding', endpoint='get_wecom_binding')
|
||||
def binding():
|
||||
"""返回当前用户的企业微信绑定状态。"""
|
||||
user = _compat._get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
return jsonify({'bound': bool(user.wecom_userid), 'wecom_userid': user.wecom_userid, 'wecom_unionid': user.wecom_unionid})
|
||||
|
||||
|
||||
@auth_bp.post('/wecom/unbind', endpoint='unbind_wecom_self')
|
||||
def unbind():
|
||||
"""解除当前用户与企业微信账号的绑定。"""
|
||||
user = _compat._get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
user.wecom_userid = None
|
||||
user.wecom_unionid = None
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok', 'message': 'WeCom account unbound'})
|
||||
@@ -0,0 +1,380 @@
|
||||
"""
|
||||
backend/app/api/user/handlers.py
|
||||
|
||||
用途:当前用户域 API(Casdoor 登录、企微 OAuth、首页、FAQ、反馈等)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、models、wecom/dify 相关 services。
|
||||
逻辑:薄路由层鉴权与参数校验;Casdoor/企微 OAuth 委托 services/auth/*。
|
||||
"""
|
||||
from flask import Blueprint, request, jsonify, current_app
|
||||
from app import db
|
||||
from app.models import User, Agent, QuickQuestion, UserFavoriteAgent, UserDefaultAgent, UserHomepageConfig, GeneralFeedback, ChatLog
|
||||
from app.services.feedback_notify import send_feedback_group_notification
|
||||
from app.services.agent_category import serialize_agent_list_item, sort_agent_rows
|
||||
from app.services.agent_registry.serialization import serialize_registry_fields
|
||||
from app.services.wecom_notify import mark_wecom_message_opened, send_wecom_event_message
|
||||
import re
|
||||
import ast
|
||||
from app.core.errors import (
|
||||
AppError,
|
||||
ForbiddenError,
|
||||
NotFoundError,
|
||||
UnauthorizedError,
|
||||
ValidationError,
|
||||
)
|
||||
from .auth import (
|
||||
_clean_str,
|
||||
_get_current_user,
|
||||
_parse_leave_int_flag,
|
||||
_run_db_with_retry,
|
||||
)
|
||||
user_bp = Blueprint('user', __name__)
|
||||
|
||||
@user_bp.route('/wecom/deeplink-opened', methods=['POST'])
|
||||
def mark_wecom_deeplink_opened():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
trace_id = _clean_str(data.get('trace_id'))
|
||||
if not trace_id:
|
||||
raise ValidationError('trace_id is required')
|
||||
ok = mark_wecom_message_opened(trace_id)
|
||||
if not ok:
|
||||
raise NotFoundError('trace_id not found')
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/wecom/task-complete', methods=['POST'])
|
||||
def wecom_task_complete():
|
||||
"""
|
||||
Lightweight endpoint for sending task completion WeCom message.
|
||||
Can be called by frontend after long-running task is done.
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
title = _clean_str(data.get('title')) or 'AI 任务已完成'
|
||||
content = _clean_str(data.get('content')) or '你发起的 AI 任务已完成,点击查看详情。'
|
||||
agent_id = data.get('agent_id')
|
||||
jump_path = '/workspace'
|
||||
jump_params = {}
|
||||
if agent_id:
|
||||
jump_path = f'/chat/{int(agent_id)}'
|
||||
result = send_wecom_event_message(event_type='task_completed', user=user, title=title, content=content, jump_path=jump_path, jump_params=jump_params)
|
||||
db.session.commit()
|
||||
return (jsonify(result), 200 if result.get('ok') else 202)
|
||||
|
||||
@user_bp.route('/leave-balance', methods=['GET'])
|
||||
def get_leave_balance():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
leave_type_code = _clean_str(request.args.get('leave_type'))
|
||||
if leave_type_code not in ('010', '408'):
|
||||
raise ValidationError('仅支持查询年假(010)和育儿假(408)的余额')
|
||||
try:
|
||||
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
|
||||
employee_code = HRLeaveSQLServerService._get_employee_code(user)
|
||||
now_year = datetime.now().year
|
||||
if leave_type_code == '010':
|
||||
_, record = HRLeaveSQLServerService._query_one(view_name='VIEW_D044', year_column='D044001', total_column='D044005', used_column='D044006', remaining_column='D044007', employee_code=employee_code, year=now_year)
|
||||
label = '年假'
|
||||
else:
|
||||
_, record = HRLeaveSQLServerService._query_one(view_name='VIEW_D072', year_column='d072001', total_column='d072002', used_column='d072003', remaining_column='d072004', employee_code=employee_code, year=now_year)
|
||||
label = '育儿假'
|
||||
remaining = record.get('remaining_hours') if record else None
|
||||
try:
|
||||
has_balance = remaining is not None and float(remaining) > 0
|
||||
except (TypeError, ValueError):
|
||||
has_balance = False
|
||||
return jsonify({'leave_type_code': leave_type_code, 'leave_type_label': label, 'year': record.get('leave_year', now_year) if record else now_year, 'total_hours': record.get('total_hours') if record else None, 'used_hours': record.get('used_hours') if record else None, 'remaining_hours': remaining, 'has_balance': has_balance})
|
||||
except Exception as exc:
|
||||
current_app.logger.exception('[leave-balance] query failed user_id=%s', getattr(user, 'id', None))
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'假期余额查询失败:{exc}', http_status=500)
|
||||
|
||||
@user_bp.route('/leave-workflow/submit', methods=['POST'])
|
||||
def submit_leave_workflow():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
form_data = {'applicantName': _clean_str(data.get('applicantName')) or _clean_str(getattr(user, 'real_name', None)) or _clean_str(getattr(user, 'username', None)), 'employeeId': _clean_str(data.get('employeeId')) or _clean_str(getattr(user, 'employee_id', None)) or _clean_str(getattr(user, 'username', None)), 'applicantJobTitle': _clean_str(data.get('applicantJobTitle')), 'applicantDepartmentId': _clean_str(data.get('applicantDepartmentId')), 'applicantSubCompanyId1': _clean_str(data.get('applicantSubCompanyId1')), 'applyTime': _clean_str(data.get('applyTime')), 'fillerName': _clean_str(data.get('fillerName')) or _clean_str(getattr(user, 'real_name', None)) or _clean_str(getattr(user, 'username', None)), 'agentUid': _clean_str(data.get('agentUid')), 'agentEmployeeId': _clean_str(data.get('agentEmployeeId')), 'agentName': _clean_str(data.get('agentName')), 'agentJobTitle': _clean_str(data.get('agentJobTitle')), 'agentDepartmentId': _clean_str(data.get('agentDepartmentId')), 'agentSubCompanyId1': _clean_str(data.get('agentSubCompanyId1')), 'leaveType': _clean_str(data.get('leaveType')), 'startTime': _clean_str(data.get('startTime')), 'endTime': _clean_str(data.get('endTime')), 'durationHours': data.get('durationHours'), 'isOutOfOffice': _parse_leave_int_flag(data.get('isOutOfOffice'), '是否外出'), 'isWorkInjury': _parse_leave_int_flag(data.get('isWorkInjury'), '是否为工伤'), 'remark': _clean_str(data.get('remark')) or ''}
|
||||
required_fields = {'applicantName': '请假人', 'employeeId': '工号', 'fillerName': '填单人', 'agentUid': '代理人UID', 'agentEmployeeId': '代理人工号', 'agentName': '代理人姓名', 'leaveType': '假别', 'startTime': '开始时间', 'endTime': '结束时间'}
|
||||
for key, label in required_fields.items():
|
||||
if not form_data.get(key):
|
||||
raise ValidationError(f'{label}不能为空。')
|
||||
try:
|
||||
from app.services.oa_leave_workflow import OALeaveWorkflowService, OALeaveWorkflowError
|
||||
result = OALeaveWorkflowService.submit_leave_request(form_data, user)
|
||||
except OALeaveWorkflowError as exc:
|
||||
current_app.logger.warning('[oa-leave] submit failed user_id=%s employee_id=%s err=%s', getattr(user, 'id', None), form_data.get('employeeId'), exc)
|
||||
raise ValidationError(str(exc))
|
||||
except Exception as exc:
|
||||
current_app.logger.exception('[oa-leave] unexpected submit failure user_id=%s', getattr(user, 'id', None))
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'OA 请假提交失败:{exc}', http_status=500)
|
||||
current_app.logger.info('[oa-leave] submit success user_id=%s employee_id=%s request_id=%s workflow_id=%s', getattr(user, 'id', None), form_data.get('employeeId'), result.get('request_id'), result.get('workflow_id'))
|
||||
return jsonify(result)
|
||||
|
||||
@user_bp.route('/feedback', methods=['POST'])
|
||||
def submit_general_feedback():
|
||||
"""
|
||||
通用意见反馈接口(与 /api/chat/feedback 的对话评分接口不同
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
feedback_type = _clean_str(data.get('feedback_type'))
|
||||
feedback_module = _clean_str(data.get('feedback_module'))
|
||||
content = _clean_str(data.get('content'))
|
||||
source_page = _clean_str(data.get('source_page'))
|
||||
raw_chat_log_id = data.get('chat_log_id')
|
||||
chat_log_id = None
|
||||
if raw_chat_log_id not in (None, ''):
|
||||
try:
|
||||
chat_log_id = int(raw_chat_log_id)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError('chat_log_id must be an integer')
|
||||
if chat_log_id <= 0:
|
||||
raise ValidationError('chat_log_id must be a positive integer')
|
||||
if not feedback_type:
|
||||
raise ValidationError('feedback_type is required')
|
||||
if not feedback_module:
|
||||
raise ValidationError('feedback_module is required')
|
||||
if len(feedback_type) > 32:
|
||||
raise ValidationError('feedback_type is too long')
|
||||
if len(feedback_module) > 32:
|
||||
raise ValidationError('feedback_module is too long')
|
||||
if not content:
|
||||
raise ValidationError('content is required')
|
||||
if len(content) > 2000:
|
||||
raise ValidationError('content is too long')
|
||||
if source_page != 'chat':
|
||||
chat_log_id = None
|
||||
if chat_log_id is not None:
|
||||
chat_log = db.session.get(ChatLog, chat_log_id)
|
||||
if not chat_log:
|
||||
raise ValidationError('chat_log_id not found')
|
||||
if chat_log.user_id != user.id:
|
||||
raise ForbiddenError('chat_log_id is not owned by current user')
|
||||
row = GeneralFeedback(user_id=user.id, username=user.username, feedback_type=feedback_type, feedback_module=feedback_module, content=content, source_page=source_page, chat_log_id=chat_log_id)
|
||||
db.session.add(row)
|
||||
db.session.commit()
|
||||
notify_result = send_feedback_group_notification(row, user)
|
||||
if notify_result.get('ok'):
|
||||
current_app.logger.info('[feedback] group notification sent feedback_id=%s', row.id)
|
||||
elif not notify_result.get('skipped'):
|
||||
current_app.logger.warning(
|
||||
'[feedback] group notification failed feedback_id=%s reason=%s',
|
||||
row.id,
|
||||
notify_result.get('reason'),
|
||||
)
|
||||
return jsonify({'status': 'ok', 'id': row.id})
|
||||
|
||||
@user_bp.route('/home', methods=['GET'])
|
||||
def home():
|
||||
"""
|
||||
Get user homepage data
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
|
||||
def _load_home_payload():
|
||||
if user.role == 'admin':
|
||||
agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all()
|
||||
else:
|
||||
agent_rows = [agent for agent in user.agents if agent.is_active]
|
||||
agent_rows = sort_agent_rows(agent_rows)
|
||||
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
|
||||
favorite_ids = [f.agent_id for f in favorites]
|
||||
qqs = db.session.query(QuickQuestion).filter(
|
||||
or_(
|
||||
QuickQuestion.user_id == user.id,
|
||||
and_(QuickQuestion.user_id.is_(None), QuickQuestion.is_enabled.is_(True)),
|
||||
)
|
||||
).all()
|
||||
layout_config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||||
layout = layout_config.layout if layout_config else {}
|
||||
embedded_rel = db.session.query(UserDefaultAgent).filter_by(user_id=user.id).order_by(UserDefaultAgent.sort_order).all()
|
||||
embedded_agents = []
|
||||
for rel in embedded_rel:
|
||||
agent = db.session.get(Agent, rel.agent_id)
|
||||
if agent:
|
||||
registry = serialize_registry_fields(agent)
|
||||
embedded_agents.append({
|
||||
'id': agent.id,
|
||||
'name': agent.name,
|
||||
'iframe_url': registry.get('iframe_url'),
|
||||
'runtime_provider': registry.get('runtime_provider'),
|
||||
'conversation_mode': registry.get('conversation_mode'),
|
||||
})
|
||||
return jsonify({'user': {'id': user.id, 'username': user.username, 'role': user.role, 'default_agent_id': user.default_agent_id, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'}, 'agents': [serialize_agent_list_item(a) for a in agent_rows], 'favorite_agent_ids': favorite_ids, 'quick_questions': [{'id': q.id, 'title': q.title, 'question': q.question, 'agent_id': q.agent_id} for q in qqs], 'embedded_agents': embedded_agents, 'layout': layout})
|
||||
try:
|
||||
return _run_db_with_retry(_load_home_payload, label='user.home')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
current_app.logger.warning('user.home retry failed: %s', exc)
|
||||
raise ServiceUnavailableError('Database connection failed')
|
||||
|
||||
@user_bp.route('/favorites/<int:agent_id>', methods=['POST', 'DELETE'])
|
||||
def toggle_favorite(agent_id: int):
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if request.method == 'POST':
|
||||
exists = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).first()
|
||||
if not exists:
|
||||
fav = UserFavoriteAgent(user_id=user.id, agent_id=agent_id)
|
||||
db.session.add(fav)
|
||||
else:
|
||||
db.session.query(UserFavoriteAgent).filter_by(user_id=user.id, agent_id=agent_id).delete()
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/quick-questions', methods=['POST'])
|
||||
def add_quick_question():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
if not data.get('title') or not data.get('question') or (not data.get('agent_id')):
|
||||
raise ValidationError('Missing fields')
|
||||
qq = QuickQuestion(user_id=user.id, title=data['title'], question=data['question'], agent_id=data['agent_id'])
|
||||
db.session.add(qq)
|
||||
db.session.commit()
|
||||
return (jsonify({'message': 'Added', 'id': qq.id}), 201)
|
||||
|
||||
@user_bp.route('/quick-questions/<int:qq_id>', methods=['PUT', 'DELETE'])
|
||||
def update_quick_question(qq_id: int):
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
qq = db.session.query(QuickQuestion).filter_by(id=qq_id, user_id=user.id).first()
|
||||
if not qq:
|
||||
raise NotFoundError('QuickQuestion not found or permission denied')
|
||||
if request.method == 'DELETE':
|
||||
db.session.delete(qq)
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
data = request.get_json() or {}
|
||||
if 'title' in data:
|
||||
qq.title = data['title']
|
||||
if 'question' in data:
|
||||
qq.question = data['question']
|
||||
if 'agent_id' in data:
|
||||
qq.agent_id = data['agent_id']
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/homepage-layout', methods=['PUT'])
|
||||
def update_layout():
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
data = request.get_json() or {}
|
||||
layout = data.get('layout', {})
|
||||
config = db.session.query(UserHomepageConfig).filter_by(user_id=user.id).first()
|
||||
if not config:
|
||||
config = UserHomepageConfig(user_id=user.id, layout=layout)
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.layout = layout
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
@user_bp.route('/profile', methods=['GET', 'PUT'])
|
||||
def user_profile():
|
||||
"""
|
||||
User profile management
|
||||
GET: Get details
|
||||
PUT: Update basic info
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
if request.method == 'GET':
|
||||
return jsonify({'id': user.id, 'username': user.username, 'real_name': user.real_name, 'email': user.email, 'phone_number': user.phone_number, 'employee_id': user.employee_id, 'department': user.department, 'role': user.role, 'feature_permissions': user.get_feature_permissions(), 'language': user.language, 'theme_preference': user.theme_preference or 'system'})
|
||||
data = request.get_json() or {}
|
||||
|
||||
def _update_profile():
|
||||
if 'real_name' in data:
|
||||
user.real_name = data['real_name']
|
||||
if 'phone_number' in data:
|
||||
user.phone_number = data['phone_number']
|
||||
if 'language' in data:
|
||||
user.language = data['language']
|
||||
if 'theme_preference' in data:
|
||||
if data['theme_preference'] not in ['light', 'dark', 'system']:
|
||||
raise ValidationError('Invalid theme preference')
|
||||
user.theme_preference = data['theme_preference']
|
||||
if 'email' in data:
|
||||
if data['email']:
|
||||
existing = db.session.query(User).filter_by(email=data['email']).first()
|
||||
if existing and existing.id != user.id:
|
||||
raise ValidationError('Email already exists')
|
||||
user.email = data['email']
|
||||
if 'employee_id' in data:
|
||||
if data['employee_id']:
|
||||
existing = db.session.query(User).filter_by(employee_id=data['employee_id']).first()
|
||||
if existing and existing.id != user.id:
|
||||
raise ValidationError('Employee ID already exists')
|
||||
user.employee_id = data['employee_id']
|
||||
if 'department' in data:
|
||||
user.department = data['department']
|
||||
db.session.commit()
|
||||
return jsonify({'message': 'Profile updated successfully'})
|
||||
try:
|
||||
return _run_db_with_retry(_update_profile, label='user.profile.update')
|
||||
except (OperationalError, DatabaseError) as exc:
|
||||
db.session.rollback()
|
||||
current_app.logger.warning('user.profile.update retry failed: %s', exc)
|
||||
raise ServiceUnavailableError('Database connection failed')
|
||||
except Exception as e:
|
||||
db.session.rollback()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
|
||||
|
||||
@user_bp.route('/agents/<int:id>', methods=['GET'])
|
||||
def get_agent_details(id):
|
||||
"""
|
||||
Get agent details with permission check
|
||||
"""
|
||||
user = _get_current_user()
|
||||
if not user:
|
||||
raise UnauthorizedError('Unauthorized')
|
||||
agent = db.session.get(Agent, id)
|
||||
if not agent:
|
||||
raise NotFoundError('Not found')
|
||||
if user.role != 'admin':
|
||||
has_permission = agent in user.agents
|
||||
if not has_permission:
|
||||
raise ForbiddenError('Access denied')
|
||||
|
||||
from app.services.agent_registry.resolver import resolve_runtime_provider
|
||||
from app.services.agent_registry.serialization import serialize_agent_for_user_detail
|
||||
|
||||
dify_parameters = None
|
||||
if resolve_runtime_provider(agent) in {'dify', 'hybrid'} and getattr(agent, 'dify_api_key', None):
|
||||
from app.services.dify import DifyService
|
||||
|
||||
try:
|
||||
params = DifyService.get_app_parameters(agent)
|
||||
if isinstance(params, dict):
|
||||
dify_parameters = {
|
||||
'file_upload': params.get('file_upload') if isinstance(params.get('file_upload'), dict) else {},
|
||||
'system_parameters': params.get('system_parameters') if isinstance(params.get('system_parameters'), dict) else {},
|
||||
}
|
||||
except Exception as exc:
|
||||
current_app.logger.warning('[user.agents] dify parameters fetch failed agent_id=%s err=%s', id, exc)
|
||||
|
||||
return jsonify(serialize_agent_for_user_detail(
|
||||
agent,
|
||||
dify_parameters=dify_parameters,
|
||||
))
|
||||
|
||||
@user_bp.route('/db', methods=['GET'])
|
||||
def get_db():
|
||||
from app.models import User
|
||||
from app import db
|
||||
u = db.session.query(User).filter_by(username='26040006').first()
|
||||
return jsonify({'db': current_app.config.get('SQLALCHEMY_DATABASE_URI'), 'user': u.username if u else None})
|
||||
@@ -1,3 +1,11 @@
|
||||
"""
|
||||
services/text2sql.py
|
||||
|
||||
Purpose: Translate natural-language ERP asset queries into safe Oracle SQL and format results.
|
||||
Dependencies: Oracle client, LLM client, and docs/integrations/erp/text2sql_schema.md.
|
||||
Flow: The chat fast route calls this service; this service loads the ERP schema to build SQL prompts.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -424,17 +432,26 @@ class Text2SQLService:
|
||||
|
||||
@classmethod
|
||||
def get_schema(cls):
|
||||
"""
|
||||
Load the ERP schema document used as context for Text2SQL generation.
|
||||
|
||||
The environment override is checked first, followed by the packaged and source-tree
|
||||
locations, so the same schema is available in containers and local development.
|
||||
|
||||
Returns:
|
||||
str: UTF-8 schema text, or a diagnostic string when no schema document is available.
|
||||
"""
|
||||
if cls._schema_text is None:
|
||||
schema_filename = '(表+字段).md'
|
||||
schema_relative_path = os.path.join('integrations', 'erp', 'text2sql_schema.md')
|
||||
env_path = (os.getenv("TEXT2SQL_SCHEMA_PATH") or "").strip()
|
||||
candidate_paths = []
|
||||
if env_path:
|
||||
candidate_paths.append(env_path)
|
||||
|
||||
candidate_paths.extend([
|
||||
os.path.join(cls._backend_dir(), 'docs', schema_filename),
|
||||
os.path.join(cls._project_root(), 'docs', schema_filename),
|
||||
os.path.join(os.getcwd(), 'docs', schema_filename),
|
||||
os.path.join(cls._backend_dir(), 'docs', schema_relative_path),
|
||||
os.path.join(cls._project_root(), 'docs', schema_relative_path),
|
||||
os.path.join(os.getcwd(), 'docs', schema_relative_path),
|
||||
])
|
||||
|
||||
unique_paths = []
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
from app import create_app, db
|
||||
from app.models import ChatLog, User
|
||||
from sqlalchemy import func
|
||||
|
||||
app = create_app('development')
|
||||
with app.app_context():
|
||||
print('=== 数据库中的用户 ===')
|
||||
users = db.session.query(User).all()
|
||||
for u in users:
|
||||
print(f'id={u.id}, username={u.username}, role={u.role}')
|
||||
|
||||
print()
|
||||
print('=== 各用户对 Agent 3 的会话统计 ===')
|
||||
for uid in [1, 2, 3, 4, 5]:
|
||||
count = db.session.query(func.count(ChatLog.id)).filter(
|
||||
ChatLog.user_id == uid,
|
||||
ChatLog.agent_id == 3
|
||||
).scalar()
|
||||
print(f'user_id={uid}: {count} logs')
|
||||
|
||||
print()
|
||||
print('=== ChatLog 样本 (Agent 3) ===')
|
||||
logs = db.session.query(ChatLog).filter(ChatLog.agent_id == 3).order_by(ChatLog.created_at.desc()).limit(5).all()
|
||||
for log in logs:
|
||||
print(f'user_id={log.user_id}, conv_id={log.conversation_id}, query={log.query[:40]}...')
|
||||
@@ -1,15 +0,0 @@
|
||||
from app import create_app, db
|
||||
from app.models import Agent, User
|
||||
|
||||
app = create_app('development')
|
||||
|
||||
with app.app_context():
|
||||
agents = Agent.query.all()
|
||||
print("--- Agents ---")
|
||||
for a in agents:
|
||||
print(f"ID: {a.id}, Name: {a.name}, Key: {a.dify_api_key}, URL: {a.api_base_url}")
|
||||
|
||||
users = User.query.all()
|
||||
print("\n--- Users ---")
|
||||
for u in users:
|
||||
print(f"ID: {u.id}, Username: {u.username}, Role: {u.role}")
|
||||
@@ -1,9 +0,0 @@
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import User
|
||||
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
users = User.query.all()
|
||||
for u in users:
|
||||
print(f"ID: {u.id}, User: {u.username}, Role: {u.role}")
|
||||
@@ -1,16 +0,0 @@
|
||||
import urllib.request
|
||||
import zipfile
|
||||
import os
|
||||
import sys
|
||||
|
||||
url = "https://download.oracle.com/otn_software/nt/instantclient/1924000/instantclient-basiclite-windows.x64-19.24.0.0.0dbru.zip"
|
||||
zip_path = "instantclient.zip"
|
||||
extract_dir = "oracle_client"
|
||||
|
||||
print("Downloading...")
|
||||
urllib.request.urlretrieve(url, zip_path)
|
||||
print("Downloaded. Extracting...")
|
||||
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
||||
zip_ref.extractall(extract_dir)
|
||||
print("Done. Content:")
|
||||
print(os.listdir(extract_dir))
|
||||
@@ -1,129 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
fix_agent_permission.py
|
||||
文件用途:修复 Agent 权限问题
|
||||
关键逻辑:
|
||||
1. 根据 username 或 user_id 获取用户
|
||||
2. 给用户分配指定的 agent 权限
|
||||
3. 支持批量分配和查看当前权限
|
||||
语法实现:使用 SQLAlchemy relationship 操作多对多关联
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import User, Agent
|
||||
|
||||
|
||||
def grant_agent_permission(username=None, user_id=None, agent_ids=None, grant_all=False):
|
||||
"""
|
||||
给用户分配 Agent 权限
|
||||
|
||||
参数:
|
||||
username: 用户名
|
||||
user_id: 用户 ID
|
||||
agent_ids: 要分配的 Agent ID 列表,如 [1, 2, 3]
|
||||
grant_all: 是否授予所有 Agent 的权限
|
||||
"""
|
||||
env = os.getenv('FLASK_ENV', 'production')
|
||||
app = create_app(env)
|
||||
|
||||
with app.app_context():
|
||||
user = None
|
||||
if user_id:
|
||||
user = User.query.get(int(user_id))
|
||||
elif username:
|
||||
user = User.query.filter_by(username=username).first()
|
||||
|
||||
if not user:
|
||||
print(f"❌ 用户不存在: username={username}, user_id={user_id}")
|
||||
return False
|
||||
|
||||
print(f"✅ 找到用户: {user.username} (ID: {user.id}, Role: {user.role})")
|
||||
|
||||
if grant_all:
|
||||
agents = Agent.query.all()
|
||||
agent_ids = [a.id for a in agents]
|
||||
print(f"📋 所有可用 Agent: {agent_ids}")
|
||||
|
||||
if not agent_ids:
|
||||
print("⚠️ 未指定 agent_ids,使用 --grant-all 授予所有权限")
|
||||
agents = Agent.query.all()
|
||||
user.agents = agents
|
||||
else:
|
||||
agents = Agent.query.filter(Agent.id.in_(agent_ids)).all()
|
||||
if not agents:
|
||||
print(f"❌ 未找到 ID 为 {agent_ids} 的 Agent")
|
||||
return False
|
||||
user.agents = agents
|
||||
|
||||
db.session.commit()
|
||||
print(f"✅ 权限授予成功!用户 {user.username} 现在可以访问 Agent: {[a.id for a in user.agents]}")
|
||||
return True
|
||||
|
||||
|
||||
def list_user_permissions(username=None, user_id=None):
|
||||
"""查看用户的 Agent 权限"""
|
||||
env = os.getenv('FLASK_ENV', 'production')
|
||||
app = create_app(env)
|
||||
|
||||
with app.app_context():
|
||||
user = None
|
||||
if user_id:
|
||||
user = User.query.get(int(user_id))
|
||||
elif username:
|
||||
user = User.query.filter_by(username=username).first()
|
||||
|
||||
if not user:
|
||||
print(f"❌ 用户不存在: username={username}, user_id={user_id}")
|
||||
return
|
||||
|
||||
print(f"\n👤 用户: {user.username} (ID: {user.id}, Role: {user.role})")
|
||||
print(f"📋 当前可访问的 Agent: {[a.id for a in user.agents]}")
|
||||
print("\n📋 所有 Agent 列表:")
|
||||
all_agents = Agent.query.all()
|
||||
for a in all_agents:
|
||||
has_access = a in user.agents
|
||||
print(f" [{a.id}] {a.name} - {'✅ 有权限' if has_access else '❌ 无权限'}")
|
||||
|
||||
|
||||
def list_all_users():
|
||||
"""列出所有用户及其权限"""
|
||||
env = os.getenv('FLASK_ENV', 'production')
|
||||
app = create_app(env)
|
||||
|
||||
with app.app_context():
|
||||
users = User.query.all()
|
||||
print("\n👥 所有用户列表:")
|
||||
for u in users:
|
||||
print(f" [{u.id}] {u.username} (Role: {u.role}) - Agents: {[a.id for a in u.agents]}")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description='修复 Agent 权限')
|
||||
parser.add_argument('--username', '-u', type=str, help='用户名')
|
||||
parser.add_argument('--user-id', '-i', type=int, help='用户 ID')
|
||||
parser.add_argument('--agent-ids', '-a', type=int, nargs='+', help='Agent ID 列表,如: 1 2 3')
|
||||
parser.add_argument('--grant-all', '-g', action='store_true', help='授予所有 Agent 权限')
|
||||
parser.add_argument('--list', '-l', action='store_true', help='查看用户权限')
|
||||
parser.add_argument('--list-users', action='store_true', help='列出所有用户')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.list_users:
|
||||
list_all_users()
|
||||
elif args.list:
|
||||
list_user_permissions(username=args.username, user_id=args.user_id)
|
||||
elif args.grant_all or args.agent_ids:
|
||||
grant_agent_permission(
|
||||
username=args.username,
|
||||
user_id=args.user_id,
|
||||
agent_ids=args.agent_ids,
|
||||
grant_all=args.grant_all
|
||||
)
|
||||
else:
|
||||
parser.print_help()
|
||||
@@ -1,70 +0,0 @@
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import Agent
|
||||
import uuid
|
||||
|
||||
app = create_app()
|
||||
|
||||
with app.app_context():
|
||||
# 1. 方式一:嵌入到网站中 (Iframe)
|
||||
# <iframe src=" http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg " style="width: 100%; height: 100%; min-height: 700px" frameborder="0" allow="microphone"> </iframe>
|
||||
|
||||
agent_iframe = Agent.query.filter_by(name='人事规章(网页版)').first()
|
||||
iframe_url = 'http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg'
|
||||
if not agent_iframe:
|
||||
agent_iframe = Agent(
|
||||
name='人事规章(网页版)',
|
||||
description='嵌入式人事规章助手',
|
||||
dify_app_id=str(uuid.uuid4()),
|
||||
dify_api_key='placeholder',
|
||||
type='iframe',
|
||||
extra_config={'iframe_url': iframe_url},
|
||||
icon_url='ri-article-line',
|
||||
agent_code='generic',
|
||||
runtime_provider='iframe',
|
||||
conversation_mode='embedded',
|
||||
iframe_url=iframe_url,
|
||||
)
|
||||
db.session.add(agent_iframe)
|
||||
print('Added Iframe Agent')
|
||||
else:
|
||||
agent_iframe.type = 'iframe'
|
||||
agent_iframe.extra_config = {'iframe_url': iframe_url}
|
||||
agent_iframe.icon_url = 'ri-article-line'
|
||||
agent_iframe.agent_code = 'generic'
|
||||
agent_iframe.runtime_provider = 'iframe'
|
||||
agent_iframe.conversation_mode = 'embedded'
|
||||
agent_iframe.iframe_url = iframe_url
|
||||
print('Updated Iframe Agent')
|
||||
|
||||
# 2. 方式二:API
|
||||
# 基础URL: http://127.0.0.1:5001/v1
|
||||
# API密钥:app-xdiejQibWQy8ZQWXcdxJjS9I
|
||||
|
||||
agent_api = Agent.query.filter_by(name='人事规章(API版)').first()
|
||||
if not agent_api:
|
||||
agent_api = Agent(
|
||||
name='人事规章(API版)',
|
||||
description='API调用人事规章助手',
|
||||
dify_app_id=str(uuid.uuid4()),
|
||||
dify_api_key='app-xdiejQibWQy8ZQWXcdxJjS9I',
|
||||
type='api',
|
||||
api_base_url='http://127.0.0.1:5001/v1',
|
||||
icon_url='ri-robot-line',
|
||||
agent_code='generic',
|
||||
runtime_provider='dify',
|
||||
conversation_mode='chat',
|
||||
)
|
||||
db.session.add(agent_api)
|
||||
print('Added API Agent')
|
||||
else:
|
||||
agent_api.type = 'api'
|
||||
agent_api.dify_api_key = 'app-xdiejQibWQy8ZQWXcdxJjS9I'
|
||||
agent_api.api_base_url = 'http://127.0.0.1:5001/v1'
|
||||
agent_api.icon_url = 'ri-robot-line'
|
||||
agent_api.agent_code = 'generic'
|
||||
agent_api.runtime_provider = 'dify'
|
||||
agent_api.conversation_mode = 'chat'
|
||||
print('Updated API Agent')
|
||||
|
||||
db.session.commit()
|
||||
@@ -1,35 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
密码重置脚本
|
||||
用途:用于重置用户密码,特别是在用户忘记密码时
|
||||
使用方法:python3 reset_password.py <username> <new_password>
|
||||
"""
|
||||
import sys
|
||||
from app import create_app, db
|
||||
from app.models import User
|
||||
|
||||
if len(sys.argv) != 3:
|
||||
print("Usage: python3 reset_password.py <username> <new_password>")
|
||||
print("Example: python3 reset_password.py admin Hxit@54321")
|
||||
sys.exit(1)
|
||||
|
||||
username = sys.argv[1]
|
||||
new_password = sys.argv[2]
|
||||
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
# 查找用户
|
||||
user = User.query.filter_by(username=username).first()
|
||||
if user:
|
||||
print(f"Found user: {user.username}, Role: {user.role}")
|
||||
# 设置新密码
|
||||
user.set_password(new_password)
|
||||
db.session.commit()
|
||||
print(f"✅ SUCCESS: Password reset for user '{username}' to '{new_password}'")
|
||||
else:
|
||||
print(f"❌ FAILURE: User '{username}' not found")
|
||||
# 列出所有可用用户
|
||||
print("\nAvailable users:")
|
||||
users = User.query.all()
|
||||
for u in users:
|
||||
print(f" - {u.username} (Role: {u.role})")
|
||||
@@ -1,24 +0,0 @@
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import ZlLanguage
|
||||
|
||||
app = create_app('development')
|
||||
|
||||
with app.app_context():
|
||||
languages = [
|
||||
{'code': 'zh-CN', 'name': '简体中文'},
|
||||
{'code': 'zh-TW', 'name': '繁體中文'},
|
||||
{'code': 'en', 'name': 'English'},
|
||||
{'code': 'th', 'name': 'ไทย'},
|
||||
]
|
||||
|
||||
for lang in languages:
|
||||
exists = ZlLanguage.query.filter_by(code=lang['code']).first()
|
||||
if not exists:
|
||||
print(f"Adding language: {lang['name']}")
|
||||
db.session.add(ZlLanguage(code=lang['code'], name=lang['name'], is_active=True))
|
||||
else:
|
||||
print(f"Language exists: {lang['name']}")
|
||||
|
||||
db.session.commit()
|
||||
print("Done seeding languages.")
|
||||
@@ -1,76 +0,0 @@
|
||||
import os
|
||||
import sys
|
||||
import redis
|
||||
from app import create_app, db
|
||||
from app.models import User, ZlLanguage, Agent
|
||||
|
||||
def seed_production():
|
||||
"""
|
||||
Production Seeding Script
|
||||
1. Initialize Languages
|
||||
2. Create Admin User
|
||||
3. Verify Redis
|
||||
"""
|
||||
env = os.getenv('FLASK_ENV', 'production')
|
||||
print(f"Starting seeding for environment: {env}")
|
||||
app = create_app(env)
|
||||
|
||||
with app.app_context():
|
||||
# 1. Seed Languages
|
||||
languages = [
|
||||
{'code': 'zh-CN', 'name': '简体中文'},
|
||||
{'code': 'zh-TW', 'name': '繁體中文'},
|
||||
{'code': 'en', 'name': 'English'},
|
||||
{'code': 'th', 'name': 'ไทย'},
|
||||
]
|
||||
print("Seeding languages...")
|
||||
for lang in languages:
|
||||
exists = ZlLanguage.query.filter_by(code=lang['code']).first()
|
||||
if not exists:
|
||||
print(f" + Adding language: {lang['name']}")
|
||||
db.session.add(ZlLanguage(code=lang['code'], name=lang['name'], is_active=True))
|
||||
else:
|
||||
print(f" . Language exists: {lang['name']}")
|
||||
|
||||
# 2. Create Admin User
|
||||
admin_username = 'admin'
|
||||
admin_email = 'admin@example.com'
|
||||
admin_password = 'admin' # Default initial password, should be changed
|
||||
|
||||
print(f"Checking admin user '{admin_username}'...")
|
||||
user = User.query.filter_by(username=admin_username).first()
|
||||
if not user:
|
||||
print(f" + Creating admin user: {admin_username} / {admin_password}")
|
||||
user = User(
|
||||
username=admin_username,
|
||||
email=admin_email,
|
||||
role='admin',
|
||||
real_name='Administrator',
|
||||
status='active'
|
||||
)
|
||||
user.set_password(admin_password)
|
||||
db.session.add(user)
|
||||
else:
|
||||
print(f" . Admin user already exists. Updating password to default 'admin' if needed.")
|
||||
# Ensure the password is reset to a known state for initial deployment
|
||||
# user.set_password(admin_password)
|
||||
# db.session.add(user)
|
||||
|
||||
db.session.commit()
|
||||
print("Database seeding completed.")
|
||||
|
||||
# 3. Verify Redis
|
||||
print("Verifying Redis connection...")
|
||||
redis_url = app.config.get('REDIS_URL')
|
||||
if redis_url:
|
||||
try:
|
||||
r = redis.from_url(redis_url)
|
||||
r.ping()
|
||||
print("✅ Redis connection successful.")
|
||||
except Exception as e:
|
||||
print(f"❌ Redis connection failed: {e}")
|
||||
else:
|
||||
print("⚠️ No REDIS_URL configured.")
|
||||
|
||||
if __name__ == '__main__':
|
||||
seed_production()
|
||||
@@ -1,24 +0,0 @@
|
||||
from app import create_app, db
|
||||
from app.models import User
|
||||
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
# 测试 admin 用户登录
|
||||
admin = User.query.filter_by(username='admin').first()
|
||||
if admin:
|
||||
print(f"Testing admin user login...")
|
||||
# 测试新密码
|
||||
password = 'Hxit@54321'
|
||||
if admin.check_password(password):
|
||||
print(f"✅ SUCCESS: Admin user can login with password '{password}'")
|
||||
else:
|
||||
print(f"❌ FAILURE: Admin user cannot login with password '{password}'")
|
||||
|
||||
# 测试错误密码
|
||||
wrong_password = 'wrongpassword'
|
||||
if not admin.check_password(wrong_password):
|
||||
print(f"✅ SUCCESS: Admin user correctly rejects wrong password")
|
||||
else:
|
||||
print(f"❌ FAILURE: Admin user accepts wrong password")
|
||||
else:
|
||||
print("Admin user not found!")
|
||||
@@ -1,57 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
测试登录 API
|
||||
用途:直接测试后端的登录 API 是否能正常响应
|
||||
使用方法:python3 test_login_api.py <username> <password>
|
||||
"""
|
||||
import sys
|
||||
import json
|
||||
import requests
|
||||
|
||||
if len(sys.argv) != 3:
|
||||
print("Usage: python3 test_login_api.py <username> <password>")
|
||||
print("Example: python3 test_login_api.py admin Hxit@54321")
|
||||
sys.exit(1)
|
||||
|
||||
username = sys.argv[1]
|
||||
password = sys.argv[2]
|
||||
|
||||
# 测试登录 API
|
||||
url = "http://localhost:5052/api/user/login"
|
||||
headers = {"Content-Type": "application/json"}
|
||||
data = {"username": username, "password": password}
|
||||
|
||||
print(f"Testing login API for user '{username}'...")
|
||||
try:
|
||||
response = requests.post(url, headers=headers, data=json.dumps(data), timeout=5)
|
||||
print(f"Status code: {response.status_code}")
|
||||
print(f"Response: {response.json()}")
|
||||
|
||||
if response.status_code == 200:
|
||||
print("✅ SUCCESS: Login API returned 200 OK")
|
||||
else:
|
||||
print("❌ FAILURE: Login API returned error")
|
||||
except requests.exceptions.ConnectionError:
|
||||
print("❌ FAILURE: Cannot connect to the server. Is the backend running?")
|
||||
except Exception as e:
|
||||
print(f"❌ FAILURE: Error testing login API: {e}")
|
||||
|
||||
# 测试另一种方式:使用 Flask 应用上下文直接测试
|
||||
print("\nTesting with Flask app context...")
|
||||
try:
|
||||
from app import create_app
|
||||
from app.models import User
|
||||
|
||||
app = create_app()
|
||||
with app.app_context():
|
||||
user = User.query.filter_by(username=username).first()
|
||||
if user:
|
||||
print(f"Found user: {user.username}, Role: {user.role}")
|
||||
if user.check_password(password):
|
||||
print(f"✅ SUCCESS: Password is correct for user '{username}'")
|
||||
else:
|
||||
print(f"❌ FAILURE: Password is incorrect for user '{username}'")
|
||||
else:
|
||||
print(f"❌ FAILURE: User '{username}' not found")
|
||||
except Exception as e:
|
||||
print(f"❌ FAILURE: Error testing with app context: {e}")
|
||||
@@ -1,30 +0,0 @@
|
||||
from app import create_app, db
|
||||
from app.models import Agent, User
|
||||
|
||||
app = create_app('development')
|
||||
|
||||
with app.app_context():
|
||||
# 1. Fix Agent URL
|
||||
agent = Agent.query.get(2)
|
||||
if agent:
|
||||
print(f"Updating Agent {agent.name}...")
|
||||
# Remove trailing /chat-messages if present
|
||||
if '/chat-messages' in agent.api_base_url:
|
||||
new_url = agent.api_base_url.replace('/chat-messages', '')
|
||||
agent.api_base_url = new_url
|
||||
print(f"Updated URL to: {new_url}")
|
||||
|
||||
# Ensure Key is correct (it seemed correct but good to be sure)
|
||||
agent.dify_api_key = 'app-xdiejQibWQy8ZQWXcdxJjS9I'
|
||||
|
||||
# 2. Grant permissions to non-admin users
|
||||
users = User.query.filter(User.role != 'admin').all()
|
||||
for u in users:
|
||||
if agent not in u.agents:
|
||||
u.agents.append(agent)
|
||||
print(f"Granted permission to user: {u.username}")
|
||||
|
||||
db.session.commit()
|
||||
print("Done.")
|
||||
else:
|
||||
print("Agent 2 not found.")
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -8,6 +8,7 @@
|
||||
| [convention/](convention/) | 开发规范(提交、错误处理、环境变量等) |
|
||||
| [openapi/](openapi/) | Dify / 集成 OpenAPI 契约 |
|
||||
| [dify/](dify/) | Dify 集成说明 |
|
||||
| [integrations/](integrations/) | 外部系统集成资料(运行时依赖的 ERP Schema 等) |
|
||||
| [refactor/](refactor/) | 架构重构计划 |
|
||||
| [release_note/](release_note/) | 发布说明 |
|
||||
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
# WeCom Integration Checklist
|
||||
|
||||
## 1) Backend Environment Variables
|
||||
|
||||
Set these on the backend runtime:
|
||||
|
||||
- Recommended start point: copy `backend/.env.production.example` to `backend/.env` and update values.
|
||||
|
||||
- `WECOM_ENABLED=true`
|
||||
- `WECOM_CORP_ID=<your_corp_id>`
|
||||
- `WECOM_AGENT_ID=<your_agent_id>`
|
||||
- `WECOM_SECRET=<your_app_secret>`
|
||||
- `WECOM_REDIRECT_URI=https://<your-domain>/workspace`
|
||||
- `WECOM_AUTO_CREATE_USER=true` (or `false` if you require manual admin binding)
|
||||
- `WECOM_MATCH_RULES=employee_id,mobile` (supported: `employee_id,mobile,email`)
|
||||
- `WECOM_MATCH_OPERATOR=AND` (`AND` / `OR`)
|
||||
- `WECOM_EMPLOYEE_ID_SOURCE=userid` (or `extattr:<name>`)
|
||||
- `WECOM_MOBILE_NORMALIZE=true`
|
||||
|
||||
## 2) Database Migration
|
||||
|
||||
Run migrations after deployment:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
flask db upgrade
|
||||
```
|
||||
|
||||
This applies:
|
||||
|
||||
- WeCom user binding fields in `users`
|
||||
- Login audit table `login_audits`
|
||||
|
||||
## 3) WeCom Console Configuration
|
||||
|
||||
In WeCom admin console (自建应用):
|
||||
|
||||
1. Configure application homepage URL to your HTTPS domain.
|
||||
2. Configure OAuth trusted redirect domain.
|
||||
3. Ensure callback URL matches `WECOM_REDIRECT_URI`.
|
||||
4. Ensure users/groups are visible to the app.
|
||||
|
||||
## 4) Frontend Checks
|
||||
|
||||
1. Open `/workspace`.
|
||||
2. Verify `企业微信登录 / Login with WeCom` button is shown.
|
||||
3. Trigger login in WeCom and confirm redirect back to `/workspace`.
|
||||
4. Verify session is stored and user enters workspace.
|
||||
|
||||
## 5) Admin Operations
|
||||
|
||||
Available admin APIs:
|
||||
|
||||
- `GET /api/admin/wecom/bindings`
|
||||
- `POST /api/admin/wecom/bind`
|
||||
- `POST /api/admin/wecom/unbind`
|
||||
- `GET /api/admin/wecom/login-audits`
|
||||
|
||||
## 6) Smoke Tests
|
||||
|
||||
1. Password login still works.
|
||||
2. WeCom login success creates an audit record.
|
||||
3. Invalid/expired state is rejected.
|
||||
4. Disabled user cannot login via WeCom.
|
||||
@@ -1,8 +0,0 @@
|
||||
# 文档已迁移
|
||||
|
||||
Agent 应用管理方案已迁至:
|
||||
|
||||
- **设计方案**:[docs/platform/agent_application_management.md](platform/agent_application_management.md)
|
||||
- **实现手册**:[docs/platform/agent_application_management_implementation.md](platform/agent_application_management_implementation.md)
|
||||
|
||||
平台索引:[docs/platform/README.md](platform/README.md)
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,7 +0,0 @@
|
||||
# 文档已迁移
|
||||
|
||||
文件检核技术手册已迁至:
|
||||
|
||||
**[docs/features/file-check/technical.md](features/file-check/technical.md)**
|
||||
|
||||
域索引:[docs/features/file-check/README.md](features/file-check/README.md)
|
||||
@@ -1,5 +0,0 @@
|
||||
# 文档已迁移
|
||||
|
||||
固资快照技术方案已迁至:
|
||||
|
||||
**[docs/features/fixed-assets/technical.md](features/fixed-assets/technical.md)**
|
||||
@@ -0,0 +1,7 @@
|
||||
# 外部系统集成资料
|
||||
|
||||
本目录存放外部系统集成所需的技术资料。运行时依赖的资料必须在对应服务、镜像构建及部署校验中保持路径一致。
|
||||
|
||||
| 子目录 | 内容 |
|
||||
| --- | --- |
|
||||
| `erp/` | ERP Oracle 的表结构、字段定义及 Text2SQL 上下文资料 |
|
||||
@@ -0,0 +1,7 @@
|
||||
# ERP 集成资料
|
||||
|
||||
| 文件 | 用途 | 使用方 |
|
||||
| --- | --- | --- |
|
||||
| `text2sql_schema.md` | ERP Oracle 表、字段及业务含义,作为 Text2SQL 生成 SQL 的上下文 | `backend/app/services/text2sql.py` |
|
||||
|
||||
更新 Schema 后,应同步验证 Text2SQL 查询,并重新构建后端镜像。
|
||||
File renamed without changes.
@@ -1,176 +0,0 @@
|
||||
# 知识库 Excel/CSV 切块与 Dify 同步
|
||||
|
||||
> 说明 Excel/CSV 清洗成 Markdown 后如何与 Dify custom 分段配合,以及版本目录下调试产物路径。
|
||||
|
||||
---
|
||||
|
||||
## 1. 问题背景
|
||||
|
||||
知识库 Excel(如 RoHS/供应商排程宽表)经 edkb 清洗成 Markdown 后,同步 Dify 时若使用默认 `process_rule.mode=automatic`,宽表 pipe 行或长段落会被 Dify 按 token/标点切散,导致**同一数据行字段落入不同 segment**,Hit testing 检索时上下文不完整。
|
||||
|
||||
典型症状:
|
||||
|
||||
- 问「某供应商编码 + 物料」命中片段只有半行字段;
|
||||
- Dify 文档分段数远大于 Excel 数据行数,或一行被拆成多段。
|
||||
|
||||
---
|
||||
|
||||
## 2. 改造后数据流
|
||||
|
||||
```text
|
||||
上传 xlsx/csv
|
||||
→ edkb loader_excel / loader_csv
|
||||
→ table_linearize(宽表行文本化 / 窄表 pipe 行 \n\n 分隔)
|
||||
→ document.md(写入 KB 版本目录)
|
||||
→ [可选] 04_chunks.jsonl / chunks/(调试,不传 Dify)
|
||||
→ sync_dify:create-by-text / update-by-text
|
||||
→ Dify process_rule.mode=custom(Excel/CSV 专用,separator=\n\n)
|
||||
```
|
||||
|
||||
### table_linearize 输出规则(摘要)
|
||||
|
||||
| 表类型 | 条件 | 输出格式 |
|
||||
| --- | --- | --- |
|
||||
| 条件/处理/责任表 | 表头含「条件」「处理」等关键词 | 每条 bullet 之间 `\n\n` |
|
||||
| 窄表 | 列数 ≤ 8 | 表头块 + 每个数据行单独 `\| ... \|` 块,行间 `\n\n` |
|
||||
| 宽表 | 列数 > 8 | `- 【行】列1=值1;列2=值2;...`,行间 `\n\n` |
|
||||
|
||||
示例(宽表,与 RoHS 排程类文件一致):
|
||||
|
||||
```markdown
|
||||
## Sheet: result
|
||||
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;物料编码=121040033400;...
|
||||
|
||||
- 【行】供应商编码=VCCD00027;供应商名称=沃顿;...
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. 配置项(KB_DIFY_*)
|
||||
|
||||
可通过 **环境变量** 或管理台 **AppSetting** 覆盖;读取入口:`get_kb_dify_settings()`。
|
||||
|
||||
| 键 | 默认值 | 含义 |
|
||||
| --- | --- | --- |
|
||||
| `KB_DIFY_PROCESS_MODE` | `automatic` | 非 Excel/CSV 文档的 Dify 分段模式 |
|
||||
| `KB_DIFY_PROCESS_MODE_EXCEL` | `custom` | xlsx / xls / csv 专用分段模式 |
|
||||
| `KB_DIFY_SEGMENT_SEPARATOR` | `\n\n`(env 写 `\\n\\n`) | custom 模式通用分隔符 |
|
||||
| `KB_DIFY_SEGMENT_SEPARATOR_EXCEL` | `\n\n` | Excel/CSV custom 分隔符,与 table_linearize 对齐 |
|
||||
| `KB_DIFY_SEGMENT_MAX_TOKENS` | `800` | custom 模式 max_tokens |
|
||||
| `KB_DIFY_SEGMENT_CHUNK_OVERLAP` | `50` | custom 模式 chunk_overlap |
|
||||
| `KB_DIFY_REMOVE_URLS` | `false` | 映射 Dify `remove_urls_emails`;RoHS 等表含 PDF 链接,默认关闭 |
|
||||
|
||||
`.env` 示例:
|
||||
|
||||
```bash
|
||||
KB_DIFY_PROCESS_MODE=automatic
|
||||
KB_DIFY_PROCESS_MODE_EXCEL=custom
|
||||
KB_DIFY_SEGMENT_SEPARATOR_EXCEL=\n\n
|
||||
KB_DIFY_SEGMENT_MAX_TOKENS=800
|
||||
KB_DIFY_SEGMENT_CHUNK_OVERLAP=50
|
||||
KB_DIFY_REMOVE_URLS=false
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. 版本目录与调试文件
|
||||
|
||||
清洗完成后,单版本目录结构(相对 `backend/data/kb/` 或部署挂载路径):
|
||||
|
||||
```text
|
||||
group_XXXX/document_XXXXXX/vXXX/
|
||||
su_schedule_5.xlsx # 原始上传
|
||||
document.md # 清洗结果(sync_dify 读取此文件)
|
||||
document_preview.md # 可选,含图片预览时
|
||||
04_chunks.jsonl # 可选,edkb 切块调试(不传 Dify)
|
||||
chunks/
|
||||
chunk_0000.md
|
||||
chunk_0001.md
|
||||
...
|
||||
```
|
||||
|
||||
- `document.md`:权威同步文本;
|
||||
- `04_chunks.jsonl`:edkb export 阶段产物,一行一个 chunk JSON,便于与 Dify segment 列表对照;
|
||||
- 若清洗失败回退占位,会出现 `*.preview.txt`(含 `clean_status=placeholder_success`),**不应**作为 Dify 同步源。
|
||||
|
||||
---
|
||||
|
||||
## 5. 手动验收(curl)
|
||||
|
||||
对已有 dataset 创建文本文档,模拟 Excel custom 分段(需替换 `DATASET_ID`、`API_KEY`):
|
||||
|
||||
```bash
|
||||
curl -X POST "http://<DIFY_HOST>/v1/datasets/<DATASET_ID>/document/create-by-text" \
|
||||
-H "Authorization: Bearer <API_KEY>" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"name": "excel-chunk-test.md",
|
||||
"text": "## Sheet: result\n\n- 【行】列1=a;列2=b。\n\n- 【行】列1=c;列2=d。",
|
||||
"indexing_technique": "high_quality",
|
||||
"doc_form": "text_model",
|
||||
"process_rule": {
|
||||
"mode": "custom",
|
||||
"rules": {
|
||||
"pre_processing_rules": [
|
||||
{"id": "remove_extra_spaces", "enabled": true},
|
||||
{"id": "remove_urls_emails", "enabled": false}
|
||||
],
|
||||
"segmentation": {
|
||||
"separator": "\n\n",
|
||||
"max_tokens": 800,
|
||||
"chunk_overlap": 50
|
||||
}
|
||||
}
|
||||
}
|
||||
}'
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. 对比 Dify 分段与本地 jsonl
|
||||
|
||||
1. 打开 Dify 知识库 → 该文档 → **分段列表**,记录 segment 数量与首段内容;
|
||||
2. 打开版本目录 `04_chunks.jsonl`,统计非空行数:`wc -l 04_chunks.jsonl`;
|
||||
3. 宽表场景:segment 数应接近 **数据行数**(每行一条 `【行】` bullet,经 `\n\n` 切开);
|
||||
4. 在 Dify **Hit testing** 用表中存在的「供应商编码 + 物料名称」提问,应命中包含完整行字段的片段。
|
||||
|
||||
---
|
||||
|
||||
## 7. 回滚
|
||||
|
||||
| 层级 | 做法 |
|
||||
| --- | --- |
|
||||
| Dify 分段 | 设 `KB_DIFY_PROCESS_MODE_EXCEL=automatic`,并对已有 Excel 文档 **重新 sync_dify** |
|
||||
| 清洗格式 | git revert `table_linearize` 相关提交(document.md 格式恢复旧行为) |
|
||||
| 调试文件 | 忽略 `04_chunks.jsonl`,不影响线上同步 |
|
||||
|
||||
> **发版说明**:环境变量变更后,**已有 Excel 文档需触发重新 sync_dify** 才会应用新的 `process_rule`;仅重新清洗不会更新 Dify 远端分段规则。
|
||||
|
||||
---
|
||||
|
||||
## 8. 本地开发注意
|
||||
|
||||
- API 与 KB worker 须使用同一虚拟环境:
|
||||
|
||||
```bash
|
||||
cd backend && source .venv/bin/activate
|
||||
python run.py # 终端 1
|
||||
python worker_kb.py # 终端 2
|
||||
```
|
||||
|
||||
- `.env.shared` 中 `EDKB_FILE_TIMEOUT_SEC` 对 Word 等慢格式启用 spawn 超时;**Excel/CSV 已在代码中豁免**,避免 macOS 本地 `Operation not permitted`。
|
||||
- 相关代码:`edkb_system/skills/table_linearize.py`、`app/services/knowledge_cleaning/dify_sync_service.py`、`edkb_adapter.py`。
|
||||
|
||||
---
|
||||
|
||||
## 9. 相关测试
|
||||
|
||||
```bash
|
||||
cd backend && source .venv/bin/activate
|
||||
python -m pytest tests/test_dify_sync_process_rule.py \
|
||||
tests/test_table_linearize.py \
|
||||
tests/test_kb_excel_cleaning.py \
|
||||
tests/test_edkb_adapter_chunks.py \
|
||||
tests/test_edkb_file_timeout.py -q
|
||||
```
|
||||
@@ -1,174 +0,0 @@
|
||||
# 主平台知识库运行时部署说明
|
||||
|
||||
## 目标
|
||||
|
||||
将知识库上传、清洗、Dify 同步运行时统一收敛到主平台 `hxops&xinxin`,不再依赖 `xinxin2` 独立运行 `api + worker + redis`。
|
||||
|
||||
当前主平台 `docker-compose.yml` 已接入:
|
||||
|
||||
- `kb-redis`
|
||||
- `hxops-backend`
|
||||
- `hxops-kb-worker`
|
||||
- `hxops-frontend`
|
||||
- 共享卷 `hxops_runtime_data`
|
||||
|
||||
## 容器职责
|
||||
|
||||
### `hxops-backend`
|
||||
|
||||
- 提供主平台 API
|
||||
- 提供知识库 API:`/api/kb/*`
|
||||
- 提供集成 API:`/api/integration/*`
|
||||
- 挂载知识库存储根目录到 `/app/data`
|
||||
|
||||
### `hxops-kb-worker`
|
||||
|
||||
- 轮询执行知识库 `clean` 任务
|
||||
- 复用后端镜像,避免维护第二套依赖
|
||||
- 与后端共享数据库、Redis、知识库存储卷
|
||||
|
||||
### `kb-redis`
|
||||
|
||||
- 提供知识库异步任务所需 Redis
|
||||
- 当前主要用于主平台知识库运行时接入与后续队列化扩展
|
||||
|
||||
## 关键环境变量
|
||||
|
||||
部署主平台知识库运行时时,至少确认以下变量:
|
||||
|
||||
| 变量名 | 用途 | 建议值/说明 |
|
||||
| --- | --- | --- |
|
||||
| `DATABASE_URL` | 主平台数据库连接 | 指向当前主平台生产库 |
|
||||
| `SECRET_KEY` | Flask/JWT 密钥 | 使用足够长的随机字符串 |
|
||||
| `REDIS_URL` | 知识库 Redis 连接 | 默认可用 `redis://kb-redis:6379/0` |
|
||||
| `KB_STORAGE_ROOT` | 知识库文件根目录 | 容器内建议保持 `/app/data/kb` |
|
||||
| `KB_TASK_EXECUTION_MODE` | 任务执行模式 | 生产建议 `worker` |
|
||||
| `KB_WORKER_POLL_SECONDS` | worker 轮询间隔 | 默认 `2` 即可 |
|
||||
| `KB_JOB_RUNNING_TIMEOUT_SECONDS` | running 任务超时回收 | 默认 `300`,应大于单次清洗预期耗时 |
|
||||
| `EDKB_SOFFICE_TIMEOUT_SEC` | LibreOffice 转换超时 | 默认 `120` |
|
||||
| `INTEGRATION_API_MODE` | 聊天侧集成调用模式 | 主平台自承载时建议 `local` |
|
||||
| `WECOM_PUBLIC_BASE_URL` | 对外可访问主平台地址 | 供聊天/企业微信/文件回链生成绝对地址 |
|
||||
| `DIFY_API_BASE` | Dify API 地址 | 按现网环境填写 |
|
||||
| `DIFY_API_KEY` | Dify API Key | 由管理端保存后可持久化到 `.env`/数据库 |
|
||||
| `KB_REDIS_IMAGE` | Redis 镜像来源 | 默认 `redis:7-alpine`,内网可改为私有仓库地址 |
|
||||
| `PYTHON_BASE_IMAGE` | 后端基础镜像 | 默认 `python:3.12-slim`,内网可改为私有仓库地址 |
|
||||
| `NODE_BASE_IMAGE` | 前端构建基础镜像 | 默认 `node:22-alpine` |
|
||||
| `NGINX_BASE_IMAGE` | 前端运行基础镜像 | 默认 `nginx:alpine` |
|
||||
| `PIP_INDEX_URL` | 后端 pip 主镜像源 | 可指向国内或内网 PyPI 镜像 |
|
||||
| `PIP_EXTRA_INDEX_URL` | 后端 pip 额外镜像源 | 用于补充私有或备用源 |
|
||||
|
||||
补充说明:
|
||||
|
||||
- 宿主机应先创建 `backend/.env` 文件,再执行 `docker compose up`,避免 Docker 将目标当作目录挂载。
|
||||
- 当前 `docker-compose.yml` 不再从宿主机 shell 强依赖 `DATABASE_URL`,而是由容器内挂载的 `backend/.env` 提供数据库连接与密钥。
|
||||
- 若当前环境无法访问 Docker Hub,可在执行前设置 `KB_REDIS_IMAGE`,例如改为企业私有仓库中的 Redis 镜像。
|
||||
- 若当前环境无法访问 Docker Hub,也可同时设置 `PYTHON_BASE_IMAGE`、`NODE_BASE_IMAGE`、`NGINX_BASE_IMAGE`,把后端/前端基础镜像切到企业私有仓库。
|
||||
- 若后端 `pip install -r requirements.txt` 速度过慢或不稳定,可设置 `PIP_INDEX_URL` / `PIP_EXTRA_INDEX_URL`。
|
||||
- OCR 依赖(OpenCV/RapidOCR)在 `backend/requirements-ocr.txt`,由 `backend/Dockerfile` 分步安装,避免同时下载 `opencv-python` 与 `opencv-python-headless` 两个大 wheel。
|
||||
- 若要沿用旧 `xinxin2` 文件目录,切换前需先把历史知识库文件迁入主平台卷,并保证 `KB_STORAGE_ROOT` 指向迁移后的新路径。
|
||||
- 若仍要调用外部 integration API,才需要配置 `INTEGRATION_API_BASE` 与 `INTEGRATION_API_KEY`,此时 `INTEGRATION_API_MODE` 设为 `external`。
|
||||
- 当前知识库主链路的 `worker_kb` 轮询数据库即可工作,`kb-redis` 以 profile 方式保留,用于后续异步队列扩展或外接 Redis 场景。
|
||||
|
||||
## 启动步骤
|
||||
|
||||
### 1. 构建并启动
|
||||
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
若使用私有镜像仓库,可先设置:
|
||||
|
||||
```bash
|
||||
$env:KB_REDIS_IMAGE = "your-registry.example.com/library/redis:7-alpine"
|
||||
$env:PYTHON_BASE_IMAGE = "your-registry.example.com/library/python:3.12-slim"
|
||||
$env:NODE_BASE_IMAGE = "your-registry.example.com/library/node:22-alpine"
|
||||
$env:NGINX_BASE_IMAGE = "your-registry.example.com/library/nginx:alpine"
|
||||
$env:PIP_INDEX_URL = "https://pypi.tuna.tsinghua.edu.cn/simple"
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
若需要同时启用内置 Redis,再改为:
|
||||
|
||||
```bash
|
||||
docker compose --profile kb-redis up -d --build
|
||||
```
|
||||
|
||||
### 2. 执行数据库迁移
|
||||
|
||||
```bash
|
||||
docker compose exec hxops-backend flask db upgrade
|
||||
```
|
||||
|
||||
### 3. 检查服务状态
|
||||
|
||||
```bash
|
||||
docker compose ps
|
||||
```
|
||||
|
||||
预期:
|
||||
|
||||
- `hxops-backend` 为 `Up`
|
||||
- `hxops-kb-worker` 为 `Up`(与 backend 共用镜像;Jenkins/`deploy_compose.sh` 在后端变更时会一并重建)
|
||||
- `hxops-frontend` 为 `Up`
|
||||
|
||||
若启用了 `kb-redis` profile,则额外确认:
|
||||
|
||||
- `kb-redis` 为 `Up`
|
||||
|
||||
### 4. 检查 worker 日志
|
||||
|
||||
```bash
|
||||
docker compose logs -f hxops-kb-worker
|
||||
```
|
||||
|
||||
预期可见:
|
||||
|
||||
```text
|
||||
[kb-worker] started, poll_seconds=2.0
|
||||
```
|
||||
|
||||
## 端口与卷
|
||||
|
||||
当前主平台容器端口关系:
|
||||
|
||||
- 宿主机 `5002` -> `hxops-backend:5000`
|
||||
- 宿主机 `8890` -> `hxops-frontend:80`
|
||||
|
||||
当前关键卷:
|
||||
|
||||
- `hxops_runtime_data`:主平台运行时可写数据,包含知识库存储目录
|
||||
- `hxops_redis_data`:Redis 持久化数据
|
||||
|
||||
## 切换前检查
|
||||
|
||||
切换 `xinxin2` 运行时前,至少确认:
|
||||
|
||||
1. 主平台已完成数据库迁移
|
||||
2. 主平台后台可正常打开知识库管理页
|
||||
3. 上传文件后会生成 `upload/clean` 任务
|
||||
4. `hxops-kb-worker` 能持续消费待执行任务
|
||||
5. Dify 设置已在主平台管理端保存并通过健康检查
|
||||
6. 聊天侧 `INTEGRATION_API_MODE=local`
|
||||
7. `WECOM_PUBLIC_BASE_URL` 对应外部真实可访问域名
|
||||
|
||||
## 切换后冒烟清单
|
||||
|
||||
建议按顺序验证:
|
||||
|
||||
1. 登录主平台并进入知识库工作台
|
||||
2. 新建一个分组和一个文档条目
|
||||
3. 上传一个 `txt` 或 `md` 文件
|
||||
4. 确认任务状态从 `pending/running` 进入 `success`
|
||||
5. 在文档详情里触发一次 Dify 同步
|
||||
6. 调用主平台 `/api/integration/dify-file` 或 `/api/integration/dify-files/resolve` 验证映射
|
||||
7. 从聊天侧点击源文件链接,确认下载地址仍指向主平台
|
||||
|
||||
## 常见注意事项
|
||||
|
||||
- `hxops-backend` 容器内部监听 `5000`,宿主机映射使用 `5002:5000`;若改端口,需同步更新网关/探针配置。
|
||||
- `worker_kb.py` 已按 `FLASK_ENV` 或 `APP_CONFIG` 选择配置;生产环境不要再用 `development` 配置启动 worker。
|
||||
- `KB_TASK_EXECUTION_MODE=worker` 时,需要确保 `hxops-kb-worker` 运行;若临时排障切到 `sync`,应评估接口耗时影响。
|
||||
- `kb-redis` 已改为可选 profile,不执行 `docker compose --profile kb-redis ...` 时不会默认拉起。
|
||||
- `backend/.env` 与数据库配置存在持久化联动,重建容器前不要误删该文件。
|
||||
- `SECRET_KEY` 过短会导致 JWT/HMAC 安全性不足,生产必须替换为长随机值。
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
**合并前自检**:`pytest backend/tests` 通过;改表结构须配套 Alembic 迁移;对外 URL 保持不变。
|
||||
|
||||
**当前进度**:Wave 1 基础设施已完成(`register_blueprints`、`extensions.py`、`core/*` 权威实现、根 shim 已删除、`AppError` envelope 统一、Tool API 保留 Dify 格式);Wave 3 进行中(`admin/` 已拆包,`user.py` / `chat.py` 待拆)。
|
||||
**当前进度**:Wave 1 基础设施已完成(`register_blueprints`、`extensions.py`、`core/*` 权威实现、根 shim 已删除、`AppError` envelope 统一、Tool API 保留 Dify 格式);Wave 3 已完成(`admin/`、`kb/`、`user/`、`chat/` 均已迁包;用户认证按本地密码、Casdoor、企微与密码重置拆分,共享认证操作收口至 `auth_support.py`;Chat 的 SSE、会话、预览、上传与反馈均已按职责拆分)。
|
||||
|
||||
---
|
||||
|
||||
@@ -56,7 +56,7 @@
|
||||
|
||||
| 问题 | 典型文件 | 约行数 |
|
||||
| --- | --- | --- |
|
||||
| API god 文件 | `api/user.py`、`api/chat.py`(`api/admin.py` 已拆至 `api/admin/*`) | 1400–2200 |
|
||||
| API god 文件 | `api/chat.py`、`api/user.py`、`api/admin.py` 均已拆包 | 原单体 1400–2200 |
|
||||
| Service monolith | `services/text2sql.py`、`shipping_notice/tools.py` | 1200–2000 |
|
||||
| 单文件模型 | `models.py` | 796(30+ 模型) |
|
||||
| 错误响应不统一 | API 混用 `AppError` 与 `jsonify({'error':...})` | 300+ 处 |
|
||||
@@ -120,14 +120,14 @@ backend/
|
||||
│ ├── api/ # HTTP 层:薄 Blueprint,单路由目标 < 80 行
|
||||
│ │ ├── __init__.py # register_blueprints(app)
|
||||
│ │ │
|
||||
│ │ ├── chat/ # ← 现有 api/chat.py,Wave 3 迁包
|
||||
│ │ ├── chat/ # ✅ 已从 api/chat.py 迁包(Wave 3 完成)
|
||||
│ │ │ ├── __init__.py # chat_bp
|
||||
│ │ │ ├── completions.py # POST /completions(SSE)
|
||||
│ │ │ ├── sessions.py # 会话 CRUD
|
||||
│ │ │ ├── logs.py # 历史、反馈
|
||||
│ │ │ └── preview.py # PLM/Excel 预览
|
||||
│ │ │
|
||||
│ │ ├── user/ # ← 现有 api/user.py,Wave 3
|
||||
│ │ ├── user/ # ✅ 已从 api/user.py 迁包(Wave 3 完成)
|
||||
│ │ │ ├── auth.py # Casdoor OIDC
|
||||
│ │ │ ├── profile.py
|
||||
│ │ │ ├── homepage.py
|
||||
@@ -150,7 +150,7 @@ backend/
|
||||
│ │ │ ├── tasks.py
|
||||
│ │ │ └── runs.py
|
||||
│ │ │
|
||||
│ │ ├── kb/ # ← 现有 knowledge_base.py,Wave 3
|
||||
│ │ ├── kb/ # ✅ 已从 knowledge_base.py 迁包(Wave 3 完成)
|
||||
│ │ │ ├── groups.py
|
||||
│ │ │ ├── documents.py
|
||||
│ │ │ ├── upload.py
|
||||
@@ -272,8 +272,8 @@ Python 3 中 **模块文件与同名包不能并存**,否则包覆盖模块、
|
||||
| `app/__init__.py`(db) | `extensions.py` | 1 |
|
||||
| `app/errors.py` 等根 shim(已删除) | `core/*` | ✅ |
|
||||
| `app/models.py` | `models/*.py` | 1 |
|
||||
| `app/api/user.py` | `api/user/*` + `services/user/*` | 3 |
|
||||
| `app/api/chat.py` | `api/chat/*` + `services/chat/router.py` | 3 |
|
||||
| `app/api/user.py` | `api/user/*` + `services/user/*` | 3 ✅ |
|
||||
| `app/api/chat.py` | `api/chat/*` + `services/chat/router.py` | 3 ✅ |
|
||||
| `app/api/admin.py` | `api/admin/*` + `services/admin/*` | 3 ✅ |
|
||||
| `app/api/knowledge_base.py` | `api/kb/*` + `services/kb/*` | 3 |
|
||||
| `app/api/schedule_admin.py` | `api/schedule/*` | 1 |
|
||||
@@ -398,8 +398,8 @@ jobs/handlers/kb_clean.py # worker 执行 → services/kb → edkb_system
|
||||
|
||||
| 域 | URL 前缀 | 目标 API 包 | 核心 Service | 现状 / 备注 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| **chat** | `/api/chat` | `api/chat/` | `services/chat/router.py` | `chat.py` ~1882 行;SSE + 意图路由 |
|
||||
| **user** | `/api/user` | `api/user/` | `services/auth/*`、`services/user/*` | `user.py` ~2223 行;Casdoor + 企微 |
|
||||
| **chat** | `/api/chat` | `api/chat/` | `services/chat/router.py` | ✅ 已迁包;SSE、会话、预览、上传与反馈按职责拆分 |
|
||||
| **user** | `/api/user` | `api/user/` | `services/auth/*`、`services/user/*` | 已迁包;认证路由按 local/casdoor/wecom/password-reset 拆分,共享操作集中于 `auth_support.py` |
|
||||
| **admin** | `/api/admin` | `api/admin/` | `services/admin/*` | ✅ 已迁包;原 `admin.py` 已删除 |
|
||||
| **schedule** | `/api/admin` | `api/schedule/` | `services/schedule/*` | 与 admin 同前缀,勿路由冲突 |
|
||||
| **kb** | `/api/kb` | `api/kb/` | `services/kb/*` | `knowledge_base.py`;异步清洗 |
|
||||
@@ -515,7 +515,7 @@ from app.models import User, Agent # Wave 1 后仍保持此入口
|
||||
Wave 0 骨架建立 ✅ 目录 + 占位(行为不变)
|
||||
Wave 1 基础设施 ✅ register_blueprints / extensions / core / AppError / models
|
||||
Wave 2 任务层 jobs/ 接 KB worker
|
||||
Wave 3 拆 god 文件 admin ✅ → user → chat → kb
|
||||
Wave 3 拆 god 文件 admin ✅ → user ✅ → chat ✅ → kb ✅
|
||||
Wave 4 集成收敛 integrations/、scheduler 迁出 web
|
||||
```
|
||||
|
||||
|
||||
@@ -248,9 +248,10 @@ modules/users/components/UserFormModal.vue
|
||||
|
||||
| Feature | 路由前缀 | 入口 Layout / View | 说明 |
|
||||
|---------|----------|-------------------|------|
|
||||
| **auth** | `/`、`/reset-password`、`/casdoor-callback` | `LoginView` 等 | `useAuth` / `useAuthStore`;用户 API 在 `auth/api/user.api.ts` |
|
||||
| **workspace** | `/workspace/*` | `WorkspaceLayout` | 应用管理、个人资料、排程记录、嵌入 KB/货代页 |
|
||||
| **chat** | `/chat/:agentId`、`/workspace/history` | `ChatView` | SSE 在 `useChat`;子域 `shipping/`、`leave/`、`history/` |
|
||||
| **auth** | `/`、`/reset-password`、`/casdoor-callback` | `LoginView` 等 | `useAuth` / `useAuthStore`;认证请求在 `auth/api/auth.api.ts` |
|
||||
| **user** | `/workspace/profile` | `UserProfilePage` | 当前用户资料、密码修改、可访问 Agent 与指南;包含 `api/user.api.ts`、`composables/useUserProfile.ts` 和 `components/UserPasswordDialog.vue` |
|
||||
| **workspace** | `/workspace/*` | `WorkspaceLayout` | 应用管理、排程记录、嵌入 KB/货代页;为 user 资料页提供布局上下文 |
|
||||
| **chat** | `/chat/:agentId`、`/workspace/history` | `ChatView` | SSE 在 `useChat`;子域 `shipping/`、`leave/`、`history/`;请假 API 位于 `chat/leave/leave.api.ts` |
|
||||
| **admin** | `/admin/*` | `AdminLayout` | 14+ 子模块于 `modules/`;`/admin?module=x` 已 redirect |
|
||||
| **kb** | 治理 `/admin/knowledge-base`;作业 `/workspace/knowledge-base` | `KbAdminPanel` / `KbWorkspaceView` | 治理 vs 作业面分离;旧 `/kb/*` 仅 redirect |
|
||||
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
# 文档已迁移
|
||||
|
||||
货代发货通知技术手册已迁至:
|
||||
|
||||
**[docs/features/shipping-notice/technical.md](features/shipping-notice/technical.md)**
|
||||
|
||||
域索引:[docs/features/shipping-notice/README.md](features/shipping-notice/README.md)
|
||||
@@ -1,5 +0,0 @@
|
||||
# 文档已迁移
|
||||
|
||||
货代发货通知业务说明已迁至:
|
||||
|
||||
**[docs/features/shipping-notice/business.md](features/shipping-notice/business.md)**
|
||||
@@ -1,5 +0,0 @@
|
||||
# 文档已迁移
|
||||
|
||||
库存源路由与 RPA Driver 方案已迁至:
|
||||
|
||||
**[docs/features/shipping-notice/inventory_source_plan.md](features/shipping-notice/inventory_source_plan.md)**
|
||||
@@ -1,213 +0,0 @@
|
||||
# `xinxin2` 迁移收尾清单(第一版)
|
||||
|
||||
## 目标
|
||||
|
||||
将 `xinxin2` 从“独立运行的文档清洗平台”收敛为:
|
||||
|
||||
- 代码能力已并入 `hxops&xinxin`
|
||||
- 登录入口统一使用 `hxops&xinxin`
|
||||
- 聊天侧与外部系统优先访问 `hxops&xinxin` 的知识库与集成 API
|
||||
- `xinxin2` 仅在少量未切换的部署职责上临时保留
|
||||
|
||||
## 当前已完成的迁移能力
|
||||
|
||||
主平台 `hxops&xinxin` 当前已经具备以下能力:
|
||||
|
||||
- 知识库分组管理
|
||||
- 文档条目管理
|
||||
- 文件上传
|
||||
- 文档版本记录
|
||||
- 自动 `clean` 任务执行
|
||||
- `edkb_system` 轻量接入
|
||||
- Dify 同步第一版
|
||||
- Dify 设置与健康检查面板
|
||||
- `/api/integration/*` 集成查询接口
|
||||
- 聊天侧默认优先指向主平台自身 integration API
|
||||
- 基础回归测试:分组/文档/上传/同步/集成 API
|
||||
|
||||
## 结论摘要
|
||||
|
||||
### 可立即下线
|
||||
|
||||
这些入口已经被主平台完全替代,继续保留只会造成双入口混淆:
|
||||
|
||||
| `xinxin2` 项 | 当前状态 | 处理建议 |
|
||||
| --- | --- | --- |
|
||||
| `frontend/src/views/LoginView.vue` | 已由主平台登录替代 | 停用 |
|
||||
| `frontend/src/lib/auth.ts` | 已由主平台鉴权替代 | 停用 |
|
||||
| `frontend/src/main.ts` | 不再需要独立前端入口 | 停用 |
|
||||
| `frontend/src/router/index.ts` | 不再需要独立路由壳 | 停用 |
|
||||
| `backend/app/api/auth.py` | 不再需要独立登录 API | 停用 |
|
||||
| `backend/app/main.py` | 不再需要独立 FastAPI 入口 | 停用 |
|
||||
| `start-local-frontend.ps1` | 不再需要独立前端启动 | 停用 |
|
||||
| `start-local-dev.ps1` | 不再需要独立双进程启动 | 停用 |
|
||||
|
||||
### 待切换后下线
|
||||
|
||||
这些职责在主平台里已有对应实现,但部署或调用方还需要完成切换:
|
||||
|
||||
| `xinxin2` 项 | 当前替代物 | 下线前条件 |
|
||||
| --- | --- | --- |
|
||||
| `backend/app/api/integration.py` | `hxops&xinxin/backend/app/api/integration.py` | 确认所有调用方都改指向主平台 |
|
||||
| `frontend/src/views/WorkspaceView.vue` | `hxops&xinxin/frontend/src/views/KbWorkspaceView.vue` | 用户不再访问 `8891` 前端 |
|
||||
| `frontend/src/views/AdminView.vue` | `hxops&xinxin/frontend/src/views/KbAdminView.vue` | 管理员改从主平台进入 |
|
||||
| `backend/app/api/groups.py` | `hxops&xinxin/backend/app/api/knowledge_base.py` | 验证分组管理不再依赖旧服务 |
|
||||
| `backend/app/api/files.py` | 主平台 `knowledge_base.py` 已覆盖核心主链路 | 如需高级下载/批量功能,先补齐后再停 |
|
||||
| `backend/app/tasks.py` | `hxops&xinxin/backend/app/services/knowledge_cleaning/tasks.py` | 生产环境切到主平台 worker/sync 模式 |
|
||||
| `backend/worker.py` | `hxops&xinxin/backend/worker_kb.py` | 主平台部署接入 worker 后再停 |
|
||||
|
||||
### 暂时保留
|
||||
|
||||
这些项暂时还建议保留,不是因为业务没迁,而是因为主平台部署面还没完全接住:
|
||||
|
||||
| `xinxin2` 项 | 暂时保留原因 | 建议 |
|
||||
| --- | --- | --- |
|
||||
| `docker-compose.yml` | 主平台已补 `redis` / `worker_kb` / 知识库存储卷,但切换后仍需观察一段时间 | 切换稳定后再停 |
|
||||
| `backend/Dockerfile` | 主平台镜像未完全吸收文档清洗依赖时,仍是参考来源 | 保留作为迁移参考 |
|
||||
| `start-local-backend.ps1` | 主平台本地脚本还未完全覆盖知识库依赖检查 | 保留到本地开发文档更新完成 |
|
||||
| `backend/edkb_system/*` 原仓库副本 | 主平台已轻量接入,但若要完全停旧仓库,需要确认无外部脚本再直接引用旧路径 | 短期保留 |
|
||||
| `backend/tests/*` | 主平台只补了核心主链路测试,尚未完整迁入所有旧测试 | 保留到测试迁移完成 |
|
||||
|
||||
## 当前最大阻塞
|
||||
|
||||
### 阻塞 1:主平台生产部署已接住知识库运行时,但仍需完成切换验证
|
||||
|
||||
当前主平台 `docker-compose.yml` 已新增:
|
||||
|
||||
- `kb-redis`
|
||||
- `hxops-backend`
|
||||
- `hxops-kb-worker`
|
||||
- `hxops-frontend`
|
||||
- `hxops_runtime_data`
|
||||
- `hxops_redis_data`
|
||||
|
||||
影响:
|
||||
|
||||
- 现在的重点已从“补部署件”转为“验证切换链路”
|
||||
- 如果线上有专门的 `8891` 文件存储目录,切换前仍要确认主平台 `KB_STORAGE_ROOT` 已指向迁移后的新位置
|
||||
- 若要正式下线旧 worker,需观察主平台 `hxops-kb-worker` 实际消费任务是否稳定
|
||||
|
||||
### 阻塞 2:调用方地址切换要做最终确认
|
||||
|
||||
虽然聊天侧已经默认优先用主平台自身 `/api/integration/*`,但仍建议确认:
|
||||
|
||||
- `INTEGRATION_API_MODE=local`
|
||||
- `WECOM_PUBLIC_BASE_URL` 正确配置
|
||||
- 旧的 `INTEGRATION_API_BASE` 不再被外部系统直接依赖
|
||||
|
||||
### 阻塞 3:部分高级能力仍是“第一版”
|
||||
|
||||
当前主平台已跑通主链路,但以下能力仍属于增强项,不建议在未验证前立刻删除旧仓库参考:
|
||||
|
||||
- 更完整的 `edkb_system` skill 支持
|
||||
- 批量下载与更多文件格式处理
|
||||
- 完整异步队列化执行策略
|
||||
- 更完整的 Dify diff / import 行为
|
||||
|
||||
## 建议的切换顺序
|
||||
|
||||
### 第一步:停独立入口
|
||||
|
||||
先停掉所有“用户可见的独立入口”:
|
||||
|
||||
- `xinxin2` 独立登录页
|
||||
- `xinxin2` 独立前端 Vite 本地启动
|
||||
- `xinxin2` 独立前端对外访问入口
|
||||
|
||||
判定标准:
|
||||
|
||||
- 用户和管理员都只从 `hxops&xinxin` 访问知识库模块
|
||||
|
||||
### 第二步:切集成地址
|
||||
|
||||
确认聊天链路和外部系统都使用主平台集成接口:
|
||||
|
||||
- `/api/integration/dify-file`
|
||||
- `/api/integration/dify-files/resolve`
|
||||
- `/api/integration/files/<id>/download`
|
||||
|
||||
判定标准:
|
||||
|
||||
- 旧 `xinxin2` 集成 API 日志无实际流量
|
||||
|
||||
### 第三步:切运行时
|
||||
|
||||
把知识库运行时职责切到主平台:
|
||||
|
||||
- 在主平台 compose 中加入 `redis`
|
||||
- 在主平台 compose 中加入 `worker_kb`
|
||||
- 确认 `KB_STORAGE_ROOT` 与卷映射
|
||||
|
||||
判定标准:
|
||||
|
||||
- 上传、自动 clean、sync_dify 都在主平台运行完成
|
||||
|
||||
### 第四步:停旧后端服务
|
||||
|
||||
当以下条件同时满足时,可停 `xinxin2` 的 `api` / `worker`:
|
||||
|
||||
- 主平台知识库 API 正常
|
||||
- 主平台 integration API 正常
|
||||
- 主平台 worker 正常
|
||||
- 旧服务近一段时间无流量或仅剩探测流量
|
||||
|
||||
## 具体可下线项清单
|
||||
|
||||
### 现在就可以停
|
||||
|
||||
- `xinxin2/frontend/src/views/LoginView.vue`
|
||||
- `xinxin2/frontend/src/lib/auth.ts`
|
||||
- `xinxin2/frontend/src/main.ts`
|
||||
- `xinxin2/frontend/src/router/index.ts`
|
||||
- `xinxin2/backend/app/api/auth.py`
|
||||
- `xinxin2/backend/app/main.py`
|
||||
- `xinxin2/start-local-frontend.ps1`
|
||||
- `xinxin2/start-local-dev.ps1`
|
||||
|
||||
### 完成部署切换后可停
|
||||
|
||||
- `xinxin2/frontend/Dockerfile`
|
||||
- `xinxin2/frontend/src/views/WorkspaceView.vue`
|
||||
- `xinxin2/frontend/src/views/AdminView.vue`
|
||||
- `xinxin2/backend/app/api/groups.py`
|
||||
- `xinxin2/backend/app/api/files.py`
|
||||
- `xinxin2/backend/app/api/integration.py`
|
||||
- `xinxin2/backend/app/tasks.py`
|
||||
- `xinxin2/backend/worker.py`
|
||||
- `xinxin2/docker-compose.yml`
|
||||
|
||||
### 暂时保留参考
|
||||
|
||||
- `xinxin2/backend/edkb_system/*`
|
||||
- `xinxin2/backend/tests/*`
|
||||
- `xinxin2/project-governance/*`
|
||||
- `xinxin2/README.md`
|
||||
- `xinxin2/EXTERNAL-INTEGRATION-API.md`
|
||||
|
||||
## 建议新增的主平台收尾工作
|
||||
|
||||
为了真正完成下线,主平台还建议补这几项:
|
||||
|
||||
- 观察主平台 `worker_kb` 切换后一段时间的稳定性
|
||||
- 为知识库模块补部署文档(见 `docs/knowledge_base_runtime_deploy.md`)
|
||||
- 在主平台 README 或 docs 中补本地运行步骤
|
||||
- 继续迁移 `xinxin2` 测试到主平台 `backend/tests/`
|
||||
- 补一版“切换完成后的 smoke checklist”
|
||||
|
||||
## 切换完成判定
|
||||
|
||||
满足以下条件,可认为 `xinxin2` 已完成业务下线:
|
||||
|
||||
- 用户只从 `hxops&xinxin` 登录和使用知识库
|
||||
- 聊天侧 source 文件映射只访问主平台 integration API
|
||||
- 文档上传、clean、sync 都由主平台完成
|
||||
- 主平台部署已具备所需 worker/存储能力
|
||||
- `xinxin2` 的外部访问流量归零
|
||||
|
||||
## 当前建议
|
||||
|
||||
下一步优先做:
|
||||
|
||||
1. 按 `docs/knowledge_base_runtime_deploy.md` 完成一轮主平台知识库运行时冒烟验证
|
||||
2. 观察主平台 `worker_kb`、`/api/integration/*` 与文件下载链路是否稳定
|
||||
3. 再决定是否正式停掉 `xinxin2` 的 `api/worker/frontend`
|
||||
@@ -1,238 +0,0 @@
|
||||
# `xinxin2` 正式下线执行文档
|
||||
|
||||
## 文档目标
|
||||
|
||||
用于记录 `xinxin2` 向主平台 `hxops&xinxin` 完成迁移后的正式下线执行方案、当前实机执行结果、回滚预案与生产切换注意事项。
|
||||
|
||||
## 当前结论
|
||||
|
||||
当前主平台 `hxops&xinxin` 已实机跑通以下完整链路:
|
||||
|
||||
- 知识库分组创建
|
||||
- 文档创建
|
||||
- 文件上传
|
||||
- 自动 `clean`
|
||||
- 同步到本地 Dify
|
||||
- `/api/integration/files/*`
|
||||
- `/api/integration/dify-file`
|
||||
- 源文件与 Markdown 下载
|
||||
|
||||
本地环境当前结论:
|
||||
|
||||
- `xinxin2` 已满足下线条件
|
||||
- 主平台已具备替代 `xinxin2` 的完整知识库主链路能力
|
||||
- 生产环境正式切换前,仅需把本地测试用公开地址替换为真实可访问域名
|
||||
|
||||
## 本次实机执行结果
|
||||
|
||||
### 1. 主平台状态
|
||||
|
||||
当前正在运行:
|
||||
|
||||
- `hxops-backend`
|
||||
- `hxops-kb-worker`
|
||||
- `hxops-frontend`
|
||||
- `hxops-kb-redis`
|
||||
|
||||
当前已验证:
|
||||
|
||||
- 前端访问正常:`http://127.0.0.1:8890/`
|
||||
- 后端访问正常:`http://127.0.0.1:5002/`
|
||||
- 知识库上传/清洗/同步/集成接口全部通过
|
||||
|
||||
### 2. Dify 测试配置
|
||||
|
||||
当前本地测试使用:
|
||||
|
||||
- `DIFY_API_BASE=http://host.docker.internal/v1`
|
||||
- `DIFY_API_KEY=dataset-EYE6BMiJcVQ7OJEbob2K4gM1`
|
||||
|
||||
说明:
|
||||
|
||||
- 由于主平台运行在 Docker 容器中,容器内访问宿主机 Dify 不能使用 `localhost`
|
||||
- 本地测试时应使用 `http://host.docker.internal/v1`
|
||||
|
||||
### 3. Public Base 测试配置
|
||||
|
||||
当前本地测试使用:
|
||||
|
||||
- `WECOM_PUBLIC_BASE_URL=http://127.0.0.1:5002`
|
||||
|
||||
作用:
|
||||
|
||||
- 让 `/api/integration/*` 返回的下载地址直接指向本机可访问的主平台后端
|
||||
|
||||
说明:
|
||||
|
||||
- 该值只适用于本地验证
|
||||
- 生产环境必须替换为真实公网或内网可访问域名
|
||||
|
||||
### 4. `xinxin2` 当前运行状态
|
||||
|
||||
本机实机检查结果:
|
||||
|
||||
- `docker compose ps -a`(在 `xinxin2` 目录执行)为空
|
||||
- `http://127.0.0.1:8891/` 当前不可达
|
||||
|
||||
结论:
|
||||
|
||||
- 当前机器上不存在正在运行的 `xinxin2` Docker 前端/API/worker 实例
|
||||
- 因此“停止旧服务”这一步在本机已是完成状态
|
||||
|
||||
## 正式下线执行顺序
|
||||
|
||||
### 第一步:统一入口
|
||||
|
||||
执行项:
|
||||
|
||||
- 停止 `xinxin2` 独立前端入口
|
||||
- 用户与管理员统一从 `hxops&xinxin` 登录
|
||||
- 不再对外暴露 `8891` 知识库前端入口
|
||||
|
||||
判定标准:
|
||||
|
||||
- 用户只从主平台访问知识库
|
||||
- `8891` 无用户流量
|
||||
|
||||
### 第二步:统一调用地址
|
||||
|
||||
执行项:
|
||||
|
||||
- 外部调用方统一切换到主平台 `/api/integration/*`
|
||||
- 聊天侧继续使用主平台本地 integration API
|
||||
|
||||
判定标准:
|
||||
|
||||
- 旧 `xinxin2` integration API 流量归零
|
||||
|
||||
### 第三步:统一运行时
|
||||
|
||||
执行项:
|
||||
|
||||
- 使用主平台 `hxops-backend`
|
||||
- 使用主平台 `hxops-kb-worker`
|
||||
- 使用主平台知识库存储卷
|
||||
- 使用主平台知识库 Dify 配置
|
||||
|
||||
判定标准:
|
||||
|
||||
- 上传、`clean`、`sync_dify` 都在主平台成功完成
|
||||
|
||||
### 第四步:停止旧后端
|
||||
|
||||
执行项:
|
||||
|
||||
- 停止 `xinxin2` worker
|
||||
- 停止 `xinxin2` API
|
||||
- 停止 `xinxin2` 旧 compose 服务
|
||||
|
||||
判定标准:
|
||||
|
||||
- 主平台 API、worker、integration API 持续正常
|
||||
- 旧服务无有效访问流量
|
||||
|
||||
## 当前机器的执行状态
|
||||
|
||||
### 已完成
|
||||
|
||||
- 主平台知识库功能迁移
|
||||
- 主平台 Docker 运行时接入
|
||||
- 主平台 Dify 测试配置接入
|
||||
- 主平台 integration API 验证
|
||||
- `xinxin2` 旧前端入口不可达
|
||||
- `xinxin2` compose 无运行实例
|
||||
|
||||
### 当前无需再执行的停机动作
|
||||
|
||||
在这台机器上,以下动作已无需再做:
|
||||
|
||||
- `docker compose stop` `xinxin2` 前端
|
||||
- `docker compose stop` `xinxin2` API
|
||||
- `docker compose stop` `xinxin2` worker
|
||||
|
||||
原因:
|
||||
|
||||
- 当前本机 `xinxin2` 本就未运行
|
||||
|
||||
## 回滚预案
|
||||
|
||||
若主平台切换后出现异常,可按以下顺序回滚:
|
||||
|
||||
1. 恢复 `xinxin2` 前端入口
|
||||
2. 恢复 `xinxin2` API
|
||||
3. 恢复 `xinxin2` worker
|
||||
4. 将调用方 integration 地址切回旧服务
|
||||
5. 验证旧链路恢复后,再排查主平台问题
|
||||
|
||||
## 回滚时禁止直接删除
|
||||
|
||||
- `xinxin2` 数据库
|
||||
- `xinxin2` 历史文件目录
|
||||
- `xinxin2/docker-compose.yml`
|
||||
- `xinxin2/backend/tests/*`
|
||||
- `xinxin2/backend/edkb_system/*`
|
||||
|
||||
## 生产环境切换前必改项
|
||||
|
||||
### 1. `WECOM_PUBLIC_BASE_URL`
|
||||
|
||||
本地测试值:
|
||||
|
||||
- `http://127.0.0.1:5002`
|
||||
|
||||
生产要求:
|
||||
|
||||
- 替换为真实公网或内网可访问域名
|
||||
|
||||
### 2. `DIFY_API_BASE`
|
||||
|
||||
本地测试值:
|
||||
|
||||
- `http://host.docker.internal/v1`
|
||||
|
||||
生产要求:
|
||||
|
||||
- 替换为生产环境 Dify 可访问地址
|
||||
|
||||
### 3. `DIFY_API_KEY`
|
||||
|
||||
本地测试值:
|
||||
|
||||
- `dataset-EYE6BMiJcVQ7OJEbob2K4gM1`
|
||||
|
||||
生产要求:
|
||||
|
||||
- 替换为生产可用的 Dify Key
|
||||
|
||||
### 4. 其他关键生产变量
|
||||
|
||||
切换前同时确认:
|
||||
|
||||
- `DATABASE_URL`
|
||||
- `SECRET_KEY`
|
||||
- `KB_STORAGE_ROOT`
|
||||
- `INTEGRATION_API_MODE=local`
|
||||
|
||||
## 生产切换后最小冒烟清单
|
||||
|
||||
建议逐项验证:
|
||||
|
||||
1. 登录主平台知识库工作台
|
||||
2. 新建分组
|
||||
3. 新建文档
|
||||
4. 上传 `txt` 或 `md`
|
||||
5. 确认 `clean` 成功
|
||||
6. 触发同步到 Dify
|
||||
7. 调用 `/api/integration/dify-file`
|
||||
8. 点击下载源文件与 Markdown
|
||||
|
||||
## 最终结论
|
||||
|
||||
在当前本地环境中:
|
||||
|
||||
- `xinxin2` 已可正式进入下线状态
|
||||
- 主平台 `hxops&xinxin` 已完成替代
|
||||
|
||||
在生产环境中:
|
||||
|
||||
- 只要把本地测试配置替换为真实生产配置,即可按本执行文档推进正式切换
|
||||
Binary file not shown.
@@ -1,13 +0,0 @@
|
||||
ERP\_VIEW\_USER.ERP\_AZP\_FILE\_V - 营运中心主档
|
||||
|
||||
ERP\_VIEW\_USER.ERP\_GEM\_FILE\_V - 部门名称资料档
|
||||
|
||||
ERP\_VIEW\_USER.ERP\_GEN\_FILE\_V - 员工姓名档案
|
||||
|
||||
ERP\_VIEW\_USER.ERP\_PMC\_FILE\_V - 供应商基础资料档
|
||||
|
||||
ERP\_VIEW\_USER.ERP\_FAB\_FILE\_V - 固定资产主要类型档
|
||||
|
||||
ERP\_VIEW\_USER.ERP\_FAF\_FILE\_V - 固定资产存放位置档
|
||||
|
||||
ERP\_VIEW\_USER.ERP\_FAJ\_FILE\_V - 固定资产资料档
|
||||
@@ -1,109 +0,0 @@
|
||||
# 请假单表字段整理
|
||||
|
||||
## 说明
|
||||
- 本文档根据当前提供的 3 张 OA 表单字段截图人工整理。
|
||||
- 字段名称、显示名、表现形式、字段类型、显示顺序以截图可见内容为准。
|
||||
- 个别字段如存在截图模糊、顺序重复或命名识别误差,建议后续以 OA 后台字段配置页再次核对。
|
||||
- 本文档重点用于前端请假表单、后端字段映射、OA 提交流程对接时参考。
|
||||
|
||||
## 主表字段
|
||||
| 字段名称 | 字段显示名 | 字段位置 | 表现形式 | 字段类型 | 显示顺序 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `txhjss` | 调休合计时长 | 主表字段 | 单行文本框 | 浮点数 | `0.00` |
|
||||
| `kqnjts` | 可请年假天数 | 主表字段 | 单行文本框 | 浮点数 | `0.00` |
|
||||
| `txrq` | 调休日期 | 主表字段 | 浏览按钮 | 日期 | `0.00` |
|
||||
| `njsxsj` | 年假生效时间 | 主表字段 | 单行文本框 | 文本 | `0.00` |
|
||||
| `lcbh` | 流程编号 | 主表字段 | 单行文本框 | 文本 | `1.00` |
|
||||
| `tdrgs` | 填单人公司 | 主表字段 | 浏览按钮 | 分部 | `2.00` |
|
||||
| `tdrbm` | 填单人部门 | 主表字段 | 浏览按钮 | 部门 | `3.00` |
|
||||
| `tdrgh` | 填单人工号 | 主表字段 | 单行文本框 | 文本 | `4.00` |
|
||||
| `sqrgh` | 申请人工号 | 主表字段 | 单行文本框 | 文本 | `5.00` |
|
||||
| `tdrxm` | 填单人姓名 | 主表字段 | 浏览按钮 | 人力资源 | `6.00` |
|
||||
| `sqrxm` | 申请人姓名 | 主表字段 | 浏览按钮 | 人力资源 | `7.00` |
|
||||
| `dlrgh` | 代理人工号 | 主表字段 | 单行文本框 | 文本 | `10.00` |
|
||||
| `dlrxm` | 代理人姓名 | 主表字段 | 浏览按钮 | 人力资源 | `11.00` |
|
||||
| `kssj` | 开始时间 | 主表字段 | 浏览按钮 | 日期 | `13.00` |
|
||||
| `kssk` | 开始时刻 | 主表字段 | 浏览按钮 | 时间 | `14.00` |
|
||||
| `jssj` | 结束时间 | 主表字段 | 浏览按钮 | 日期 | `15.00` |
|
||||
| `jssk` | 结束时刻 | 主表字段 | 浏览按钮 | 时间 | `16.00` |
|
||||
| `qjsc` | 请假时长 | 主表字段 | 单行文本框 | 浮点数 | `17.00` |
|
||||
| `sfwgs` | 是否为工伤 | 主表字段 | 选择框 | 是否 | `18.00` |
|
||||
| `bz` | 备注 | 主表字段 | 多行文本框 | 多行文本框 | `19.00` |
|
||||
| `xglc` | 相关流程 | 主表字段 | 浏览按钮 | 流程 | `20.00` |
|
||||
| `xgfj` | 相关附件 | 主表字段 | 附件上传 | 上传文件 | `21.00` |
|
||||
| `tdrzw` | 填单人职务 | 主表字段 | 浏览按钮 | 岗位 | `22.00` |
|
||||
| `sqrgs` | 申请人公司 | 主表字段 | 浏览按钮 | 分部 | `22.00` |
|
||||
| `sqrzw` | 申请人职务 | 主表字段 | 浏览按钮 | 岗位 | `23.00` |
|
||||
| `sqrbm` | 申请人部门 | 主表字段 | 浏览按钮 | 部门 | `23.00` |
|
||||
| `jb` | 级别 | 主表字段 | 浏览按钮 | 自定义单选 | `24.00` |
|
||||
| `jbbh` | 级别编号 | 主表字段 | 单行文本框 | 文本 | `24.00` |
|
||||
| `dlrlogid` | 代理人登录ID | 主表字段 | 单行文本框 | 文本 | `28.00` |
|
||||
| `sfwc` | 是否外出 | 主表字段 | 选择框 | 是否 | `29.00` |
|
||||
| `qc` | 厂区 | 主表字段 | 选择框 | 一厂/二厂 | `30.00` |
|
||||
| `fjf` | 上传附件否 | 主表字段 | 选择框 | 是否 | `31.00` |
|
||||
| `chsm` | 出差说明标题 | 主表字段 | 特殊字段 | 自定义链接 | `32.00` |
|
||||
| `chglbf` | 出差管理办法 | 主表字段 | 特殊字段 | 自定义链接 | `33.00` |
|
||||
| `kqyjts` | 可请育儿假时数 | 主表字段 | 单行文本框 | 浮点数 | `34.00` |
|
||||
| `chsmsa` | 出差说明其四 | 主表字段 | 特殊字段 | 自定义链接 | `36.00` |
|
||||
| `pljqsm` | 批量请假说明 | 主表字段 | 特殊字段 | 自定义链接 | `36.00` |
|
||||
|
||||
## 明细字段
|
||||
| 字段名称 | 字段显示名 | 字段位置 | 表现形式 | 字段类型 | 显示顺序 |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `gh` | 工号 | 明细字段 | 单行文本框 | 文本 | `1.00` |
|
||||
| `bh` | 编号 | 明细字段 | 单行文本框 | 文本 | `2.00` |
|
||||
| `idi` | ID | 明细字段 | 单行文本框 | 文本 | `3.00` |
|
||||
| `jbrq` | 加班日期 | 明细字段 | 单行文本框 | 文本 | `4.00` |
|
||||
| `jblx` | 加班类型 | 明细字段 | 单行文本框 | 文本 | `5.00` |
|
||||
| `jbss` | 加班时数 | 明细字段 | 单行文本框 | 浮点数 | `6.00` |
|
||||
| `ytss` | 已调时数 | 明细字段 | 单行文本框 | 浮点数 | `7.00` |
|
||||
| `wtss` | 未调时数 | 明细字段 | 单行文本框 | 浮点数 | `8.00` |
|
||||
| `txss` | 调休时数 | 明细字段 | 单行文本框 | 浮点数 | `9.00` |
|
||||
| `spzss` | 审批中时数 | 明细字段 | 单行文本框 | 浮点数 | `10.00` |
|
||||
| `kyss` | 可用时数 | 明细字段 | 单行文本框 | 浮点数 | `11.00` |
|
||||
| `txrq` | 调休日期 | 明细字段 | 浏览按钮 | 日期 | `1.00` |
|
||||
| `ksrq` | 开始日期 | 明细字段 | 浏览按钮 | 日期 | `2.00` |
|
||||
| `kssj` | 开始时间 | 明细字段 | 浏览按钮 | 时间 | `3.00` |
|
||||
| `jsrq` | 结束日期 | 明细字段 | 浏览按钮 | 日期 | `4.00` |
|
||||
| `jssj` | 结束时间 | 明细字段 | 浏览按钮 | 时间 | `5.00` |
|
||||
| `qjsc` | 请假时长 | 明细字段 | 单行文本框 | 浮点数 | `6.00` |
|
||||
|
||||
## 当前前端已接字段
|
||||
以下字段已在当前聊天请假表单中接入或展示:
|
||||
|
||||
| 前端字段 | 含义 | 备注 |
|
||||
| --- | --- | --- |
|
||||
| `applicantName` | 申请人 | 当前登录用户姓名 |
|
||||
| `employeeId` | 工号 | 当前登录用户工号 |
|
||||
| `applyTime` | 申请时间 | 默认当前时间 |
|
||||
| `fillerName` | 填单人 | 默认当前登录用户姓名 |
|
||||
| `agentUid` | 代理人 UID | 当前先为模拟选择数据 |
|
||||
| `agentEmployeeId` | 代理人工号 | 当前先为模拟选择数据 |
|
||||
| `agentName` | 代理人姓名 | 当前先为模拟选择数据 |
|
||||
| `leaveType` | 假别 | 下拉选择 |
|
||||
| `startTime` | 开始时间 | 前端日期时间控件 |
|
||||
| `endTime` | 结束时间 | 前端日期时间控件 |
|
||||
| `durationHours` | 时长 | 根据开始/结束时间自动计算 |
|
||||
| `isOutOfOffice` | 是否外出 | 当前默认 `否` |
|
||||
| `isWorkInjury` | 是否为工伤 | 当前默认 `否` |
|
||||
|
||||
## 对接建议
|
||||
- 后端对接 OA 创建请假单时,建议优先确认主表字段中的以下映射关系:
|
||||
- `tdrgh` / `tdrxm`:填单人工号、填单人姓名
|
||||
- `sqrgh` / `sqrxm`:申请人工号、申请人姓名
|
||||
- `dlrgh` / `dlrxm` / `dlrlogid`:代理人信息
|
||||
- `kssj` / `kssk` / `jssj` / `jssk`:开始结束日期时间
|
||||
- `qjsc`:请假时长
|
||||
- `sfwgs`:是否为工伤
|
||||
- `sfwc`:是否外出
|
||||
- `bz`:备注
|
||||
- 如需支持调休、年假、育儿假等复杂场景,应继续确认:
|
||||
- `txhjss`
|
||||
- `kqnjts`
|
||||
- `kqyjts`
|
||||
- 明细字段中的调休日期、加班日期、可用时数等是否参与提交流程
|
||||
|
||||
## 待确认项
|
||||
- `chsmsa` 的显示名截图较模糊,需在 OA 后台再次确认。
|
||||
- 部分字段显示顺序存在相同编号,可能是 OA 配置本身如此,也可能为截图显示问题。
|
||||
- 主表中的 `开始时间/结束时间` 与明细中的 `开始日期/开始时间/结束日期/结束时间` 是否同时必填,需要结合真实流程配置确认。
|
||||
@@ -1,101 +0,0 @@
|
||||
LET l_str1 = "<?xml version='1.0' encoding='utf-8'?>\n",
|
||||
"<requestinfo>\n",
|
||||
"<maintable>\n",
|
||||
"<fields>sqrgh,kpr,kpbm,zt,cb,kpdh,khbh,khqm,kprq,sz,hl,bz,khdzjdh,khsh,yjskrq,slhj,ybsqjehj,ybsehj,ybhsjehj,bbsqjehj,bbsehj,bbhsjehj,hth</fields>\n",
|
||||
"<creater>",l_tc_hratud03,"</creater>\n", #创建人id
|
||||
"<wfid>652</wfid>\n", #工作流idworkflow=652(请假固定)
|
||||
"<level>0</level>\n", #紧急程度
|
||||
"<requestname>",l_rn,"</requestname>\n", #流程标题
|
||||
"<sqrgh>",l_omf.omfuser,"</sqrgh>\n", #申请人工号
|
||||
"<kpr>",l_tc_hratud03,"</kpr>\n", #申请人姓名
|
||||
"<kpbm>",l_tc_hraoud03,"</kpbm>\n", #申请人部门
|
||||
"<zt>",g_plant,"</zt>\n", #账套
|
||||
"<cb>",l_zt,"</cb>\n", #厂别
|
||||
"<kpdh>",p_no,"</kpdh>\n", #开票单号
|
||||
"<khbh>",l_omf.omf05,"</khbh>\n", #客户编号
|
||||
"<khqm>",l_omf.occ18,"</khqm>\n", #客户全名
|
||||
"<kprq>",l_omf.omf31,"</kprq>\n", #开票日期
|
||||
"<sz>",l_omf.omf06,"</sz>\n", #税种
|
||||
"<hl>",l_omf.omf22,"</hl>\n", #汇率
|
||||
"<bz>",l_omf.omf07,"</bz>\n", #币种
|
||||
"<khdzjdh>",l_omf.occ241,"</khdzjdh>\n", #客户地址
|
||||
"<khsh>",l_omf.occ11,"</khsh>\n", #客户税号
|
||||
"<yjskrq>",l_omf.omfud02,"</yjskrq>\n", #预计收款日期
|
||||
"<slhj>",l_omf.omf16_sum,"</slhj>\n", #数量合计
|
||||
"<ybsqjehj>",l_omf.omf29_sum,"</ybsqjehj>\n", #原币税前金额合计
|
||||
"<ybsehj>",l_omf.omf29x_sum,"</ybsehj>\n", #原币税额合计
|
||||
"<ybhsjehj>",l_omf.omf29t_sum,"</ybhsjehj>\n", #原币含税金额合计
|
||||
"<bbsqjehj>",l_omf.omf19_sum,"</bbsqjehj>\n", #本币税前金额合计
|
||||
"<bbsehj>",l_omf.omf19x_sum,"</bbsehj>\n", #本币税额合计
|
||||
"<bbhsjehj>",l_omf.omf19t_sum,"</bbhsjehj>\n", #本币含税金额合计
|
||||
"<hth>",l_omf.omf02,"</hth>\n", #合同号
|
||||
"</maintable>\n" #主表 END
|
||||
|
||||
LET l_str1 =l_str1," </requestinfo>\n"
|
||||
|
||||
CALL createwflc(l_str1) RETURNING l_str, l_str2
|
||||
IF l_str<0 THEN
|
||||
IF l_str = -1 THEN
|
||||
LET l_msg='创建流程失败'
|
||||
END IF
|
||||
IF l_str = -2 THEN
|
||||
LET l_msg = '用户没有流程创建权限'
|
||||
END IF
|
||||
IF l_str = -3 THEN
|
||||
LET l_msg = '创建流程基本信息失败'
|
||||
END IF
|
||||
IF l_str = -4 THEN
|
||||
LET l_msg = '保存表单主表信息失败'
|
||||
END IF
|
||||
IF l_str = -5 THEN
|
||||
LET l_msg = '更新紧急程度失败'
|
||||
END IF
|
||||
IF l_str = -6 THEN
|
||||
LET l_msg = '流程操作者失败'
|
||||
END IF
|
||||
IF l_str = -7 THEN
|
||||
LET l_msg = '流转至下一节点失败'
|
||||
END IF
|
||||
IF l_str = -8 THEN
|
||||
LET l_msg = '节点附加操作失败'
|
||||
END IF
|
||||
CALL cl_err(l_msg,'!',1)
|
||||
LET l_str = "\n ",g_today," ",TIME,"报错信息 :",l_msg
|
||||
LET g_success = "N"
|
||||
ELSE
|
||||
IF l_str2<=0 THEN
|
||||
IF l_str2 = 0 THEN
|
||||
LET l_msg='返回的ID为0,请联系管理员!'
|
||||
END IF
|
||||
IF l_str2 = -1 THEN
|
||||
LET l_msg='创建流程失败'
|
||||
END IF
|
||||
IF l_str2 = -2 THEN
|
||||
LET l_msg = '用户没有流程创建权限'
|
||||
END IF
|
||||
IF l_str2 = -3 THEN
|
||||
LET l_msg = '创建流程基本信息失败'
|
||||
END IF
|
||||
IF l_str2 = -4 THEN
|
||||
LET l_msg = '保存表单主表信息失败'
|
||||
END IF
|
||||
IF l_str2 = -5 THEN
|
||||
LET l_msg = '更新紧急程度失败'
|
||||
END IF
|
||||
IF l_str2 = -6 THEN
|
||||
LET l_msg = '流程操作者失败'
|
||||
END IF
|
||||
IF l_str2 = -7 THEN
|
||||
LET l_msg = '流转至下一节点失败'
|
||||
END IF
|
||||
IF l_str2 = -8 THEN
|
||||
LET l_msg = '节点附加操作失败'
|
||||
END IF
|
||||
CALL cl_err(l_msg,'!',1)
|
||||
LET l_str2 = "\n ",g_today," ",TIME,"报错信息 :",l_msg
|
||||
LET g_success = "N"
|
||||
ELSE
|
||||
LET g_success = "Y"
|
||||
LET l_omfud11 = l_str2
|
||||
END IF
|
||||
END IF
|
||||
@@ -14,7 +14,7 @@ export const workspaceRoutes: RouteRecordRaw[] = [
|
||||
{
|
||||
path: 'profile',
|
||||
name: 'workspace-profile',
|
||||
component: () => import('@/features/workspace/pages/ProfilePage.vue'),
|
||||
component: () => import('@/features/user/views/UserProfilePage.vue'),
|
||||
meta: { title: '个人中心' },
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
/**
|
||||
* features/auth/api/auth.api.ts
|
||||
* 用途:封装登录、Casdoor/企微回调、注册和密码重置等认证域 HTTP 请求。
|
||||
* 依赖:shared/api/client。
|
||||
* 逻辑:auth views 与 composables 只调用本模块;后端暂保留 /api/user 路径以兼容既有接口。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
|
||||
export interface PasswordLoginInput {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
/** 使用当前认证模式的登录端点完成用户名密码认证。 */
|
||||
export const loginWithPassword = (api: string, input: PasswordLoginInput) =>
|
||||
requestJson<Record<string, unknown>>(api, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
|
||||
/** 将 Casdoor 授权码兑换为 HXOPS 登录会话。 */
|
||||
export const loginWithCasdoorCode = (api: string, code: string, state: string | null) =>
|
||||
requestJson<Record<string, unknown>>(api, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code, state }),
|
||||
});
|
||||
|
||||
/** 读取 Casdoor 授权地址及后端签发的 state。 */
|
||||
export const getCasdoorAuthorizeUrl = (api: string, query: URLSearchParams) =>
|
||||
requestJson<{ url?: string; state?: string }>(`${api}?${query.toString()}`);
|
||||
|
||||
/** 将企微授权码兑换为 HXOPS 登录会话。 */
|
||||
export const loginWithWecomCode = (api: string, code: string, state: string | null) =>
|
||||
requestJson<Record<string, unknown>>(api, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code, state }),
|
||||
});
|
||||
|
||||
/** 读取企微授权地址及后端签发的 state。 */
|
||||
export const getWecomAuthorizeUrl = (api: string, redirectUri: string) =>
|
||||
requestJson<{ url?: string; state?: string }>(`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`);
|
||||
|
||||
/** 完成企微首次登录所需的本地用户匹配。 */
|
||||
export const completeWecomBind = (api: string, input: { binding_token: string; field: string; value: string }) =>
|
||||
requestJson<Record<string, unknown>>(api, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(input),
|
||||
});
|
||||
|
||||
/** 从登录页发起企业微信密码重置通知。 */
|
||||
export const requestPasswordResetByWecom = (employeeId: string, username: string) =>
|
||||
requestJson('/api/user/reset-password-by-wecom', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ employee_id: employeeId, username }),
|
||||
});
|
||||
|
||||
/** 使用重置链接中的 token 设置新密码。 */
|
||||
export const confirmPasswordReset = (token: string, newPassword: string) =>
|
||||
requestJson('/api/user/reset-password-confirm', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token, new_password: newPassword }),
|
||||
});
|
||||
|
||||
/** 注册 HXOPS 用户;后端负责后续 Casdoor 用户同步。 */
|
||||
export const registerUser = (form: Record<string, unknown>) =>
|
||||
requestJson('/api/user/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
@@ -1,57 +0,0 @@
|
||||
/**
|
||||
* features/auth/api/user.api.ts
|
||||
* 用户域 HTTP API:资料、请假、密码重置、Agent 列表等。
|
||||
*/
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { requestJson } from '@/shared/api/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 resetPasswordByWecom = (employeeId: string, username: string) =>
|
||||
requestJson('/api/user/reset-password-by-wecom', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ employee_id: employeeId, username }),
|
||||
});
|
||||
|
||||
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());
|
||||
|
||||
export const listAgentGuides = (agentId: number) => requestJson<any[]>(`/api/agents/${agentId}/guides`, auth());
|
||||
@@ -2,7 +2,7 @@
|
||||
* features/auth/composables/useLoginAuth.ts
|
||||
*
|
||||
* 用途:封装登录表单、记住我偏好、企微/Casdoor OAuth 回调、注册与找回密码逻辑。
|
||||
* 依赖:shared/utils/auth、requestJson、WeCom/Casdoor 工具函数。
|
||||
* 依赖:shared/utils/auth、auth.api、WeCom/Casdoor 工具函数。
|
||||
* 逻辑:密码登录成功后根据“记住我”同步本地登录态与 remembered username/password;
|
||||
* OAuth 登录仅负责认证,不自动写入 remember 偏好,避免用户未明确选择时持久化登录页账号。
|
||||
*/
|
||||
@@ -22,7 +22,17 @@ import {
|
||||
saveRememberedLoginPreference,
|
||||
saveRememberedLoginProfile,
|
||||
} from '@/shared/utils/auth';
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import {
|
||||
completeWecomBind,
|
||||
getCasdoorAuthorizeUrl,
|
||||
getWecomAuthorizeUrl,
|
||||
loginWithCasdoorCode,
|
||||
loginWithPassword,
|
||||
loginWithWecomCode,
|
||||
registerUser,
|
||||
requestPasswordResetByWecom,
|
||||
} from '../api/auth.api';
|
||||
import { DEFAULT_POST_LOGIN_AGENT_ID } from '@/features/workspace/types/workspace.types';
|
||||
import type { WecomBindPromptState, WecomLoginDialogContent } from '@/features/workspace/types/workspace.types';
|
||||
import type { LoginDeps } from './login.deps';
|
||||
@@ -127,11 +137,7 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await requestJson('/api/user/reset-password-by-wecom', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ employee_id: employeeId, username }),
|
||||
});
|
||||
await requestPasswordResetByWecom(employeeId, username);
|
||||
msg.success(t('login.passwordResetWecomSent'));
|
||||
showForgotPasswordModal.value = false;
|
||||
forgotPasswordForm.value = { employee_id: '', username: '' };
|
||||
@@ -173,13 +179,9 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
|
||||
const loginApi = isCasdoorMode
|
||||
? (config.auth?.casdoor?.passwordLoginApi || '/api/user/casdoor/password-login')
|
||||
: '/api/user/login';
|
||||
const user = await requestJson<Record<string, unknown>>(loginApi, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
username: loginUsername.value.trim(),
|
||||
password: loginPassword.value,
|
||||
}),
|
||||
const user = await loginWithPassword(loginApi, {
|
||||
username: loginUsername.value.trim(),
|
||||
password: loginPassword.value,
|
||||
});
|
||||
|
||||
persistLoginUser(user);
|
||||
@@ -221,11 +223,7 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
|
||||
}
|
||||
try {
|
||||
const api = config.auth.casdoor.loginApi || '/api/user/casdoor/login';
|
||||
const data = await requestJson<Record<string, unknown>>(api, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code, state }),
|
||||
});
|
||||
const data = await loginWithCasdoorCode(api, code, state);
|
||||
persistLoginUser(data);
|
||||
sessionStorage.removeItem('hxops_casdoor_state');
|
||||
await completeOAuthLogin();
|
||||
@@ -267,7 +265,7 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
|
||||
const qs = new URLSearchParams({ redirect_uri: redirectUri, default_provider: 'wecom' });
|
||||
const hint = (config.auth.casdoor as { wecomProviderHint?: string }).wecomProviderHint?.trim();
|
||||
if (hint) qs.set('provider_hint', hint);
|
||||
const data = await requestJson<{ url?: string; state?: string }>(`${api}?${qs.toString()}`);
|
||||
const data = await getCasdoorAuthorizeUrl(api, qs);
|
||||
if (!data?.url) {
|
||||
msg.error(t('login.wecomStartFailed'));
|
||||
return;
|
||||
@@ -280,9 +278,7 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
|
||||
const callbackPath = wecomCfg.callbackPath || '/login';
|
||||
const redirectUri = `${window.location.origin}${callbackPath}`;
|
||||
const api = wecomCfg.authorizeApi || '/api/user/wecom/authorize-url';
|
||||
const data = await requestJson<{ url?: string; state?: string }>(
|
||||
`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`,
|
||||
);
|
||||
const data = await getWecomAuthorizeUrl(api, redirectUri);
|
||||
if (!data?.url) {
|
||||
msg.error(t('login.wecomStartFailed'));
|
||||
return;
|
||||
@@ -336,14 +332,10 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
|
||||
wecomBindPrompt.value.error = '';
|
||||
try {
|
||||
const api = config.auth.wecom.completeBindApi || '/api/user/wecom/complete-bind';
|
||||
const data = await requestJson<Record<string, unknown>>(api, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
binding_token: wecomBindPrompt.value.binding_token,
|
||||
field: wecomBindPrompt.value.field,
|
||||
value: wecomBindPrompt.value.value.trim(),
|
||||
}),
|
||||
const data = await completeWecomBind(api, {
|
||||
binding_token: wecomBindPrompt.value.binding_token,
|
||||
field: wecomBindPrompt.value.field,
|
||||
value: wecomBindPrompt.value.value.trim(),
|
||||
});
|
||||
wecomLoginDialog.value = null;
|
||||
persistLoginUser(data);
|
||||
@@ -389,11 +381,7 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
|
||||
isWecomLoggingIn.value = true;
|
||||
try {
|
||||
const api = config.auth.wecom.loginApi || '/api/user/wecom/login';
|
||||
const data = await requestJson<Record<string, unknown>>(api, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code, state }),
|
||||
});
|
||||
const data = await loginWithWecomCode(api, code, state);
|
||||
wecomLoginDialog.value = null;
|
||||
persistLoginUser(data);
|
||||
sessionStorage.removeItem('hxops_wecom_state');
|
||||
@@ -434,11 +422,7 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await requestJson('/api/user/register', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
await registerUser(form);
|
||||
msg.success(t('register.success'));
|
||||
showRegisterModal.value = false;
|
||||
registerForm.value = {
|
||||
|
||||
@@ -1,18 +1,7 @@
|
||||
/**
|
||||
* features/auth/index.ts
|
||||
* 认证 feature 对外导出:store、登录 composable、用户 API。
|
||||
* 认证 feature 对外导出:store、登录 composable 与认证 API。
|
||||
*/
|
||||
export { useAuthStore, bindAuthStoreSync } from './stores/auth.store';
|
||||
export { useLogin } from './composables/useLogin';
|
||||
export {
|
||||
getUserProfile,
|
||||
getLeaveBalance,
|
||||
submitLeaveWorkflow,
|
||||
resetPasswordByWecom,
|
||||
resetPasswordConfirm,
|
||||
getUserAgent,
|
||||
listUserAgents,
|
||||
listAgentGuides,
|
||||
type LeaveBalanceResult,
|
||||
type LeaveWorkflowSubmitResult,
|
||||
} from './api/user.api';
|
||||
export * from './api/auth.api';
|
||||
@@ -2,7 +2,7 @@
|
||||
/**
|
||||
* features/auth/views/ResetPasswordView.vue
|
||||
* 企微 textcard / 邮件链接重置密码页(/reset-password?token=...)。
|
||||
* 依赖:user.api resetPasswordConfirm、vue-i18n、MinimalShell。
|
||||
* 依赖:auth.api confirmPasswordReset、vue-i18n、MinimalShell。
|
||||
* 逻辑:校验 token 与两次密码一致后调 confirm 接口,成功后跳转 /login。
|
||||
*/
|
||||
import { onMounted, ref } from 'vue';
|
||||
@@ -10,7 +10,7 @@ import { useRoute, useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Lock, AlertCircle, CheckCircle } from 'lucide-vue-next';
|
||||
import MinimalShell from '@/shared/layouts/MinimalShell.vue';
|
||||
import { resetPasswordConfirm } from '@/features/auth/api/user.api';
|
||||
import { confirmPasswordReset } from '@/features/auth/api/auth.api';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { resolveCasdoorErrorMessage } from '@/shared/utils/casdoor';
|
||||
|
||||
@@ -65,7 +65,7 @@ onMounted(() => {
|
||||
|
||||
/**
|
||||
* 提交新密码并重置 token。
|
||||
* 核心逻辑:前端校验 → resetPasswordConfirm → 成功 3 秒后跳转登录页。
|
||||
* 核心逻辑:前端校验 → confirmPasswordReset → 成功 3 秒后跳转登录页。
|
||||
*/
|
||||
const handleReset = async () => {
|
||||
if (!token.value) {
|
||||
@@ -91,7 +91,7 @@ const handleReset = async () => {
|
||||
message.value = '';
|
||||
|
||||
try {
|
||||
await resetPasswordConfirm(token.value, password.value);
|
||||
await confirmPasswordReset(token.value, password.value);
|
||||
status.value = 'success';
|
||||
message.value = t('resetPassword.successRedirect');
|
||||
setTimeout(() => {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
import { computed, ref, watch, type ComputedRef } from 'vue';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { getUserAgent, listUserAgents } from '@/features/auth/api/user.api';
|
||||
import { getUserAgent, listUserAgents } from '@/features/user';
|
||||
import { setLastChatAgentId } from '@/shared/utils/lastChatAgent';
|
||||
import { sortAgentsByCategory } from '@/shared/utils/agent-category.utils';
|
||||
import {
|
||||
@@ -51,31 +51,33 @@ export interface UseChatAgentOptions {
|
||||
chatGuides: Pick<UseChatGuidesReturn, 'loadGuides' | 'clearGuides'>;
|
||||
}
|
||||
|
||||
type ChatAgentOption = AgentRegistryFields & {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string;
|
||||
icon_url?: string;
|
||||
dify_app_type?: 'chatflow' | 'workflow';
|
||||
category?: string | null;
|
||||
sub_category?: string | null;
|
||||
sort_order?: number;
|
||||
is_aggregate?: boolean;
|
||||
directory_members?: Array<AgentRegistryFields & {
|
||||
id: number;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
icon_url?: string;
|
||||
category?: string | null;
|
||||
sub_category?: string | null;
|
||||
sort_order?: number;
|
||||
}>;
|
||||
};
|
||||
|
||||
export function useChatAgent(options: UseChatAgentOptions) {
|
||||
const { deps, currentAgentId, currentUser, chatGuides } = options;
|
||||
const { t, msg, router } = deps;
|
||||
|
||||
const currentAgent = ref<AgentRegistryFields | null>(null);
|
||||
const userAgents = ref<Array<AgentRegistryFields & {
|
||||
id: number;
|
||||
name: string;
|
||||
description: string;
|
||||
icon_url?: string;
|
||||
dify_app_type?: 'chatflow' | 'workflow';
|
||||
category?: string | null;
|
||||
sub_category?: string | null;
|
||||
sort_order?: number;
|
||||
is_aggregate?: boolean;
|
||||
directory_members?: Array<AgentRegistryFields & {
|
||||
id: number;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
icon_url?: string;
|
||||
category?: string | null;
|
||||
sub_category?: string | null;
|
||||
sort_order?: number;
|
||||
}>;
|
||||
}>>([]);
|
||||
const userAgents = ref<ChatAgentOption[]>([]);
|
||||
const showAgentPanel = ref(true);
|
||||
const selectedKb = ref(DEFAULT_KB);
|
||||
const kbOptions = [DEFAULT_KB, ERP_KB];
|
||||
@@ -162,7 +164,7 @@ export function useChatAgent(options: UseChatAgentOptions) {
|
||||
|
||||
const loadAgent = async () => {
|
||||
try {
|
||||
currentAgent.value = await getUserAgent(currentAgentId.value);
|
||||
currentAgent.value = await getUserAgent<AgentRegistryFields>(currentAgentId.value);
|
||||
await chatGuides.loadGuides();
|
||||
} catch (e) {
|
||||
if (e instanceof BusinessError && e.status === 403) {
|
||||
@@ -178,9 +180,9 @@ export function useChatAgent(options: UseChatAgentOptions) {
|
||||
|
||||
const loadUserAgents = async () => {
|
||||
try {
|
||||
const agents = await listUserAgents();
|
||||
const agents = await listUserAgents<ChatAgentOption>();
|
||||
const filtered = Array.isArray(agents)
|
||||
? agents.filter((a: any) => (a.dify_app_type || 'chatflow') === 'chatflow')
|
||||
? agents.filter((agent) => (agent.dify_app_type || 'chatflow') === 'chatflow')
|
||||
: [];
|
||||
userAgents.value = sortAgentsByCategory(filtered);
|
||||
showAgentPanel.value = userAgents.value.length > 0;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* Agent 学习之窗:指南列表加载与弹窗状态。
|
||||
*/
|
||||
import { computed, ref, type ComputedRef } from 'vue';
|
||||
import { listAgentGuides } from '@/features/auth/api/user.api';
|
||||
import { listAgentGuides } from '@/features/user';
|
||||
|
||||
export interface AgentGuide {
|
||||
id: number;
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
* - leave-result:OA 提交结果
|
||||
*/
|
||||
import { computed, type ComputedRef, type Ref } from 'vue';
|
||||
import { getUserProfile } from '@/features/auth/api/user.api';
|
||||
import { getUserProfile } from '@/features/user';
|
||||
import { canUseLeaveFeature as resolveLeaveFeatureEnabled } from '@/shared/utils/agent-registry.utils';
|
||||
import type { AgentRegistryFields } from '@/shared/utils/agent-registry.utils';
|
||||
import { LEAVE_TYPES } from '../constants/leave';
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
/** 请假(leave)子模块 barrel:纯函数 + handler 工厂 */
|
||||
export * from './leave.api';
|
||||
export * from './leaveDateTime';
|
||||
export * from './leaveDisplay';
|
||||
export * from './leaveIntent';
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* features/chat/leave/leave.api.ts
|
||||
* 用途:封装聊天请假流程的余额查询与 OA 工作流提交请求。
|
||||
* 依赖:shared/utils/auth、shared/api/client。
|
||||
* 逻辑:聊天请假表单调用本模块;后端暂保留 /api/user/leave-* 路径以兼容既有接口。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { LeaveRequestFormData } from '../types/leave.types';
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** 将聊天内确认后的请假表单提交至 OA 工作流。 */
|
||||
export const submitLeaveWorkflow = (form: LeaveRequestFormData) =>
|
||||
requestJson<LeaveWorkflowSubmitResult>('/api/user/leave-workflow/submit', {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(form),
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* 请假:表单初始数据、校验、余额断言、确认与 OA 提交。
|
||||
*/
|
||||
import { getLeaveBalance, submitLeaveWorkflow } from '@/features/auth/api/user.api';
|
||||
import { getLeaveBalance, submitLeaveWorkflow } from './leave.api';
|
||||
import { NEED_BALANCE_CHECK_TYPES } from '../constants/leave';
|
||||
import { formatLeaveBalanceNumber, getLeaveTypeLabel } from './leaveDisplay';
|
||||
import {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* features/user/api/user.api.ts
|
||||
* 用途:封装当前登录用户的资料与其可访问 Agent 查询请求。
|
||||
* 依赖:shared/utils/auth、shared/api/client。
|
||||
* 逻辑:Chat 和用户页面通过本模块读取当前用户资源,不与认证登录流程耦合。
|
||||
*/
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import type { UserProfileForm } from '../types/user-profile.types';
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
|
||||
/** 获取当前登录用户的资料及个人设置。 */
|
||||
export const getUserProfile = () => requestJson<Record<string, unknown>>('/api/user/profile', auth());
|
||||
|
||||
/** 读取个人中心编辑表单所需的完整资料。 */
|
||||
export const getEditableUserProfile = () =>
|
||||
requestJson<Partial<UserProfileForm>>('/api/user/profile', auth());
|
||||
|
||||
/** 保存当前用户允许自助编辑的资料与偏好。 */
|
||||
export const updateUserProfile = (profile: Partial<UserProfileForm>) =>
|
||||
requestJson('/api/user/profile', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify(profile),
|
||||
});
|
||||
|
||||
/** 校验当前密码后修改 Casdoor 与 HXOPS 的统一密码。 */
|
||||
export const changeUserPassword = (currentPassword: string, newPassword: string) =>
|
||||
requestJson('/api/user/change-password', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }),
|
||||
});
|
||||
|
||||
/** 获取当前用户有权访问的单个 Agent。 */
|
||||
export const getUserAgent = <T = Record<string, unknown>>(agentId: number) =>
|
||||
requestJson<T>(`/api/user/agents/${agentId}`, auth());
|
||||
|
||||
/** 获取当前用户有权访问的 Agent 列表。 */
|
||||
export const listUserAgents = <T = unknown>() => requestJson<T[]>('/api/agents', auth());
|
||||
|
||||
/** 获取当前用户有权查看的 Agent 使用指南。 */
|
||||
export const listAgentGuides = (agentId: number) =>
|
||||
requestJson<unknown[]>(`/api/agents/${agentId}/guides`, auth());
|
||||
@@ -0,0 +1,59 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/user/components/UserPasswordDialog.vue
|
||||
* 用途:呈现并提交当前用户的密码修改表单。
|
||||
* 依赖:user-profile.context 提供的资料状态和操作方法。
|
||||
* 逻辑:由工作台布局常驻渲染,用户资料页打开弹窗后在此完成密码修改。
|
||||
*/
|
||||
import { inject } from 'vue';
|
||||
import { X } from 'lucide-vue-next';
|
||||
import { USER_PROFILE_KEY } from '../composables/user-profile.context';
|
||||
|
||||
const userProfile = inject(USER_PROFILE_KEY)!;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="userProfile.CHANGE_PASSWORD_ENABLED && userProfile.showPasswordModal"
|
||||
class="dialog-overlay z-50 items-center"
|
||||
>
|
||||
<div class="dialog-panel max-w-md">
|
||||
<div class="dialog-header">
|
||||
<h3 class="section-title">{{ $t('profile.changePassword') || 'Change Password' }}</h3>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-icon-ds"
|
||||
:aria-label="$t('admin.close')"
|
||||
:disabled="userProfile.isChangingPassword"
|
||||
@click="userProfile.showPasswordModal = false"
|
||||
>
|
||||
<X class="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
<form @submit.prevent="userProfile.handleChangePassword">
|
||||
<div class="dialog-body">
|
||||
<div>
|
||||
<label class="label-field">{{ $t('profile.currentPassword') || 'Current Password' }}</label>
|
||||
<input v-model="userProfile.passwordForm.current" type="password" class="input-field mt-1" :disabled="userProfile.isChangingPassword" required />
|
||||
</div>
|
||||
<div>
|
||||
<label class="label-field">{{ $t('profile.newPassword') || 'New Password' }}</label>
|
||||
<input v-model="userProfile.passwordForm.new" type="password" class="input-field mt-1" :disabled="userProfile.isChangingPassword" required />
|
||||
</div>
|
||||
<div>
|
||||
<label class="label-field">{{ $t('profile.confirmPassword') || 'Confirm Password' }}</label>
|
||||
<input v-model="userProfile.passwordForm.confirm" type="password" class="input-field mt-1" :disabled="userProfile.isChangingPassword" required />
|
||||
</div>
|
||||
</div>
|
||||
<div class="dialog-footer">
|
||||
<button type="button" :disabled="userProfile.isChangingPassword" @click="userProfile.showPasswordModal = false" class="btn-secondary flex-1 disabled:opacity-50 disabled:cursor-not-allowed">
|
||||
{{ $t('profile.cancel') || 'Cancel' }}
|
||||
</button>
|
||||
<button type="submit" :disabled="userProfile.isChangingPassword" class="btn-primary flex-1 disabled:opacity-50 disabled:cursor-not-allowed">
|
||||
{{ userProfile.isChangingPassword ? $t('profile.changingPassword') : ($t('profile.changePassword') || 'Update') }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
+28
-25
@@ -1,16 +1,32 @@
|
||||
/**
|
||||
* features/workspace/composables/useWorkspaceProfile.ts
|
||||
* 个人中心:资料读取/编辑、主题偏好、修改密码。
|
||||
* features/user/composables/useUserProfile.ts
|
||||
* 用途:编排个人资料读取/编辑、主题偏好与统一密码修改。
|
||||
* 依赖:user.api、主题/消息/i18n composable、Casdoor 错误映射。
|
||||
* 逻辑:UserProfilePage 和 UserPasswordDialog 消费本 composable;Workspace 仅提供它以维持布局上下文。
|
||||
*/
|
||||
import { computed, ref } from 'vue';
|
||||
import type { ThemePreference } from '@/shared/composables/useTheme';
|
||||
import { resolveCasdoorErrorMessage } from '@/shared/utils/casdoor';
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
import { CHANGE_PASSWORD_ENABLED, type WorkspaceProfileForm } from '../types/workspace.types';
|
||||
import type { WorkspaceDeps } from './workspace.deps';
|
||||
import { BusinessError } from '@/shared/api/client';
|
||||
import { changeUserPassword, getEditableUserProfile, updateUserProfile } from '../api/user.api';
|
||||
import { CHANGE_PASSWORD_ENABLED, type UserProfileForm } from '../types/user-profile.types';
|
||||
import type { ComputedRef, WritableComputedRef } from 'vue';
|
||||
import type { ComposerTranslation } from 'vue-i18n';
|
||||
import type { useMessage } from '@/shared/composables/useMessage';
|
||||
|
||||
export function useWorkspaceProfile(deps: WorkspaceDeps) {
|
||||
interface UserProfileDeps {
|
||||
t: ComposerTranslation;
|
||||
locale: WritableComputedRef<string>;
|
||||
msg: ReturnType<typeof useMessage>;
|
||||
setThemePreference: (preference: ThemePreference) => void;
|
||||
appliedTheme: ComputedRef<ThemePreference>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理当前用户资料、偏好设置和密码修改状态。
|
||||
* 由工作台在初始化时创建,使资料页面与改密弹窗共享同一份状态和请求动作。
|
||||
*/
|
||||
export function useUserProfile(deps: UserProfileDeps) {
|
||||
const { t, locale, msg, setThemePreference, appliedTheme } = deps;
|
||||
|
||||
const isProfileLoading = ref(false);
|
||||
@@ -18,7 +34,7 @@ export function useWorkspaceProfile(deps: WorkspaceDeps) {
|
||||
const isChangingPassword = ref(false);
|
||||
const isProfileEditing = ref(false);
|
||||
const showPasswordModal = ref(false);
|
||||
const profileUser = ref<WorkspaceProfileForm>({
|
||||
const profileUser = ref<UserProfileForm>({
|
||||
id: 0,
|
||||
username: '',
|
||||
real_name: '',
|
||||
@@ -30,7 +46,7 @@ export function useWorkspaceProfile(deps: WorkspaceDeps) {
|
||||
language: 'zh-CN',
|
||||
theme_preference: 'system' as ThemePreference,
|
||||
});
|
||||
const originalProfile = ref<WorkspaceProfileForm | null>(null);
|
||||
const originalProfile = ref<UserProfileForm | null>(null);
|
||||
const passwordForm = ref({ current: '', new: '', confirm: '' });
|
||||
|
||||
const themeOptions: Array<{ value: ThemePreference; label: () => string }> = [
|
||||
@@ -67,9 +83,7 @@ export function useWorkspaceProfile(deps: WorkspaceDeps) {
|
||||
const fetchProfile = async () => {
|
||||
isProfileLoading.value = true;
|
||||
try {
|
||||
const data = await requestJson<Partial<WorkspaceProfileForm>>('/api/user/profile', {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
const data = await getEditableUserProfile();
|
||||
if (!data) {
|
||||
msg.error(t('workspace.profile.msg.loadFailed'));
|
||||
return;
|
||||
@@ -122,11 +136,7 @@ export function useWorkspaceProfile(deps: WorkspaceDeps) {
|
||||
setThemePreference(profileUser.value.theme_preference);
|
||||
try {
|
||||
isProfileSaving.value = true;
|
||||
await requestJson('/api/user/profile', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
await updateUserProfile(payload);
|
||||
msg.success(t('workspace.profile.msg.saved'));
|
||||
captureOriginalProfile();
|
||||
isProfileEditing.value = false;
|
||||
@@ -146,14 +156,7 @@ export function useWorkspaceProfile(deps: WorkspaceDeps) {
|
||||
}
|
||||
try {
|
||||
isChangingPassword.value = true;
|
||||
await requestJson('/api/user/change-password', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
|
||||
body: JSON.stringify({
|
||||
current_password: passwordForm.value.current,
|
||||
new_password: passwordForm.value.new,
|
||||
}),
|
||||
});
|
||||
await changeUserPassword(passwordForm.value.current, passwordForm.value.new);
|
||||
msg.success(t('profile.passwordChanged') || 'Password changed successfully');
|
||||
passwordForm.value = { current: '', new: '', confirm: '' };
|
||||
showPasswordModal.value = false;
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* features/user/composables/user-profile.context.ts
|
||||
* 用途:定义个人资料页面和改密弹窗共享的注入上下文。
|
||||
* 依赖:useUserProfile 的返回契约与工作台提供的移动端/登出能力。
|
||||
* 逻辑:WorkspaceLayout 提供上下文;user 域组件只依赖此契约,不读取工作台注入 key。
|
||||
*/
|
||||
import type { InjectionKey } from 'vue';
|
||||
import type { UserProfileForm } from '../types/user-profile.types';
|
||||
import type { ThemePreference } from '@/shared/composables/useTheme';
|
||||
|
||||
export interface UserProfileContext {
|
||||
isMobile: boolean;
|
||||
handleLogout: () => void;
|
||||
isProfileLoading: boolean;
|
||||
isProfileSaving: boolean;
|
||||
isChangingPassword: boolean;
|
||||
isProfileEditing: boolean;
|
||||
showPasswordModal: boolean;
|
||||
CHANGE_PASSWORD_ENABLED: boolean;
|
||||
profileUser: UserProfileForm;
|
||||
passwordForm: { current: string; new: string; confirm: string };
|
||||
hasProfileUnsavedChanges: boolean;
|
||||
themeOptions: Array<{ value: ThemePreference; label: () => string }>;
|
||||
handleChangePasswordClick: () => void;
|
||||
startProfileEditing: () => void;
|
||||
cancelProfileEditing: () => void;
|
||||
saveProfile: () => Promise<void>;
|
||||
handleChangePassword: () => Promise<void>;
|
||||
}
|
||||
|
||||
export const USER_PROFILE_KEY: InjectionKey<UserProfileContext> = Symbol('user-profile');
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* features/user/index.ts
|
||||
* 用途:暴露用户域 HTTP 能力,避免其他 feature 直接依赖实现路径。
|
||||
* 依赖:user.api。
|
||||
* 逻辑:Chat 等使用方从此处或 user.api 导入当前用户资料和授权资源查询。
|
||||
*/
|
||||
export * from './api/user.api';
|
||||
export { useUserProfile } from './composables/useUserProfile';
|
||||
export type { UserProfileForm } from './types/user-profile.types';
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* features/user/types/user-profile.types.ts
|
||||
* 用途:定义个人资料编辑与密码修改的用户域类型和功能开关。
|
||||
* 依赖:shared/composables/useTheme。
|
||||
* 逻辑:useUserProfile、UserProfilePage 和 UserPasswordDialog 使用同一份资料契约。
|
||||
*/
|
||||
import type { ThemePreference } from '@/shared/composables/useTheme';
|
||||
|
||||
export interface UserProfileForm {
|
||||
id: number;
|
||||
username: string;
|
||||
real_name: string;
|
||||
email: string;
|
||||
phone_number: string;
|
||||
department: string;
|
||||
role: string;
|
||||
employee_id: string;
|
||||
language: string;
|
||||
theme_preference: ThemePreference;
|
||||
}
|
||||
|
||||
export const CHANGE_PASSWORD_ENABLED = true;
|
||||
@@ -0,0 +1,198 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/user/views/UserProfilePage.vue
|
||||
* 閻劑鈧棑绱扮仦鏇犮仛閸滃瞼绱潏鎴濈秼閸撳秶鏁ら幋鐤カ閺傛瑣鈧浇顕㈢懛鈧?娑撳顣介崑蹇撱偨閿涘苯鑻熼幓鎰返娣囶喗鏁肩€靛棛鐖滈崗銉ュ經閵? * 娓氭繆绂嗛敍姝秙er-profile.context閵嗕勾ucide 閸ョ偓鐖i妴涔倁e i18n閵? * 闁槒绶敍姘矝閻?/workspace/profile 鐠侯垳鏁遍幍鑳祰閿涘奔绲炬い鐢告桨閸滃奔绗熼崝鈥崇秺鐏?user feature閵? */
|
||||
import { inject } from 'vue';
|
||||
import {
|
||||
User, Mail, Building, CreditCard, Globe, Save, Palette,
|
||||
} from 'lucide-vue-next';
|
||||
import { USER_PROFILE_KEY } from '../composables/user-profile.context';
|
||||
|
||||
const userProfile = inject(USER_PROFILE_KEY)!;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="userProfile.isProfileLoading" class="flex justify-center py-20">
|
||||
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-6">
|
||||
<div class="rounded-3xl border border-default bg-surface px-6 py-6 shadow-sm md:px-8">
|
||||
<div class="flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between">
|
||||
<div class="flex flex-1 flex-col gap-6 sm:flex-row sm:items-center sm:justify-start">
|
||||
<div class="flex h-24 w-24 shrink-0 items-center justify-center rounded-full bg-brand-100 text-4xl font-bold text-brand-600" :class="userProfile.isMobile ? 'h-14 w-14 text-2xl' : ''">
|
||||
{{ (userProfile.profileUser.real_name || userProfile.profileUser.username || 'U').charAt(0).toUpperCase() }}
|
||||
</div>
|
||||
<div class="grid flex-1 text-left" :class="userProfile.isMobile ? 'grid-cols-2 gap-x-4 gap-y-1' : 'grid-cols-1 gap-x-12 gap-y-3 sm:grid-cols-2'">
|
||||
<div :class="userProfile.isMobile ? '' : ''">
|
||||
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.realName') : (userProfile.profileUser.username || '-') }}</div>
|
||||
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ userProfile.profileUser.real_name || userProfile.profileUser.username || '-' }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.employeeId') : (userProfile.profileUser.employee_id || '-') }}</div>
|
||||
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ userProfile.profileUser.employee_id || '-' }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.department') : (userProfile.profileUser.department || '-') }}</div>
|
||||
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ userProfile.profileUser.department || '-' }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.role') : (userProfile.profileUser.role === 'admin' ? ($t('profile.roleAdmin') || 'Administrator') : ($t('profile.roleUser') || 'User')) }}</div>
|
||||
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ userProfile.profileUser.role === 'admin' ? ($t('profile.roleAdmin') || 'Administrator') : ($t('profile.roleUser') || 'User') }}</div>
|
||||
</div>
|
||||
<div :class="userProfile.isMobile ? 'col-span-2' : 'sm:col-span-2'">
|
||||
<div :class="userProfile.isMobile ? 'text-xs text-muted' : 'break-all text-lg font-semibold text-primary'">{{ userProfile.isMobile ? $t('profile.email') : (userProfile.profileUser.email || '-') }}</div>
|
||||
<div v-if="userProfile.isMobile" class="text-sm font-medium text-primary truncate">{{ userProfile.profileUser.email || '-' }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!userProfile.isMobile" class="flex shrink-0 items-center gap-2 self-start lg:ml-6">
|
||||
<button @click="userProfile.handleChangePasswordClick" class="btn-primary px-6 py-3 text-base">
|
||||
{{ $t('profile.changePassword') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="userProfile.isMobile" class="mt-4 flex items-center justify-center gap-4">
|
||||
<button @click="userProfile.handleChangePasswordClick" class="btn-primary flex-1 py-2.5 text-sm text-center">
|
||||
{{ $t('profile.changePassword') }}
|
||||
</button>
|
||||
<button @click="userProfile.handleLogout" class="btn-secondary flex-1 py-2.5 text-sm text-center text-red-600 hover:bg-red-50">
|
||||
{{ $t('workspace.nav.logout') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-6">
|
||||
<div class="rounded-3xl border border-default bg-surface p-8 shadow-sm" :class="userProfile.isMobile ? 'p-4' : ''">
|
||||
<div class="mb-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between" :class="userProfile.isMobile ? 'mb-4 gap-2' : ''">
|
||||
<div class="flex items-center" :class="userProfile.isMobile ? 'w-full justify-center gap-2' : ''">
|
||||
<h3 class="flex items-center gap-3 text-3xl font-bold text-primary" :class="userProfile.isMobile ? 'text-lg gap-2' : ''">
|
||||
<User class="h-6 w-6 text-brand-500" :class="userProfile.isMobile ? 'h-4 w-4' : ''" />
|
||||
{{ $t('profile.basicInfo') }}
|
||||
</h3>
|
||||
<button v-if="userProfile.isMobile && !userProfile.isProfileEditing" @click="userProfile.startProfileEditing" class="btn-secondary px-3 py-1 text-xs">
|
||||
{{ $t('profile.edit') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="!userProfile.isMobile" class="mt-2 text-sm text-muted">
|
||||
{{ userProfile.isProfileEditing ? $t('profile.directEditHint') : $t('profile.switchEditHint') }}
|
||||
</p>
|
||||
<div v-if="!userProfile.isMobile" class="flex items-center gap-2">
|
||||
<button v-if="!userProfile.isProfileEditing" @click="userProfile.startProfileEditing" class="btn-secondary px-5 py-2.5 text-sm">
|
||||
{{ $t('profile.edit') }}
|
||||
</button>
|
||||
<template v-else>
|
||||
<button @click="userProfile.cancelProfileEditing" class="btn-secondary px-5 py-2.5 text-sm">
|
||||
{{ $t('profile.cancel') || 'Cancel' }}
|
||||
</button>
|
||||
<button
|
||||
@click="userProfile.saveProfile"
|
||||
:disabled="userProfile.isProfileSaving || !userProfile.hasProfileUnsavedChanges"
|
||||
class="btn-primary px-5 py-2.5 text-sm disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Save class="w-4 h-4" />
|
||||
<span>{{ userProfile.isProfileSaving ? $t('profile.saving') : $t('workspace.save') }}</span>
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 gap-5 md:grid-cols-2" :class="userProfile.isMobile ? 'gap-3' : ''">
|
||||
<div>
|
||||
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
|
||||
<User class="h-4 w-4" /> {{ $t('profile.username') }}
|
||||
</label>
|
||||
<div class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
|
||||
{{ userProfile.profileUser.username || '-' }}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
|
||||
<CreditCard class="h-4 w-4" /> {{ $t('profile.employeeId') }}
|
||||
</label>
|
||||
<input v-if="userProfile.isProfileEditing" v-model="userProfile.profileUser.employee_id" type="text" class="input-field" :class="userProfile.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
|
||||
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
|
||||
{{ userProfile.profileUser.employee_id || '-' }}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
|
||||
<User class="h-4 w-4" /> {{ $t('profile.realName') }}
|
||||
</label>
|
||||
<input v-if="userProfile.isProfileEditing" v-model="userProfile.profileUser.real_name" type="text" class="input-field" :class="userProfile.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
|
||||
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
|
||||
{{ userProfile.profileUser.real_name || '-' }}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
|
||||
<Building class="h-4 w-4" /> {{ $t('profile.department') }}
|
||||
</label>
|
||||
<input v-if="userProfile.isProfileEditing" v-model="userProfile.profileUser.department" type="text" class="input-field" :class="userProfile.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
|
||||
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
|
||||
{{ userProfile.profileUser.department || '-' }}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
|
||||
<Mail class="h-4 w-4" /> {{ $t('profile.email') }}
|
||||
</label>
|
||||
<input v-if="userProfile.isProfileEditing" v-model="userProfile.profileUser.email" type="email" class="input-field" :class="userProfile.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
|
||||
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
|
||||
{{ userProfile.profileUser.email || '-' }}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="userProfile.isMobile ? 'text-xs mb-1' : ''">
|
||||
<Globe class="h-4 w-4" /> {{ $t('profile.phoneNumber') }}
|
||||
</label>
|
||||
<input v-if="userProfile.isProfileEditing" v-model="userProfile.profileUser.phone_number" type="text" class="input-field" :class="userProfile.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
|
||||
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="userProfile.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
|
||||
{{ userProfile.profileUser.phone_number || '-' }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-3xl border border-default bg-surface p-8 shadow-sm">
|
||||
<h3 class="mb-6 flex items-center gap-3 text-2xl font-bold text-primary">
|
||||
<Palette class="h-5 w-5 text-brand-500" />
|
||||
{{ $t('profile.preferences') }}
|
||||
</h3>
|
||||
<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
|
||||
<div>
|
||||
<label class="mb-2 block text-sm font-medium text-muted">{{ $t('workspace.languageLabel') }}</label>
|
||||
<select v-model="userProfile.profileUser.language" :disabled="!userProfile.isProfileEditing" class="input-field h-[58px]">
|
||||
<option value="en">English</option>
|
||||
<option value="zh-CN">{{ $t('workspace.lang.zhCN') }}</option>
|
||||
<option value="zh-TW">{{ $t('workspace.lang.zhTW') }}</option>
|
||||
<option value="th">Thai</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-2 block text-sm font-medium text-muted">{{ $t('profile.theme') }}</label>
|
||||
<div
|
||||
class="segment-control segment-control--cols-3 segment-control--md"
|
||||
role="radiogroup"
|
||||
:aria-label="$t('profile.theme')"
|
||||
>
|
||||
<button
|
||||
v-for="item in userProfile.themeOptions"
|
||||
:key="item.value"
|
||||
type="button"
|
||||
role="radio"
|
||||
:aria-checked="userProfile.profileUser.theme_preference === item.value"
|
||||
:disabled="!userProfile.isProfileEditing"
|
||||
class="segment-item"
|
||||
:class="userProfile.profileUser.theme_preference === item.value ? 'segment-item--active' : ''"
|
||||
@click="userProfile.profileUser.theme_preference = item.value"
|
||||
>
|
||||
{{ item.label() }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/workspace/components/WorkspaceModals.vue
|
||||
* 工作台弹窗:公告详情、修改密码、快捷问题删除、意见反馈。
|
||||
* 工作台弹窗:公告详情、快捷问题删除、意见反馈。
|
||||
*/
|
||||
import { inject } from 'vue';
|
||||
import { X } from 'lucide-vue-next';
|
||||
@@ -41,77 +41,6 @@ const ws = inject(WORKSPACE_KEY)! as any;
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="ws.CHANGE_PASSWORD_ENABLED && ws.showPasswordModal"
|
||||
class="dialog-overlay z-50 items-center"
|
||||
>
|
||||
<div class="dialog-panel max-w-md">
|
||||
<div class="dialog-header">
|
||||
<h3 class="section-title">{{ $t('profile.changePassword') || 'Change Password' }}</h3>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-icon-ds"
|
||||
:aria-label="$t('admin.close')"
|
||||
:disabled="ws.isChangingPassword"
|
||||
@click="ws.showPasswordModal = false"
|
||||
>
|
||||
<X class="w-5 h-5" />
|
||||
</button>
|
||||
</div>
|
||||
<form @submit.prevent="ws.handleChangePassword">
|
||||
<div class="dialog-body">
|
||||
<div>
|
||||
<label class="label-field">{{ $t('profile.currentPassword') || 'Current Password' }}</label>
|
||||
<input
|
||||
v-model="ws.passwordForm.current"
|
||||
type="password"
|
||||
class="input-field mt-1"
|
||||
:disabled="ws.isChangingPassword"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label class="label-field">{{ $t('profile.newPassword') || 'New Password' }}</label>
|
||||
<input
|
||||
v-model="ws.passwordForm.new"
|
||||
type="password"
|
||||
class="input-field mt-1"
|
||||
:disabled="ws.isChangingPassword"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label class="label-field">{{ $t('profile.confirmPassword') || 'Confirm Password' }}</label>
|
||||
<input
|
||||
v-model="ws.passwordForm.confirm"
|
||||
type="password"
|
||||
class="input-field mt-1"
|
||||
:disabled="ws.isChangingPassword"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="dialog-footer">
|
||||
<button
|
||||
type="button"
|
||||
:disabled="ws.isChangingPassword"
|
||||
@click="ws.showPasswordModal = false"
|
||||
class="btn-secondary flex-1 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{{ $t('profile.cancel') || 'Cancel' }}
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
:disabled="ws.isChangingPassword"
|
||||
class="btn-primary flex-1 disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
{{ ws.isChangingPassword ? $t('profile.changingPassword') : ($t('profile.changePassword') || 'Update') }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DeleteConfirmDialog
|
||||
v-model="ws.showDeleteQuickQuestionDialog"
|
||||
:title="$t('workspace.quickQuestions.deleteDialog.title')"
|
||||
|
||||
@@ -15,7 +15,7 @@ import { useChatHistory } from '@/features/chat/composables/useChatHistory';
|
||||
import { useWorkspaceHome } from './useWorkspaceHome';
|
||||
import { useWorkspaceLocale } from './useWorkspaceLocale';
|
||||
import { useWorkspaceNavigation } from './useWorkspaceNavigation';
|
||||
import { useWorkspaceProfile } from './useWorkspaceProfile';
|
||||
import { useUserProfile } from '@/features/user/composables/useUserProfile';
|
||||
import { useWorkspaceSchedule } from './useWorkspaceSchedule';
|
||||
import { useWorkspaceSession } from './useWorkspaceSession';
|
||||
|
||||
@@ -44,7 +44,7 @@ export function useWorkspace() {
|
||||
});
|
||||
sessionRef.handleLogout = session.handleLogout;
|
||||
|
||||
const profile = useWorkspaceProfile(deps);
|
||||
const profile = useUserProfile(deps);
|
||||
const schedule = useWorkspaceSchedule(deps);
|
||||
const history = useChatHistory();
|
||||
|
||||
|
||||
@@ -1,199 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/workspace/pages/ProfilePage.vue
|
||||
* 个人中心:用户资料展示与编辑、语言/主题偏好、修改密码入口。
|
||||
*/
|
||||
import { inject } from 'vue';
|
||||
import {
|
||||
User, Mail, Building, CreditCard, Globe, Save, Palette,
|
||||
} from 'lucide-vue-next';
|
||||
import { WORKSPACE_KEY } from '../composables/workspace.context';
|
||||
|
||||
const ws = inject(WORKSPACE_KEY)! as any;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="ws.isProfileLoading" class="flex justify-center py-20">
|
||||
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-brand-600"></div>
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-6">
|
||||
<div class="rounded-3xl border border-default bg-surface px-6 py-6 shadow-sm md:px-8">
|
||||
<div class="flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between">
|
||||
<div class="flex flex-1 flex-col gap-6 sm:flex-row sm:items-center sm:justify-start">
|
||||
<div class="flex h-24 w-24 shrink-0 items-center justify-center rounded-full bg-brand-100 text-4xl font-bold text-brand-600" :class="ws.isMobile ? 'h-14 w-14 text-2xl' : ''">
|
||||
{{ (ws.profileUser.real_name || ws.profileUser.username || 'U').charAt(0).toUpperCase() }}
|
||||
</div>
|
||||
<div class="grid flex-1 text-left" :class="ws.isMobile ? 'grid-cols-2 gap-x-4 gap-y-1' : 'grid-cols-1 gap-x-12 gap-y-3 sm:grid-cols-2'">
|
||||
<div :class="ws.isMobile ? '' : ''">
|
||||
<div :class="ws.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ ws.isMobile ? $t('profile.realName') : (ws.profileUser.username || '-') }}</div>
|
||||
<div v-if="ws.isMobile" class="text-sm font-medium text-primary truncate">{{ ws.profileUser.real_name || ws.profileUser.username || '-' }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div :class="ws.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ ws.isMobile ? $t('profile.employeeId') : (ws.profileUser.employee_id || '-') }}</div>
|
||||
<div v-if="ws.isMobile" class="text-sm font-medium text-primary truncate">{{ ws.profileUser.employee_id || '-' }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div :class="ws.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ ws.isMobile ? $t('profile.department') : (ws.profileUser.department || '-') }}</div>
|
||||
<div v-if="ws.isMobile" class="text-sm font-medium text-primary truncate">{{ ws.profileUser.department || '-' }}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div :class="ws.isMobile ? 'text-xs text-muted' : 'text-lg font-semibold text-primary'">{{ ws.isMobile ? $t('profile.role') : (ws.profileUser.role === 'admin' ? ($t('profile.roleAdmin') || 'Administrator') : ($t('profile.roleUser') || 'User')) }}</div>
|
||||
<div v-if="ws.isMobile" class="text-sm font-medium text-primary truncate">{{ ws.profileUser.role === 'admin' ? ($t('profile.roleAdmin') || 'Administrator') : ($t('profile.roleUser') || 'User') }}</div>
|
||||
</div>
|
||||
<div :class="ws.isMobile ? 'col-span-2' : 'sm:col-span-2'">
|
||||
<div :class="ws.isMobile ? 'text-xs text-muted' : 'break-all text-lg font-semibold text-primary'">{{ ws.isMobile ? $t('profile.email') : (ws.profileUser.email || '-') }}</div>
|
||||
<div v-if="ws.isMobile" class="text-sm font-medium text-primary truncate">{{ ws.profileUser.email || '-' }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="!ws.isMobile" class="flex shrink-0 items-center gap-2 self-start lg:ml-6">
|
||||
<button @click="ws.handleChangePasswordClick" class="btn-primary px-6 py-3 text-base">
|
||||
{{ $t('profile.changePassword') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="ws.isMobile" class="mt-4 flex items-center justify-center gap-4">
|
||||
<button @click="ws.handleChangePasswordClick" class="btn-primary flex-1 py-2.5 text-sm text-center">
|
||||
{{ $t('profile.changePassword') }}
|
||||
</button>
|
||||
<button @click="ws.handleLogout" class="btn-secondary flex-1 py-2.5 text-sm text-center text-red-600 hover:bg-red-50">
|
||||
{{ $t('workspace.nav.logout') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-6">
|
||||
<div class="rounded-3xl border border-default bg-surface p-8 shadow-sm" :class="ws.isMobile ? 'p-4' : ''">
|
||||
<div class="mb-8 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between" :class="ws.isMobile ? 'mb-4 gap-2' : ''">
|
||||
<div class="flex items-center" :class="ws.isMobile ? 'w-full justify-center gap-2' : ''">
|
||||
<h3 class="flex items-center gap-3 text-3xl font-bold text-primary" :class="ws.isMobile ? 'text-lg gap-2' : ''">
|
||||
<User class="h-6 w-6 text-brand-500" :class="ws.isMobile ? 'h-4 w-4' : ''" />
|
||||
{{ $t('profile.basicInfo') }}
|
||||
</h3>
|
||||
<button v-if="ws.isMobile && !ws.isProfileEditing" @click="ws.startProfileEditing" class="btn-secondary px-3 py-1 text-xs">
|
||||
{{ $t('profile.edit') }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="!ws.isMobile" class="mt-2 text-sm text-muted">
|
||||
{{ ws.isProfileEditing ? $t('profile.directEditHint') : $t('profile.switchEditHint') }}
|
||||
</p>
|
||||
<div v-if="!ws.isMobile" class="flex items-center gap-2">
|
||||
<button v-if="!ws.isProfileEditing" @click="ws.startProfileEditing" class="btn-secondary px-5 py-2.5 text-sm">
|
||||
{{ $t('profile.edit') }}
|
||||
</button>
|
||||
<template v-else>
|
||||
<button @click="ws.cancelProfileEditing" class="btn-secondary px-5 py-2.5 text-sm">
|
||||
{{ $t('profile.cancel') || 'Cancel' }}
|
||||
</button>
|
||||
<button
|
||||
@click="ws.saveProfile"
|
||||
:disabled="ws.isProfileSaving || !ws.hasProfileUnsavedChanges"
|
||||
class="btn-primary px-5 py-2.5 text-sm disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<Save class="w-4 h-4" />
|
||||
<span>{{ ws.isProfileSaving ? $t('profile.saving') : $t('workspace.save') }}</span>
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 gap-5 md:grid-cols-2" :class="ws.isMobile ? 'gap-3' : ''">
|
||||
<div>
|
||||
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="ws.isMobile ? 'text-xs mb-1' : ''">
|
||||
<User class="h-4 w-4" /> {{ $t('profile.username') }}
|
||||
</label>
|
||||
<div class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="ws.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
|
||||
{{ ws.profileUser.username || '-' }}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="ws.isMobile ? 'text-xs mb-1' : ''">
|
||||
<CreditCard class="h-4 w-4" /> {{ $t('profile.employeeId') }}
|
||||
</label>
|
||||
<input v-if="ws.isProfileEditing" v-model="ws.profileUser.employee_id" type="text" class="input-field" :class="ws.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
|
||||
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="ws.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
|
||||
{{ ws.profileUser.employee_id || '-' }}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="ws.isMobile ? 'text-xs mb-1' : ''">
|
||||
<User class="h-4 w-4" /> {{ $t('profile.realName') }}
|
||||
</label>
|
||||
<input v-if="ws.isProfileEditing" v-model="ws.profileUser.real_name" type="text" class="input-field" :class="ws.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
|
||||
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="ws.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
|
||||
{{ ws.profileUser.real_name || '-' }}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="ws.isMobile ? 'text-xs mb-1' : ''">
|
||||
<Building class="h-4 w-4" /> {{ $t('profile.department') }}
|
||||
</label>
|
||||
<input v-if="ws.isProfileEditing" v-model="ws.profileUser.department" type="text" class="input-field" :class="ws.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
|
||||
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="ws.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
|
||||
{{ ws.profileUser.department || '-' }}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="ws.isMobile ? 'text-xs mb-1' : ''">
|
||||
<Mail class="h-4 w-4" /> {{ $t('profile.email') }}
|
||||
</label>
|
||||
<input v-if="ws.isProfileEditing" v-model="ws.profileUser.email" type="email" class="input-field" :class="ws.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
|
||||
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="ws.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
|
||||
{{ ws.profileUser.email || '-' }}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-2 flex items-center gap-2 text-sm font-medium text-muted" :class="ws.isMobile ? 'text-xs mb-1' : ''">
|
||||
<Globe class="h-4 w-4" /> {{ $t('profile.phoneNumber') }}
|
||||
</label>
|
||||
<input v-if="ws.isProfileEditing" v-model="ws.profileUser.phone_number" type="text" class="input-field" :class="ws.isMobile ? 'h-10 text-sm' : 'h-[58px]'" />
|
||||
<div v-else class="rounded-2xl border border-default bg-surface-soft px-4 py-4 text-lg font-medium text-secondary" :class="ws.isMobile ? 'px-3 py-2 text-sm rounded-xl' : ''">
|
||||
{{ ws.profileUser.phone_number || '-' }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-3xl border border-default bg-surface p-8 shadow-sm">
|
||||
<h3 class="mb-6 flex items-center gap-3 text-2xl font-bold text-primary">
|
||||
<Palette class="h-5 w-5 text-brand-500" />
|
||||
{{ $t('profile.preferences') }}
|
||||
</h3>
|
||||
<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
|
||||
<div>
|
||||
<label class="mb-2 block text-sm font-medium text-muted">{{ $t('workspace.languageLabel') }}</label>
|
||||
<select v-model="ws.profileUser.language" :disabled="!ws.isProfileEditing" class="input-field h-[58px]">
|
||||
<option value="en">English</option>
|
||||
<option value="zh-CN">{{ $t('workspace.lang.zhCN') }}</option>
|
||||
<option value="zh-TW">{{ $t('workspace.lang.zhTW') }}</option>
|
||||
<option value="th">ไทย</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-2 block text-sm font-medium text-muted">{{ $t('profile.theme') }}</label>
|
||||
<div
|
||||
class="segment-control segment-control--cols-3 segment-control--md"
|
||||
role="radiogroup"
|
||||
:aria-label="$t('profile.theme')"
|
||||
>
|
||||
<button
|
||||
v-for="item in ws.themeOptions"
|
||||
:key="item.value"
|
||||
type="button"
|
||||
role="radio"
|
||||
:aria-checked="ws.profileUser.theme_preference === item.value"
|
||||
:disabled="!ws.isProfileEditing"
|
||||
class="segment-item"
|
||||
:class="ws.profileUser.theme_preference === item.value ? 'segment-item--active' : ''"
|
||||
@click="ws.profileUser.theme_preference = item.value"
|
||||
>
|
||||
{{ item.label() }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -2,7 +2,6 @@
|
||||
* features/workspace/types/workspace.types.ts
|
||||
* 工作台相关 TypeScript 类型与业务常量。
|
||||
*/
|
||||
import type { ThemePreference } from '@/shared/composables/useTheme';
|
||||
import type { WecomMatchField } from '@/shared/utils/wecom';
|
||||
import type { WecomLoginDialogContent } from '@/shared/utils/wecom';
|
||||
|
||||
@@ -73,19 +72,6 @@ export interface WecomBindPromptState {
|
||||
error: string;
|
||||
}
|
||||
|
||||
export interface WorkspaceProfileForm {
|
||||
id: number;
|
||||
username: string;
|
||||
real_name: string;
|
||||
email: string;
|
||||
phone_number: string;
|
||||
department: string;
|
||||
role: string;
|
||||
employee_id: string;
|
||||
language: string;
|
||||
theme_preference: ThemePreference;
|
||||
}
|
||||
|
||||
export type { ChatCrossAgentHistoryItem as WorkspaceChatHistoryItem } from '@/features/chat/types/chat.types';
|
||||
|
||||
export type { WecomLoginDialogContent };
|
||||
@@ -101,4 +87,3 @@ export const SECTION_TITLE_KEY_MAP: Record<string, string> = {
|
||||
export const DEFAULT_POST_LOGIN_AGENT_ID = 16;
|
||||
export const KB_ACCESS_DENIED_MESSAGE = '需要管理员权限才能访问知识库。';
|
||||
export const WS_SCHEDULE_FILTER_INPUT_CLASS = 'admin-table-filter-input text-xs py-1.5 px-2';
|
||||
export const CHANGE_PASSWORD_ENABLED = true;
|
||||
@@ -11,9 +11,12 @@ import { WORKSPACE_KEY } from '../composables/workspace.context';
|
||||
import WorkspaceSidebar from '../components/WorkspaceSidebar.vue';
|
||||
import WorkspaceModals from '../components/WorkspaceModals.vue';
|
||||
import { ExternalSystemLinks } from '@/features/sso';
|
||||
import UserPasswordDialog from '@/features/user/components/UserPasswordDialog.vue';
|
||||
import { USER_PROFILE_KEY, type UserProfileContext } from '@/features/user/composables/user-profile.context';
|
||||
|
||||
const ws = useWorkspace();
|
||||
provide(WORKSPACE_KEY, ws);
|
||||
provide(USER_PROFILE_KEY, ws as UserProfileContext);
|
||||
|
||||
const mobileTabs = [
|
||||
{ key: 'applications', path: WORKSPACE_PATHS.applications, icon: LayoutGrid, labelKey: 'workspace.mobileTabs.applications' },
|
||||
@@ -72,5 +75,6 @@ const mobileTabs = [
|
||||
</div>
|
||||
|
||||
<WorkspaceModals />
|
||||
<UserPasswordDialog />
|
||||
</div>
|
||||
</template>
|
||||
@@ -32,7 +32,7 @@ ENV_FILE="${ROOT_DIR}/.env.${ENV_NAME}"
|
||||
SHARED_ENV_FILE="${ROOT_DIR}/.env.shared"
|
||||
ORACLE_CLIENT_DIR="${ROOT_DIR}/oracle_client"
|
||||
BACKEND_DOCKERFILE="${ROOT_DIR}/backend/Dockerfile"
|
||||
SCHEMA_DOC_PATH="${ROOT_DIR}/docs/(表+字段).md"
|
||||
SCHEMA_DOC_PATH="${ROOT_DIR}/docs/integrations/erp/text2sql_schema.md"
|
||||
ROOT_DOCKERIGNORE="${ROOT_DIR}/.dockerignore"
|
||||
|
||||
check_oracle_client() {
|
||||
@@ -63,7 +63,7 @@ check_backend_build_inputs() {
|
||||
|
||||
if [[ ! -f "${SCHEMA_DOC_PATH}" ]]; then
|
||||
echo "Missing Text2SQL schema doc: ${SCHEMA_DOC_PATH}"
|
||||
echo "Please ensure docs/(表+字段).md exists in the repository root before building hxops-backend."
|
||||
echo "Please ensure docs/integrations/erp/text2sql_schema.md exists before building hxops-backend."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -75,18 +75,20 @@ check_backend_build_inputs() {
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! grep -Fq 'COPY docs/(表+字段).md /app/docs/(表+字段).md' "${BACKEND_DOCKERFILE}"; then
|
||||
if ! grep -Fq 'COPY docs/integrations/erp/text2sql_schema.md /app/docs/integrations/erp/text2sql_schema.md' "${BACKEND_DOCKERFILE}"; then
|
||||
echo "Invalid backend Dockerfile: schema doc is not copied into the image."
|
||||
echo "Expected line:"
|
||||
echo " COPY docs/(表+字段).md /app/docs/(表+字段).md"
|
||||
echo " COPY docs/integrations/erp/text2sql_schema.md /app/docs/integrations/erp/text2sql_schema.md"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ -f "${ROOT_DOCKERIGNORE}" ]] && grep -Eq '^(docs|docs/\*)$' "${ROOT_DOCKERIGNORE}"; then
|
||||
if ! grep -Fxq '!docs/(表+字段).md' "${ROOT_DOCKERIGNORE}"; then
|
||||
echo "Invalid .dockerignore: docs is excluded but docs/(表+字段).md is not re-included."
|
||||
if ! grep -Fxq '!docs/integrations/erp/text2sql_schema.md' "${ROOT_DOCKERIGNORE}"; then
|
||||
echo "Invalid .dockerignore: docs is excluded but the Text2SQL schema is not re-included."
|
||||
echo "Please add the following line to ${ROOT_DOCKERIGNORE}:"
|
||||
echo " !docs/(表+字段).md"
|
||||
echo " !docs/integrations/"
|
||||
echo " !docs/integrations/erp/"
|
||||
echo " !docs/integrations/erp/text2sql_schema.md"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# Configuration
|
||||
SERVER_USER="ai30"
|
||||
SERVER_IP="192.168.100.230"
|
||||
REMOTE_DIR="/data/ai-platform/hxops"
|
||||
BACKEND_CONTAINER="hxops-backend"
|
||||
|
||||
echo "=== Starting Remote Server Initialization ==="
|
||||
echo "Target: $SERVER_USER@$SERVER_IP"
|
||||
|
||||
# 1. Check local files exist
|
||||
if [ ! -f "backend/init_db.py" ] || [ ! -f "backend/seed_production.py" ]; then
|
||||
echo "Error: Required files not found locally (backend/init_db.py or backend/seed_production.py)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 2. Upload updated scripts to server
|
||||
echo ">>> Uploading initialization scripts..."
|
||||
scp backend/init_db.py $SERVER_USER@$SERVER_IP:$REMOTE_DIR/backend/
|
||||
scp backend/seed_production.py $SERVER_USER@$SERVER_IP:$REMOTE_DIR/backend/
|
||||
|
||||
# 3. Execute remote commands
|
||||
echo ">>> Executing remote initialization..."
|
||||
ssh $SERVER_USER@$SERVER_IP "cd $REMOTE_DIR && \
|
||||
echo '--- 1. Initializing Database (Create DB if missing) ---' && \
|
||||
docker-compose exec -T $BACKEND_CONTAINER python3 init_db.py && \
|
||||
echo '--- 2. Running Migrations (Create Tables) ---' && \
|
||||
docker-compose exec -T $BACKEND_CONTAINER flask db upgrade && \
|
||||
echo '--- 3. Seeding Data (Admin User & Languages) ---' && \
|
||||
docker-compose exec -T $BACKEND_CONTAINER python3 seed_production.py"
|
||||
|
||||
echo "=== Initialization Complete! ==="
|
||||
echo "You can now login with:"
|
||||
echo " Username: admin"
|
||||
echo " Password: admin"
|
||||
echo "Please change the password immediately after login."
|
||||
Reference in new issue
Block a user