diff --git a/.vscode/settings.json b/.vscode/settings.json index e98726b0..7aa70d3d 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,17 +1,31 @@ { - // 后端 Python 虚拟环境:新终端自动激活,无需手动 .venv\Scripts\activate + // 后端 Python 虚拟环境 "python.defaultInterpreterPath": "${workspaceFolder}/backend/.venv/Scripts/python.exe", "python.terminal.activateEnvironment": true, "python.venvPath": "${workspaceFolder}/backend", "python.venvFolders": [".venv"], - // 可选:在终端下拉中选择「HXOPS Backend」时,直接进入 backend 并激活 venv + // 默认终端:加载 cd 钩子,进入 backend 时自动激活 .venv + "terminal.integrated.defaultProfile.windows": "PowerShell (HXOPS)", "terminal.integrated.profiles.windows": { + "PowerShell (HXOPS)": { + "source": "PowerShell", + "icon": "terminal-powershell", + "args": [ + "-NoExit", + "-ExecutionPolicy", + "Bypass", + "-File", + "${workspaceFolder}/scripts/powershell-backend-auto-venv.ps1" + ] + }, "HXOPS Backend": { "source": "PowerShell", "icon": "server-environment", "args": [ "-NoExit", + "-ExecutionPolicy", + "Bypass", "-Command", "Set-Location '${workspaceFolder}/backend'; if (Test-Path '.venv/Scripts/Activate.ps1') { . '.venv/Scripts/Activate.ps1' }" ] diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py new file mode 100644 index 00000000..ec00b1a9 --- /dev/null +++ b/backend/app/api/__init__.py @@ -0,0 +1,52 @@ +""" +backend/app/api/__init__.py + +用途:集中注册所有 Blueprint(Wave 1 接入 create_app)。 +依赖:各 api 子包 blueprint。 +逻辑:替代 app/__init__.py 内 15 行散乱 register_blueprint。 +""" +from __future__ import annotations + +from flask import Flask + + +def register_blueprints(app: Flask) -> None: + """ + 注册全部 HTTP Blueprint,保持对外 url_prefix 不变。 + 核心逻辑:Wave 0 仍从既有单体模块 import;Wave 1+ 逐步切换至分包。 + Args: + app: Flask 应用实例。 + """ + # [STEP 1] 单体模块(Wave 3 前保持不变) + 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.knowledge_base import knowledge_base_bp + from app.api.integration import integration_bp + from app.api.internal_jobs import internal_jobs_bp + from app.api.speech import speech_bp + + # [STEP 2] 已分包骨架(re-export 旧模块,Wave 1 可切换 import 来源) + from app.api.schedule import schedule_admin_bp + from app.api.workspace import ( + workspace_file_check_bp, + workspace_schedule_bp, + workspace_shipping_notice_bp, + ) + from app.api.tools import file_check_bp, shipping_notice_bp + + app.register_blueprint(chat_bp, url_prefix='/api/chat') + 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(knowledge_base_bp, url_prefix='/api/kb') + app.register_blueprint(integration_bp, url_prefix='/api/integration') + app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin') + app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace') + app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace') + app.register_blueprint(workspace_file_check_bp, url_prefix='/api/workspace') + app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs') + app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice') + app.register_blueprint(file_check_bp, url_prefix='/api/file-check') + app.register_blueprint(speech_bp, url_prefix='/api/speech') diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py index 40b306fd..10d616c2 100644 --- a/backend/app/api/admin.py +++ b/backend/app/api/admin.py @@ -14,6 +14,7 @@ from app import db from app.env_persistence import persist_env_settings from sqlalchemy import func, desc, inspect, or_ from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import joinedload from datetime import datetime, timedelta import csv import io @@ -23,6 +24,7 @@ import uuid from app.services.wecom_notify import send_wecom_event_message from app.services.oa_wecom_sync import sync_wecom_userids_from_oa from app.services.dify import DifyService +from app.services.user_admin import delete_admin_users from app.auth_jwt import get_current_user as _get_auth_user from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status admin_bp = Blueprint('admin', __name__) @@ -452,14 +454,87 @@ def update_agent_permissions(id): db.session.commit() return jsonify({'status': 'ok'}) +def _serialize_admin_user(user: User) -> dict: + """将 User ORM 转为管理端列表/详情 JSON 结构。""" + return { + 'id': user.id, + 'username': user.username, + 'email': user.email, + 'department': user.department, + 'role': user.role, + 'status': user.status, + 'real_name': user.real_name, + 'employee_id': user.employee_id, + 'phone_number': user.phone_number, + 'agent_ids': [agent.id for agent in user.agents], + } + + +def _apply_admin_users_filters(query): + """ + 按 Query 参数过滤用户列表(模糊匹配文本字段)。 + 支持:username, email, department, role, status, real_name, employee_id, phone_number, hide_rejected。 + """ + if request.args.get('hide_rejected', 'false').lower() == 'true': + query = query.filter(User.status != 'rejected') + filter_columns = { + 'username': User.username, + 'email': User.email, + 'department': User.department, + 'role': User.role, + 'status': User.status, + 'real_name': User.real_name, + 'employee_id': User.employee_id, + 'phone_number': User.phone_number, + } + for key, column in filter_columns.items(): + value = (request.args.get(key) or '').strip() + if value: + query = query.filter(column.cast(db.String).ilike(f'%{value}%')) + return query + + @admin_bp.route('/users', methods=['GET']) @require_admin def list_users(): - users = db.session.query(User).order_by(User.id.asc()).all() - res = [] - for u in users: - res.append({'id': u.id, 'username': u.username, 'email': u.email, 'department': u.department, 'role': u.role, 'status': u.status, 'real_name': u.real_name, 'employee_id': u.employee_id, 'phone_number': u.phone_number, 'agent_ids': [a.id for a in u.agents]}) - return jsonify(res) + """ + 列出管理端用户。无 page 参数时返回全量数组(兼容旧调用);带 page 时分页并支持筛选。 + + Query: page, page_size, username, email, department, role, status, real_name, + employee_id, phone_number, hide_rejected + Returns (paginated): { items, total, page, page_size, pages } + Returns (legacy): User[] + """ + query = _apply_admin_users_filters(db.session.query(User)) + + if 'page' not in request.args: + users = query.options(joinedload(User.agents)).order_by(User.id.asc()).all() + return jsonify([_serialize_admin_user(u) for u in users]) + + page = request.args.get('page', type=int) or 1 + page_size = request.args.get('page_size', type=int) or 20 + page = max(1, page) + page_size = max(1, min(100, page_size)) + + total = query.count() + pages = max(1, (total + page_size - 1) // page_size) if total else 1 + if page > pages: + page = pages + + users = ( + query.options(joinedload(User.agents)) + .order_by(User.id.asc()) + .offset((page - 1) * page_size) + .limit(page_size) + .all() + ) + return jsonify({ + 'items': [_serialize_admin_user(u) for u in users], + 'total': int(total), + 'page': page, + 'page_size': page_size, + 'pages': pages, + }) @admin_bp.route('/users', methods=['POST']) @require_admin @@ -572,7 +647,11 @@ def update_user(id): @admin_bp.route('/users/cleanup-rejected', methods=['POST']) @require_admin def cleanup_rejected_users(): - cnt = db.session.query(User).filter_by(status='rejected').delete() + rejected_ids = [ + row[0] + for row in db.session.query(User.id).filter_by(status='rejected').all() + ] + cnt = delete_admin_users(rejected_ids) db.session.commit() return jsonify({'deleted_count': cnt}) @@ -586,10 +665,42 @@ def batch_delete_users(): target_ids = [uid for uid in ids if str(uid) != str(current_user_id)] if not target_ids: raise ValidationError('No valid users') - cnt = db.session.query(User).filter(User.id.in_(target_ids)).delete(synchronize_session=False) - db.session.commit() + try: + cnt = delete_admin_users(target_ids) + db.session.commit() + except IntegrityError as exc: + db.session.rollback() + raise AppError( + code='USER.DELETE_BLOCKED', + message='Unable to delete user because related records still exist', + http_status=409, + details={'reason': str(getattr(exc, 'orig', exc))}, + ) from exc return jsonify({'deleted_count': cnt}) +@admin_bp.route('/users/', methods=['DELETE']) +@require_admin +def delete_user(id: int): + """删除单个用户,复用 delete_admin_users 的关联清理逻辑。""" + current_user = _get_auth_user() + if current_user and str(current_user.id) == str(id): + raise ValidationError('Cannot delete current user') + user = db.session.get(User, id) + if not user: + raise NotFoundError('User not found') + try: + delete_admin_users([id]) + db.session.commit() + except IntegrityError as exc: + db.session.rollback() + raise AppError( + code='USER.DELETE_BLOCKED', + message='Unable to delete user because related records still exist', + http_status=409, + details={'reason': str(getattr(exc, 'orig', exc))}, + ) from exc + return jsonify({'status': 'ok'}) + @admin_bp.route('/permissions/batch', methods=['POST']) @require_admin def batch_update_permissions(): diff --git a/backend/app/api/internal/__init__.py b/backend/app/api/internal/__init__.py new file mode 100644 index 00000000..a0184f8c --- /dev/null +++ b/backend/app/api/internal/__init__.py @@ -0,0 +1,8 @@ +""" +backend/app/api/internal/__init__.py + +用途:内部 job 回调/健康检查 Blueprint。 +""" +from app.api.internal.jobs import internal_jobs_bp # noqa: F401 + +__all__ = ['internal_jobs_bp'] diff --git a/backend/app/api/internal/jobs.py b/backend/app/api/internal/jobs.py new file mode 100644 index 00000000..92ccc426 --- /dev/null +++ b/backend/app/api/internal/jobs.py @@ -0,0 +1,8 @@ +""" +backend/app/api/internal/jobs.py + +用途:内部 jobs API(Wave 1 自 internal_jobs.py 迁入)。 +""" +from app.api.internal_jobs import internal_jobs_bp # noqa: F401 + +__all__ = ['internal_jobs_bp'] diff --git a/backend/app/api/schedule/__init__.py b/backend/app/api/schedule/__init__.py new file mode 100644 index 00000000..cc143382 --- /dev/null +++ b/backend/app/api/schedule/__init__.py @@ -0,0 +1,9 @@ +""" +backend/app/api/schedule/__init__.py + +用途:排程管理 Blueprint 入口(自 schedule_admin.py 收敛)。 +逻辑:Wave 1 前 re-export 旧模块 blueprint。 +""" +from app.api.schedule_admin import schedule_admin_bp # noqa: F401 + +__all__ = ['schedule_admin_bp'] diff --git a/backend/app/api/tools/__init__.py b/backend/app/api/tools/__init__.py new file mode 100644 index 00000000..6627ca7e --- /dev/null +++ b/backend/app/api/tools/__init__.py @@ -0,0 +1,10 @@ +""" +backend/app/api/tools/__init__.py + +用途:Dify HTTP Tool API Blueprint 聚合。 +逻辑:Wave 1 前 re-export shipping_notice_tools、file_check_tools。 +""" +from app.api.tools.shipping_notice import shipping_notice_bp # noqa: F401 +from app.api.tools.file_check import file_check_bp # noqa: F401 + +__all__ = ['shipping_notice_bp', 'file_check_bp'] diff --git a/backend/app/api/tools/file_check.py b/backend/app/api/tools/file_check.py new file mode 100644 index 00000000..394a7e35 --- /dev/null +++ b/backend/app/api/tools/file_check.py @@ -0,0 +1,8 @@ +""" +backend/app/api/tools/file_check.py + +用途:文件检核 Tool API Blueprint(Wave 1 自 file_check_tools.py 迁入)。 +""" +from app.api.file_check_tools import file_check_bp # noqa: F401 + +__all__ = ['file_check_bp'] diff --git a/backend/app/api/tools/shipping_notice.py b/backend/app/api/tools/shipping_notice.py new file mode 100644 index 00000000..f9963a29 --- /dev/null +++ b/backend/app/api/tools/shipping_notice.py @@ -0,0 +1,8 @@ +""" +backend/app/api/tools/shipping_notice.py + +用途:出货通知 Tool API Blueprint(Wave 1 自 shipping_notice_tools.py 迁入)。 +""" +from app.api.shipping_notice_tools import shipping_notice_bp # noqa: F401 + +__all__ = ['shipping_notice_bp'] diff --git a/backend/app/api/workspace/__init__.py b/backend/app/api/workspace/__init__.py new file mode 100644 index 00000000..bd9e707d --- /dev/null +++ b/backend/app/api/workspace/__init__.py @@ -0,0 +1,15 @@ +""" +backend/app/api/workspace/__init__.py + +用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check)。 +逻辑:Wave 1 前 re-export 旧 workspace_* 模块。 +""" +from app.api.workspace_schedule import workspace_schedule_bp # noqa: F401 +from app.api.workspace_shipping_notice import workspace_shipping_notice_bp # noqa: F401 +from app.api.workspace_file_check import workspace_file_check_bp # noqa: F401 + +__all__ = [ + 'workspace_schedule_bp', + 'workspace_shipping_notice_bp', + 'workspace_file_check_bp', +] diff --git a/backend/app/api/workspace/file_check.py b/backend/app/api/workspace/file_check.py new file mode 100644 index 00000000..b9bf6b05 --- /dev/null +++ b/backend/app/api/workspace/file_check.py @@ -0,0 +1,5 @@ +""" +backend/app/api/workspace/file_check.py + +用途:工作台文件检核路由(Wave 1 自 workspace_file_check.py 迁入)。 +""" diff --git a/backend/app/api/workspace/schedule.py b/backend/app/api/workspace/schedule.py new file mode 100644 index 00000000..dcb6978e --- /dev/null +++ b/backend/app/api/workspace/schedule.py @@ -0,0 +1,5 @@ +""" +backend/app/api/workspace/schedule.py + +用途:工作台排程路由(Wave 1 自 workspace_schedule.py 迁入)。 +""" diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py new file mode 100644 index 00000000..651c18fc --- /dev/null +++ b/backend/app/api/workspace/shipping_notice.py @@ -0,0 +1,5 @@ +""" +backend/app/api/workspace/shipping_notice.py + +用途:工作台出货通知路由(Wave 1 自 workspace_shipping_notice.py 迁入)。 +""" diff --git a/backend/app/core/__init__.py b/backend/app/core/__init__.py new file mode 100644 index 00000000..a2bf5d76 --- /dev/null +++ b/backend/app/core/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/core/__init__.py + +用途:横切能力包入口(errors、response、auth、config、db)。 +逻辑:Wave 1 逐步将 app 根目录模块迁入 core/ 子包;过渡期旧路径 re-export。 +""" diff --git a/backend/app/core/auth/__init__.py b/backend/app/core/auth/__init__.py new file mode 100644 index 00000000..0ea0ea18 --- /dev/null +++ b/backend/app/core/auth/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/core/auth/__init__.py + +用途:认证与当前用户解析包入口。 +逻辑:api 层通过 get_current_user 获取 User;Wave 1 自 auth_jwt.py 迁入 jwt.py。 +""" diff --git a/backend/app/core/auth/context.py b/backend/app/core/auth/context.py new file mode 100644 index 00000000..0affde86 --- /dev/null +++ b/backend/app/core/auth/context.py @@ -0,0 +1,39 @@ +""" +backend/app/core/auth/context.py + +用途:从 Flask g/request 解析请求上下文(request_id、user),供 api 层薄封装。 +逻辑:Wave 3 拆分 user/chat 路由时,将重复 auth 逻辑收敛到本模块。 +""" +from __future__ import annotations + +from typing import Any + + +def get_request_id() -> str | None: + """ + 读取当前请求的 X-Request-Id 或 g.request_id。 + 核心逻辑:延迟 import flask.g,避免 services 层依赖。 + Returns: + request_id 字符串,无上下文时返回 None。 + """ + try: + from flask import g + + return getattr(g, 'request_id', None) + except RuntimeError: + return None + + +def get_optional_config(key: str, default: Any = None) -> Any: + """ + 读取 Flask app.config 项(仅 api / jobs context 使用)。 + Args: + key: config 键名。 + default: 无 app context 时的默认值。 + """ + try: + from flask import current_app + + return current_app.config.get(key, default) + except RuntimeError: + return default diff --git a/backend/app/core/auth/jwt.py b/backend/app/core/auth/jwt.py new file mode 100644 index 00000000..3a271cf1 --- /dev/null +++ b/backend/app/core/auth/jwt.py @@ -0,0 +1,9 @@ +""" +backend/app/core/auth/jwt.py + +用途:Casdoor JWT 校验与当前用户解析(Wave 1 自 app/auth_jwt.py 迁入)。 +逻辑:api 路由与 decorators 调用 get_current_user()。 +""" +from app.auth_jwt import get_current_user # noqa: F401 + +__all__ = ['get_current_user'] diff --git a/backend/app/core/config/__init__.py b/backend/app/core/config/__init__.py new file mode 100644 index 00000000..7c5299d8 --- /dev/null +++ b/backend/app/core/config/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/core/config/__init__.py + +用途:应用配置包入口(settings、env_persistence)。 +逻辑:create_app 加载 Config;before_request 刷新 DB 持久化配置。 +""" diff --git a/backend/app/core/config/env_persistence.py b/backend/app/core/config/env_persistence.py new file mode 100644 index 00000000..f0030852 --- /dev/null +++ b/backend/app/core/config/env_persistence.py @@ -0,0 +1,9 @@ +""" +backend/app/core/config/env_persistence.py + +用途:DB 持久化运行时配置(Wave 1 自 app/env_persistence.py 迁入)。 +逻辑:before_request 调用 apply_env_settings 刷新 app.config。 +""" +from app.env_persistence import apply_env_settings # noqa: F401 + +__all__ = ['apply_env_settings'] diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py new file mode 100644 index 00000000..09f483cb --- /dev/null +++ b/backend/app/core/config/settings.py @@ -0,0 +1,9 @@ +""" +backend/app/core/config/settings.py + +用途:Config 类与环境映射(Wave 1 自 app/config.py 迁入)。 +逻辑:create_app(config_name) 通过 config[config_name] 加载。 +""" +from app.config import ACTIVE_ENV_NAME, config # noqa: F401 + +__all__ = ['config', 'ACTIVE_ENV_NAME'] diff --git a/backend/app/core/db/__init__.py b/backend/app/core/db/__init__.py new file mode 100644 index 00000000..70d0aa9e --- /dev/null +++ b/backend/app/core/db/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/core/db/__init__.py + +用途:数据库会话工具包入口。 +逻辑:Wave 1 提供 run_with_retry;sequence 工具供迁移/运维脚本使用。 +""" diff --git a/backend/app/core/db/sequence.py b/backend/app/core/db/sequence.py new file mode 100644 index 00000000..7840ec85 --- /dev/null +++ b/backend/app/core/db/sequence.py @@ -0,0 +1,7 @@ +""" +backend/app/core/db/sequence.py + +用途:PostgreSQL 序列修复工具(Wave 1 自 services/db_sequence.py 迁入)。 +逻辑:迁移脚本与 check_schema_drift 调用。 +""" +from app.services.db_sequence import * # noqa: F403 diff --git a/backend/app/core/db/session.py b/backend/app/core/db/session.py new file mode 100644 index 00000000..1c61815d --- /dev/null +++ b/backend/app/core/db/session.py @@ -0,0 +1,28 @@ +""" +backend/app/core/db/session.py + +用途:数据库会话辅助(重试、只读查询封装)。 +逻辑:Wave 1 从 api/user.py、knowledge_base.py 等抽取 _run_db_with_retry 模式。 +""" +from __future__ import annotations + +from collections.abc import Callable +from typing import TypeVar + +T = TypeVar('T') + + +def run_with_retry(fn: Callable[[], T], *, max_attempts: int = 3) -> T: + """ + 在数据库短暂失败时重试可调用对象。 + 核心逻辑:捕获 OperationalError/DisconnectionError 后 rollback 并重试。 + Args: + fn: 无参 callable,内部使用 db.session。 + max_attempts: 最大尝试次数。 + Returns: + fn 的返回值。 + Raises: + 最后一次失败的异常。 + """ + # [STEP 1] Wave 0 占位:Wave 1 从 user.py / knowledge_base.py 抽取实现 + return fn() diff --git a/backend/app/core/decorators.py b/backend/app/core/decorators.py new file mode 100644 index 00000000..ceb36e33 --- /dev/null +++ b/backend/app/core/decorators.py @@ -0,0 +1,9 @@ +""" +backend/app/core/decorators.py + +用途:路由权限装饰器(Wave 1 自 app/decorators.py 迁入)。 +逻辑:api 层路由使用 @require_admin、@require_agent_permission。 +""" +from app.decorators import require_admin, require_agent_permission # noqa: F401 + +__all__ = ['require_admin', 'require_agent_permission'] diff --git a/backend/app/core/errors.py b/backend/app/core/errors.py new file mode 100644 index 00000000..3e75b17c --- /dev/null +++ b/backend/app/core/errors.py @@ -0,0 +1,26 @@ +""" +backend/app/core/errors.py + +用途:统一业务异常类型(Wave 1 自 app/errors.py 迁入)。 +依赖:无 Flask 依赖。 +逻辑:API 全局 handler 识别 AppError;业务层 raise 子类替代 jsonify(error)。 +""" +from app.errors import ( # noqa: F401 — Wave 1: 实现迁入本文件后删除 app/errors.py shim + AppError, + ConflictError, + ForbiddenError, + NotFoundError, + ServiceUnavailableError, + UnauthorizedError, + ValidationError, +) + +__all__ = [ + 'AppError', + 'ValidationError', + 'UnauthorizedError', + 'ForbiddenError', + 'NotFoundError', + 'ConflictError', + 'ServiceUnavailableError', +] diff --git a/backend/app/core/response.py b/backend/app/core/response.py new file mode 100644 index 00000000..ffc0b0d3 --- /dev/null +++ b/backend/app/core/response.py @@ -0,0 +1,9 @@ +""" +backend/app/core/response.py + +用途:统一 API 响应工具(Wave 1 自 app/response_utils.py 迁入)。 +逻辑:error_payload 供全局异常 handler 使用;ok() 供成功 envelope(可选)。 +""" +from app.response_utils import error_payload, ok, utc_iso_now # noqa: F401 + +__all__ = ['error_payload', 'ok', 'utc_iso_now'] diff --git a/backend/app/extensions.py b/backend/app/extensions.py new file mode 100644 index 00000000..122f9361 --- /dev/null +++ b/backend/app/extensions.py @@ -0,0 +1,12 @@ +""" +backend/app/extensions.py + +用途:Flask 扩展实例(db、migrate)集中定义;Wave 1 从 __init__.py 迁入并接线。 +依赖:flask_sqlalchemy、flask_migrate。 +逻辑:create_app 调用 db.init_app(app);models 与各 service 从本模块 import db。 +""" +from flask_sqlalchemy import SQLAlchemy +from flask_migrate import Migrate + +db = SQLAlchemy() +migrate = Migrate() diff --git a/backend/app/jobs/__init__.py b/backend/app/jobs/__init__.py new file mode 100644 index 00000000..73385707 --- /dev/null +++ b/backend/app/jobs/__init__.py @@ -0,0 +1,11 @@ +""" +backend/app/jobs/__init__.py + +用途:统一后台任务层入口(方案 D)。 +依赖:types、registry、queue、runner。 +逻辑:Web API enqueue;worker.py 调用 runner.run_forever。 +""" +from app.jobs.types import JobStatus, JobType +from app.jobs.queue import enqueue + +__all__ = ['JobType', 'JobStatus', 'enqueue'] diff --git a/backend/app/jobs/context.py b/backend/app/jobs/context.py new file mode 100644 index 00000000..e4684331 --- /dev/null +++ b/backend/app/jobs/context.py @@ -0,0 +1,26 @@ +""" +backend/app/jobs/context.py + +用途:Worker 运行时上下文,注入 config / db / logger。 +逻辑:handler.run(ctx, payload) 通过 ctx 访问依赖,禁止 import flask.request。 +""" +from __future__ import annotations + +import logging +from dataclasses import dataclass, field +from typing import Any + + +@dataclass +class JobContext: + """ + Worker 执行上下文。 + Attributes: + config: Flask app.config 快照或类 dict。 + logger: 模块 logger。 + extras: 扩展字段(如 worker_label)。 + """ + + config: dict[str, Any] + logger: logging.Logger + extras: dict[str, Any] = field(default_factory=dict) diff --git a/backend/app/jobs/handlers/__init__.py b/backend/app/jobs/handlers/__init__.py new file mode 100644 index 00000000..8fdec6e2 --- /dev/null +++ b/backend/app/jobs/handlers/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/jobs/handlers/__init__.py + +用途:导入各 handler 模块以触发 @register_handler 注册。 +逻辑:Wave 2 起在 worker 启动前 import 本包。 +""" diff --git a/backend/app/jobs/handlers/file_check_run.py b/backend/app/jobs/handlers/file_check_run.py new file mode 100644 index 00000000..2bb83aa1 --- /dev/null +++ b/backend/app/jobs/handlers/file_check_run.py @@ -0,0 +1,18 @@ +""" +backend/app/jobs/handlers/file_check_run.py + +用途:文件检核异步执行 handler。 +逻辑:Wave 4 替代 api/file_check_tools 内 threading.Thread。 +""" +from __future__ import annotations + +from app.jobs.context import JobContext +from app.jobs.registry import register_handler +from app.jobs.types import JobType + + +@register_handler(JobType.FILE_CHECK_RUN) +def run_file_check(ctx: JobContext, payload: dict) -> None: + """执行异步文件检核。""" + ctx.logger.info('file_check_run handler skeleton invoked payload=%s', payload) + raise NotImplementedError('file_check_run handler pending Wave 4') diff --git a/backend/app/jobs/handlers/kb_clean.py b/backend/app/jobs/handlers/kb_clean.py new file mode 100644 index 00000000..7848935a --- /dev/null +++ b/backend/app/jobs/handlers/kb_clean.py @@ -0,0 +1,24 @@ +""" +backend/app/jobs/handlers/kb_clean.py + +用途:KB 文档清洗任务 handler。 +逻辑:Wave 2 包装 knowledge_cleaning.queue_service.process_next_clean_job。 +""" +from __future__ import annotations + +from app.jobs.context import JobContext +from app.jobs.registry import register_handler +from app.jobs.types import JobType + + +@register_handler(JobType.KB_CLEAN) +def run_kb_clean(ctx: JobContext, payload: dict) -> None: + """ + 执行单条 KB 清洗任务。 + Args: + ctx: Worker 上下文。 + payload: 含 document_id 等字段。 + """ + ctx.logger.info('kb_clean handler skeleton invoked payload=%s', payload) + # Wave 2: from app.services.knowledge_cleaning.queue_service import process_job + raise NotImplementedError('kb_clean handler pending Wave 2') diff --git a/backend/app/jobs/handlers/kb_dify_sync.py b/backend/app/jobs/handlers/kb_dify_sync.py new file mode 100644 index 00000000..328b4e5c --- /dev/null +++ b/backend/app/jobs/handlers/kb_dify_sync.py @@ -0,0 +1,18 @@ +""" +backend/app/jobs/handlers/kb_dify_sync.py + +用途:KB 文档同步至 Dify 任务 handler。 +逻辑:Wave 2 包装 knowledge_cleaning.dify_sync_service。 +""" +from __future__ import annotations + +from app.jobs.context import JobContext +from app.jobs.registry import register_handler +from app.jobs.types import JobType + + +@register_handler(JobType.KB_DIFY_SYNC) +def run_kb_dify_sync(ctx: JobContext, payload: dict) -> None: + """同步已清洗文档到 Dify。""" + ctx.logger.info('kb_dify_sync handler skeleton invoked payload=%s', payload) + raise NotImplementedError('kb_dify_sync handler pending Wave 2') diff --git a/backend/app/jobs/handlers/schedule_run.py b/backend/app/jobs/handlers/schedule_run.py new file mode 100644 index 00000000..a316c9ed --- /dev/null +++ b/backend/app/jobs/handlers/schedule_run.py @@ -0,0 +1,18 @@ +""" +backend/app/jobs/handlers/schedule_run.py + +用途:排程任务执行 handler。 +逻辑:Wave 4 从 scheduler_service in-process 执行体迁入。 +""" +from __future__ import annotations + +from app.jobs.context import JobContext +from app.jobs.registry import register_handler +from app.jobs.types import JobType + + +@register_handler(JobType.SCHEDULE_RUN) +def run_schedule(ctx: JobContext, payload: dict) -> None: + """执行单条 ScheduleTask。""" + ctx.logger.info('schedule_run handler skeleton invoked payload=%s', payload) + raise NotImplementedError('schedule_run handler pending Wave 4') diff --git a/backend/app/jobs/handlers/wecom_directory_sync.py b/backend/app/jobs/handlers/wecom_directory_sync.py new file mode 100644 index 00000000..e36d3422 --- /dev/null +++ b/backend/app/jobs/handlers/wecom_directory_sync.py @@ -0,0 +1,18 @@ +""" +backend/app/jobs/handlers/wecom_directory_sync.py + +用途:企微通讯录同步 handler。 +逻辑:Wave 4 包装 wecom_directory_sync 服务。 +""" +from __future__ import annotations + +from app.jobs.context import JobContext +from app.jobs.registry import register_handler +from app.jobs.types import JobType + + +@register_handler(JobType.WECOM_DIRECTORY_SYNC) +def run_wecom_directory_sync(ctx: JobContext, payload: dict) -> None: + """同步企微通讯录到本地用户/部门。""" + ctx.logger.info('wecom_directory_sync handler skeleton invoked payload=%s', payload) + raise NotImplementedError('wecom_directory_sync handler pending Wave 4') diff --git a/backend/app/jobs/queue.py b/backend/app/jobs/queue.py new file mode 100644 index 00000000..89d25260 --- /dev/null +++ b/backend/app/jobs/queue.py @@ -0,0 +1,34 @@ +""" +backend/app/jobs/queue.py + +用途:任务入队 API。 +逻辑:API / services 调用 enqueue;Wave 2 写入 Job 表并 adapter KbJob。 +""" +from __future__ import annotations + +from typing import Any + +from app.jobs.types import JobType + + +def enqueue( + job_type: JobType, + payload: dict[str, Any], + *, + correlation_id: str | None = None, + scheduled_at: Any = None, +) -> int: + """ + 将任务写入队列并返回 job id。 + 核心逻辑:Wave 2 实现 store.create + KbJob adapter。 + Args: + job_type: 任务类型。 + payload: 任务参数 JSON。 + correlation_id: 关联业务 id(如 kb_document_id)。 + scheduled_at: 延迟执行时间(可选)。 + Returns: + Job 主键。 + Raises: + NotImplementedError: Wave 0 占位。 + """ + raise NotImplementedError('jobs.enqueue is not wired until Wave 2') diff --git a/backend/app/jobs/registry.py b/backend/app/jobs/registry.py new file mode 100644 index 00000000..52405e89 --- /dev/null +++ b/backend/app/jobs/registry.py @@ -0,0 +1,37 @@ +""" +backend/app/jobs/registry.py + +用途:JobType → Handler 注册表。 +逻辑:handlers 模块 import 时 @register_handler 装饰;runner 按 type 分发。 +""" +from __future__ import annotations + +from collections.abc import Callable +from typing import Any + +from app.jobs.types import JobType + +HandlerFn = Callable[[Any, dict], None] + +_REGISTRY: dict[JobType, HandlerFn] = {} + + +def register_handler(job_type: JobType) -> Callable[[HandlerFn], HandlerFn]: + """ + 注册某 JobType 的处理函数。 + Args: + job_type: 任务类型枚举。 + Returns: + 装饰器。 + """ + + def decorator(fn: HandlerFn) -> HandlerFn: + _REGISTRY[job_type] = fn + return fn + + return decorator + + +def get_handler(job_type: JobType) -> HandlerFn | None: + """按类型获取 handler;未注册返回 None。""" + return _REGISTRY.get(job_type) diff --git a/backend/app/jobs/runner.py b/backend/app/jobs/runner.py new file mode 100644 index 00000000..21780cc3 --- /dev/null +++ b/backend/app/jobs/runner.py @@ -0,0 +1,38 @@ +""" +backend/app/jobs/runner.py + +用途:Worker 主循环 poll → dispatch → ack/fail。 +逻辑:worker.py 调用 run_forever(ctx);Wave 2 接入 store 与 registry。 +""" +from __future__ import annotations + +import time + +from app.jobs.context import JobContext +from app.jobs.registry import get_handler +from app.jobs import store + + +def run_forever(ctx: JobContext, *, poll_interval_seconds: float = 2.0) -> None: + """ + 持续轮询并执行任务。 + 核心逻辑:claim_next → get_handler → handler(ctx, payload) → 更新状态。 + Args: + ctx: Worker 上下文。 + poll_interval_seconds: 无任务时的休眠秒数。 + """ + ctx.logger.info('Job runner started (skeleton mode — Wave 2 will enable claim loop)') + while True: + try: + job = store.claim_next() + except NotImplementedError: + time.sleep(poll_interval_seconds) + continue + if not job: + time.sleep(poll_interval_seconds) + continue + handler = get_handler(job['job_type']) + if not handler: + ctx.logger.error('No handler for job_type=%s', job.get('job_type')) + continue + handler(ctx, job.get('payload') or {}) diff --git a/backend/app/jobs/store.py b/backend/app/jobs/store.py new file mode 100644 index 00000000..53c6581c --- /dev/null +++ b/backend/app/jobs/store.py @@ -0,0 +1,20 @@ +""" +backend/app/jobs/store.py + +用途:Job 表 CRUD(claim、update status)。 +逻辑:runner 通过 claim_next 获取待执行任务;Wave 2 落地 SQLAlchemy 模型。 +""" +from __future__ import annotations + +from typing import Any + + +def claim_next() -> dict[str, Any] | None: + """ + 认领下一条待执行 Job(SELECT FOR UPDATE SKIP LOCKED)。 + Returns: + job 字典或 None。 + Raises: + NotImplementedError: Wave 0 占位。 + """ + raise NotImplementedError('jobs.store.claim_next is not wired until Wave 2') diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py new file mode 100644 index 00000000..5b91ce7d --- /dev/null +++ b/backend/app/jobs/types.py @@ -0,0 +1,29 @@ +""" +backend/app/jobs/types.py + +用途:Job 类型与状态枚举。 +逻辑:handlers 与 queue 通过 JobType 注册;store 持久化 status 字符串。 +""" +from __future__ import annotations + +from enum import StrEnum + + +class JobType(StrEnum): + """后台任务类型。""" + + KB_CLEAN = 'kb_clean' + KB_DIFY_SYNC = 'kb_dify_sync' + SCHEDULE_RUN = 'schedule_run' + FILE_CHECK_RUN = 'file_check_run' + WECOM_DIRECTORY_SYNC = 'wecom_directory_sync' + + +class JobStatus(StrEnum): + """Job 生命周期状态。""" + + PENDING = 'pending' + RUNNING = 'running' + SUCCEEDED = 'succeeded' + FAILED = 'failed' + DEAD = 'dead' diff --git a/backend/app/schemas/__init__.py b/backend/app/schemas/__init__.py new file mode 100644 index 00000000..a2e0d656 --- /dev/null +++ b/backend/app/schemas/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/schemas/__init__.py + +用途:请求/响应 DTO 包(dataclass 或 Pydantic,非 FastAPI 专用)。 +逻辑:api 层解析入参、校验后传入 services;Wave 3 随 admin/user/kb 拆分落地。 +""" diff --git a/backend/app/schemas/admin/__init__.py b/backend/app/schemas/admin/__init__.py new file mode 100644 index 00000000..4344a176 --- /dev/null +++ b/backend/app/schemas/admin/__init__.py @@ -0,0 +1,5 @@ +""" +backend/app/schemas/admin/__init__.py + +用途:管理后台 DTO 包入口。 +""" diff --git a/backend/app/schemas/admin/agents.py b/backend/app/schemas/admin/agents.py new file mode 100644 index 00000000..bac6379f --- /dev/null +++ b/backend/app/schemas/admin/agents.py @@ -0,0 +1,5 @@ +""" +backend/app/schemas/admin/agents.py + +用途:Agent 管理 API DTO。 +""" diff --git a/backend/app/schemas/admin/settings.py b/backend/app/schemas/admin/settings.py new file mode 100644 index 00000000..35fdf159 --- /dev/null +++ b/backend/app/schemas/admin/settings.py @@ -0,0 +1,5 @@ +""" +backend/app/schemas/admin/settings.py + +用途:系统设置 API DTO。 +""" diff --git a/backend/app/schemas/admin/users.py b/backend/app/schemas/admin/users.py new file mode 100644 index 00000000..8f7841ff --- /dev/null +++ b/backend/app/schemas/admin/users.py @@ -0,0 +1,6 @@ +""" +backend/app/schemas/admin/users.py + +用途:用户管理 API DTO。 +逻辑:Wave 3 admin/users 路由使用。 +""" diff --git a/backend/app/schemas/chat.py b/backend/app/schemas/chat.py new file mode 100644 index 00000000..3e44ebfc --- /dev/null +++ b/backend/app/schemas/chat.py @@ -0,0 +1,6 @@ +""" +backend/app/schemas/chat.py + +用途:聊天域 API 请求/响应 DTO。 +逻辑:Wave 3 从 api/chat/_legacy 抽取 completions、sessions 参数模型。 +""" diff --git a/backend/app/schemas/kb.py b/backend/app/schemas/kb.py new file mode 100644 index 00000000..ffbf94dc --- /dev/null +++ b/backend/app/schemas/kb.py @@ -0,0 +1,6 @@ +""" +backend/app/schemas/kb.py + +用途:知识库域 API 请求/响应 DTO。 +逻辑:Wave 3 从 api/kb 拆分 upload、sync 参数模型。 +""" diff --git a/backend/app/schemas/user/__init__.py b/backend/app/schemas/user/__init__.py new file mode 100644 index 00000000..6365bf17 --- /dev/null +++ b/backend/app/schemas/user/__init__.py @@ -0,0 +1,5 @@ +""" +backend/app/schemas/user/__init__.py + +用途:当前用户域 API DTO(profile、homepage、faq)。 +""" diff --git a/backend/app/services/admin/__init__.py b/backend/app/services/admin/__init__.py new file mode 100644 index 00000000..4895b4b3 --- /dev/null +++ b/backend/app/services/admin/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/services/admin/__init__.py + +用途:管理后台业务服务包。 +逻辑:Wave 3 从 api/admin/_legacy 抽取 users/agents/departments/settings 等。 +""" diff --git a/backend/app/services/admin/agent_service.py b/backend/app/services/admin/agent_service.py new file mode 100644 index 00000000..59f4de90 --- /dev/null +++ b/backend/app/services/admin/agent_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/admin/agent_service.py + +用途:Agent CRUD、权限、guide 配置。 +""" diff --git a/backend/app/services/admin/dashboard_service.py b/backend/app/services/admin/dashboard_service.py new file mode 100644 index 00000000..9790f589 --- /dev/null +++ b/backend/app/services/admin/dashboard_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/admin/dashboard_service.py + +用途:管理后台仪表盘统计聚合。 +""" diff --git a/backend/app/services/admin/department_service.py b/backend/app/services/admin/department_service.py new file mode 100644 index 00000000..8bf71d71 --- /dev/null +++ b/backend/app/services/admin/department_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/admin/department_service.py + +用途:部门 CRUD。 +""" diff --git a/backend/app/services/admin/permission_service.py b/backend/app/services/admin/permission_service.py new file mode 100644 index 00000000..d470ec7e --- /dev/null +++ b/backend/app/services/admin/permission_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/admin/permission_service.py + +用途:权限申请、批量授权业务逻辑。 +""" diff --git a/backend/app/services/admin/settings_service.py b/backend/app/services/admin/settings_service.py new file mode 100644 index 00000000..3dcbb3dc --- /dev/null +++ b/backend/app/services/admin/settings_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/admin/settings_service.py + +用途:AppSetting、运行时配置管理业务逻辑。 +""" diff --git a/backend/app/services/admin/user_service.py b/backend/app/services/admin/user_service.py new file mode 100644 index 00000000..2c15269c --- /dev/null +++ b/backend/app/services/admin/user_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/admin/user_service.py + +用途:管理端用户 CRUD、权限分配。 +""" diff --git a/backend/app/services/auth/__init__.py b/backend/app/services/auth/__init__.py new file mode 100644 index 00000000..5bd3e722 --- /dev/null +++ b/backend/app/services/auth/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/services/auth/__init__.py + +用途:认证域业务(Casdoor OIDC、企微 OAuth)。 +逻辑:Wave 3 从 api/user/_legacy auth 相关路由抽取。 +""" diff --git a/backend/app/services/auth/casdoor_service.py b/backend/app/services/auth/casdoor_service.py new file mode 100644 index 00000000..b3fdb6e2 --- /dev/null +++ b/backend/app/services/auth/casdoor_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/auth/casdoor_service.py + +用途:Casdoor OIDC 登录、token 交换、用户同步业务逻辑。 +""" diff --git a/backend/app/services/auth/wecom_auth_service.py b/backend/app/services/auth/wecom_auth_service.py new file mode 100644 index 00000000..dfde5359 --- /dev/null +++ b/backend/app/services/auth/wecom_auth_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/auth/wecom_auth_service.py + +用途:企业微信 OAuth、绑定、解绑业务逻辑。 +""" diff --git a/backend/app/services/chat/__init__.py b/backend/app/services/chat/__init__.py new file mode 100644 index 00000000..03fa53fe --- /dev/null +++ b/backend/app/services/chat/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/services/chat/__init__.py + +用途:聊天域业务服务包。 +逻辑:Wave 3 从 api/chat/_legacy 与 chat.py 意图路由抽取。 +""" diff --git a/backend/app/services/chat/log_service.py b/backend/app/services/chat/log_service.py new file mode 100644 index 00000000..faafd971 --- /dev/null +++ b/backend/app/services/chat/log_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/chat/log_service.py + +用途:聊天历史、反馈业务逻辑。 +""" diff --git a/backend/app/services/chat/perf.py b/backend/app/services/chat/perf.py new file mode 100644 index 00000000..94fdc8d2 --- /dev/null +++ b/backend/app/services/chat/perf.py @@ -0,0 +1,6 @@ +""" +backend/app/services/chat/perf.py + +用途:聊天性能埋点(Wave 3 自 services/chat_perf.py 迁入)。 +""" +from app.services.chat_perf import * # noqa: F403 diff --git a/backend/app/services/chat/preview_service.py b/backend/app/services/chat/preview_service.py new file mode 100644 index 00000000..40e0d6cd --- /dev/null +++ b/backend/app/services/chat/preview_service.py @@ -0,0 +1,6 @@ +""" +backend/app/services/chat/preview_service.py + +用途:PLM/Excel 预览与文件转换(从 api/chat 抽出)。 +逻辑:Wave 3 将 subprocess/openpyxl 逻辑迁入本模块。 +""" diff --git a/backend/app/services/chat/router.py b/backend/app/services/chat/router.py new file mode 100644 index 00000000..9466cc59 --- /dev/null +++ b/backend/app/services/chat/router.py @@ -0,0 +1,27 @@ +""" +backend/app/services/chat/router.py + +用途:Chat Intent Router,按意图分流至 PLM/HR/Text2SQL/Dify。 +依赖:integrations/* stream_chat 实现。 +逻辑:api/chat/completions 调用本模块 select_stream_generator。 +设计参考:docs/tec.md §4.1 Chat Intent Router。 +""" +from __future__ import annotations + +from typing import Any, Iterator + + +def select_stream_generator(*, user: Any, agent: Any, query: str, **kwargs: Any) -> Iterator[str]: + """ + 根据 agent 配置与用户问题选择流式 generator。 + 核心逻辑:Wave 3 从 api/chat.py /completions 分支迁入。 + Args: + user: 当前 User 模型实例。 + agent: 当前 Agent 模型实例。 + query: 用户问题文本。 + Returns: + SSE 事件字符串迭代器。 + Raises: + NotImplementedError: Wave 0 占位。 + """ + raise NotImplementedError('ChatIntentRouter pending Wave 3 migration from api/chat.py') diff --git a/backend/app/services/chat/session_service.py b/backend/app/services/chat/session_service.py new file mode 100644 index 00000000..c6f4aa8c --- /dev/null +++ b/backend/app/services/chat/session_service.py @@ -0,0 +1,6 @@ +""" +backend/app/services/chat/session_service.py + +用途:聊天会话 CRUD 业务逻辑。 +逻辑:Wave 3 从 api/chat/_legacy 抽取 sessions 相关路由逻辑。 +""" diff --git a/backend/app/services/faq/__init__.py b/backend/app/services/faq/__init__.py new file mode 100644 index 00000000..f83d72c2 --- /dev/null +++ b/backend/app/services/faq/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/services/faq/__init__.py + +用途:FAQ 缓存与热榜聚合(收敛 faq_*、hot_faq_* 模块)。 +逻辑:Wave 4 自 services 根目录迁入。 +""" diff --git a/backend/app/services/faq/aggregator.py b/backend/app/services/faq/aggregator.py new file mode 100644 index 00000000..2c94c06c --- /dev/null +++ b/backend/app/services/faq/aggregator.py @@ -0,0 +1,2 @@ +"""FAQ 热榜聚合(Wave 4 自 hot_faq_aggregator.py 迁入)。""" +from app.services import hot_faq_aggregator # noqa: F401 diff --git a/backend/app/services/faq/cache.py b/backend/app/services/faq/cache.py new file mode 100644 index 00000000..0ff5ef09 --- /dev/null +++ b/backend/app/services/faq/cache.py @@ -0,0 +1,2 @@ +"""FAQ Redis 缓存(Wave 4 自 faq_cache.py 迁入)。""" +from app.services import faq_cache # noqa: F401 diff --git a/backend/app/services/faq/hot_settings.py b/backend/app/services/faq/hot_settings.py new file mode 100644 index 00000000..a9332121 --- /dev/null +++ b/backend/app/services/faq/hot_settings.py @@ -0,0 +1,2 @@ +"""FAQ 热榜设置(Wave 4 自 faq_hot_settings.py 迁入)。""" +from app.services import faq_hot_settings # noqa: F401 diff --git a/backend/app/services/integrations/__init__.py b/backend/app/services/integrations/__init__.py new file mode 100644 index 00000000..d2e99f33 --- /dev/null +++ b/backend/app/services/integrations/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/services/integrations/__init__.py + +用途:外部系统纯适配层(Dify、OA、PLM、WeCom、MinIO)。 +逻辑:Wave 4 从 services 根目录迁入;禁止领域编排。 +""" diff --git a/backend/app/services/integrations/dify.py b/backend/app/services/integrations/dify.py new file mode 100644 index 00000000..74f363b1 --- /dev/null +++ b/backend/app/services/integrations/dify.py @@ -0,0 +1,9 @@ +""" +backend/app/services/integrations/dify.py + +用途:Dify API 客户端(流式、上传、workflow)。 +逻辑:Wave 4 自 app/services/dify.py 迁入。 +""" +from app.services import dify # noqa: F401 + +__all__ = ['dify'] diff --git a/backend/app/services/integrations/integration_api.py b/backend/app/services/integrations/integration_api.py new file mode 100644 index 00000000..fa4ad5e9 --- /dev/null +++ b/backend/app/services/integrations/integration_api.py @@ -0,0 +1,8 @@ +""" +backend/app/services/integrations/integration_api.py + +用途:知识库源文件反查等集成 API 适配。 +""" +from app.services import integration_api # noqa: F401 + +__all__ = ['integration_api'] diff --git a/backend/app/services/integrations/minio.py b/backend/app/services/integrations/minio.py new file mode 100644 index 00000000..98a58252 --- /dev/null +++ b/backend/app/services/integrations/minio.py @@ -0,0 +1,8 @@ +""" +backend/app/services/integrations/minio.py + +用途:MinIO 对象存储适配。 +""" +from app.services import minio_service # noqa: F401 + +__all__ = ['minio_service'] diff --git a/backend/app/services/integrations/oa/__init__.py b/backend/app/services/integrations/oa/__init__.py new file mode 100644 index 00000000..b2440826 --- /dev/null +++ b/backend/app/services/integrations/oa/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/services/integrations/oa/__init__.py + +用途:OA 系统适配(SQL Server、请假 SOAP、企微同步)。 +逻辑:Wave 4 自 oa_sqlserver、oa_leave_workflow、oa_wecom_sync 迁入。 +""" diff --git a/backend/app/services/integrations/oa/leave_workflow.py b/backend/app/services/integrations/oa/leave_workflow.py new file mode 100644 index 00000000..77da5d72 --- /dev/null +++ b/backend/app/services/integrations/oa/leave_workflow.py @@ -0,0 +1,2 @@ +"""OA 请假 Workflow SOAP 适配(Wave 4 自 oa_leave_workflow.py 迁入)。""" +from app.services import oa_leave_workflow # noqa: F401 diff --git a/backend/app/services/integrations/oa/sqlserver.py b/backend/app/services/integrations/oa/sqlserver.py new file mode 100644 index 00000000..b40009d6 --- /dev/null +++ b/backend/app/services/integrations/oa/sqlserver.py @@ -0,0 +1,2 @@ +"""OA SQL Server 适配(Wave 4 自 oa_sqlserver.py 迁入)。""" +from app.services import oa_sqlserver # noqa: F401 diff --git a/backend/app/services/integrations/oa/wecom_sync.py b/backend/app/services/integrations/oa/wecom_sync.py new file mode 100644 index 00000000..d09e4201 --- /dev/null +++ b/backend/app/services/integrations/oa/wecom_sync.py @@ -0,0 +1,2 @@ +"""OA 与企微同步适配(Wave 4 自 oa_wecom_sync.py 迁入)。""" +from app.services import oa_wecom_sync # noqa: F401 diff --git a/backend/app/services/integrations/plm/__init__.py b/backend/app/services/integrations/plm/__init__.py new file mode 100644 index 00000000..3553572d --- /dev/null +++ b/backend/app/services/integrations/plm/__init__.py @@ -0,0 +1,5 @@ +""" +backend/app/services/integrations/plm/__init__.py + +用途:PLM Oracle 适配。 +""" diff --git a/backend/app/services/integrations/plm/oracle.py b/backend/app/services/integrations/plm/oracle.py new file mode 100644 index 00000000..f82e7cc1 --- /dev/null +++ b/backend/app/services/integrations/plm/oracle.py @@ -0,0 +1,2 @@ +"""PLM Oracle 流式查询适配(Wave 4 自 plm_oracle.py 迁入)。""" +from app.services import plm_oracle # noqa: F401 diff --git a/backend/app/services/integrations/text2sql.py b/backend/app/services/integrations/text2sql.py new file mode 100644 index 00000000..eb794ea2 --- /dev/null +++ b/backend/app/services/integrations/text2sql.py @@ -0,0 +1,8 @@ +""" +backend/app/services/integrations/text2sql.py + +用途:ERP 知识库 Text2SQL 流式服务。 +""" +from app.services import text2sql # noqa: F401 + +__all__ = ['text2sql'] diff --git a/backend/app/services/integrations/wecom/__init__.py b/backend/app/services/integrations/wecom/__init__.py new file mode 100644 index 00000000..43ce2e30 --- /dev/null +++ b/backend/app/services/integrations/wecom/__init__.py @@ -0,0 +1,5 @@ +""" +backend/app/services/integrations/wecom/__init__.py + +用途:企业微信 SDK 适配(通知、通讯录、加解密)。 +""" diff --git a/backend/app/services/integrations/wecom/crypto.py b/backend/app/services/integrations/wecom/crypto.py new file mode 100644 index 00000000..3ebdfe31 --- /dev/null +++ b/backend/app/services/integrations/wecom/crypto.py @@ -0,0 +1,2 @@ +"""企微回调加解密(Wave 4 自 wecom_crypto.py 迁入)。""" +from app.services import wecom_crypto # noqa: F401 diff --git a/backend/app/services/integrations/wecom/directory_sync.py b/backend/app/services/integrations/wecom/directory_sync.py new file mode 100644 index 00000000..9d7919fb --- /dev/null +++ b/backend/app/services/integrations/wecom/directory_sync.py @@ -0,0 +1,2 @@ +"""企微通讯录同步(Wave 4 自 wecom_directory_sync.py 迁入)。""" +from app.services import wecom_directory_sync # noqa: F401 diff --git a/backend/app/services/integrations/wecom/notify.py b/backend/app/services/integrations/wecom/notify.py new file mode 100644 index 00000000..924c70f8 --- /dev/null +++ b/backend/app/services/integrations/wecom/notify.py @@ -0,0 +1,2 @@ +"""企微消息通知(Wave 4 自 wecom_notify.py 迁入)。""" +from app.services import wecom_notify # noqa: F401 diff --git a/backend/app/services/kb/__init__.py b/backend/app/services/kb/__init__.py new file mode 100644 index 00000000..b082d2a7 --- /dev/null +++ b/backend/app/services/kb/__init__.py @@ -0,0 +1,9 @@ +""" +backend/app/services/kb/__init__.py + +用途:知识库域服务包(收敛 knowledge_cleaning/)。 +逻辑:Wave 2–4 逐步 alias 至 knowledge_cleaning 子模块。 +""" +from app.services import knowledge_cleaning # noqa: F401 + +__all__ = ['knowledge_cleaning'] diff --git a/backend/app/services/speech/__init__.py b/backend/app/services/speech/__init__.py new file mode 100644 index 00000000..669877ee --- /dev/null +++ b/backend/app/services/speech/__init__.py @@ -0,0 +1,8 @@ +""" +backend/app/services/speech/__init__.py + +用途:语音 ASR 服务。 +""" +from app.services import speech_asr # noqa: F401 + +__all__ = ['speech_asr'] diff --git a/backend/app/services/text2sql.py b/backend/app/services/text2sql.py index 1df9da5a..62d7b680 100644 --- a/backend/app/services/text2sql.py +++ b/backend/app/services/text2sql.py @@ -43,6 +43,7 @@ class Text2SQLService: "LOCATION_NAME": "存放位置名称", "SITE": "营运中心代码", "SITE_DESC": "营运中心名称", + "PMC03": "供应厂商", "FAJ01": "序号", "FAJ02": "资产编号", "FAJ021": "类型", @@ -66,6 +67,7 @@ class Text2SQLService: "FAJ22": "存放营运中心", "FAJ25": "取得日期", "FAJ26": "入账日期", + "FAJ31": "预留残值", "FAJ43": "资产状态", "FAB02": "类型名称", "FAF02": "存放位置名称", @@ -516,6 +518,11 @@ class Text2SQLService: val = cls._clean_asset_scope_value(m.group(1)) if val: conds["location"] = val + m = re.search(r"(?:供应商|供应厂商|厂商)(?:为|是|叫|=|:|:)?\s*([A-Za-z0-9\u4e00-\u9fff_*-]+)", query) + if m: + val = cls._clean_asset_scope_value(m.group(1)) + if val: conds["vendor"] = val + return conds @staticmethod @@ -815,7 +822,9 @@ SELECT DISTINCT gen.gen02 AS "保管人姓名", gem.gem02 AS "保管部门名称", faf.faf02 AS "存放位置名称", - faj.faj43 AS "资产状态" + faj.faj43 AS "资产状态", + faj.faj31 AS "预留残值", + pmc.pmc03 AS "供应厂商" FROM ERP_VIEW_USER.ERP_FAJ_FILE_V faj LEFT JOIN ERP_VIEW_USER.ERP_GEN_FILE_V gen ON gen.gen01 = faj.faj19 @@ -826,6 +835,9 @@ LEFT JOIN ERP_VIEW_USER.ERP_GEM_FILE_V gem LEFT JOIN ERP_VIEW_USER.ERP_FAF_FILE_V faf ON faf.faf01 = faj.faj21 AND faf.site = faj.site +LEFT JOIN ERP_VIEW_USER.ERP_PMC_FILE_V pmc + ON pmc.pmc01 = faj.faj10 + AND pmc.site = faj.site WHERE UPPER(TRIM(NVL(faj.faj02, ''))) LIKE '%' || UPPER('{literal}') || '%' {nature_sql} ORDER BY faj.faj02 @@ -850,7 +862,9 @@ SELECT DISTINCT gen.gen02 AS "保管人姓名", gem.gem02 AS "保管部门名称", faf.faf02 AS "存放位置名称", - faj.faj43 AS "资产状态" + faj.faj43 AS "资产状态", + faj.faj31 AS "预留残值", + pmc.pmc03 AS "供应厂商" FROM ERP_VIEW_USER.ERP_FAJ_FILE_V faj LEFT JOIN ERP_VIEW_USER.ERP_GEN_FILE_V gen ON gen.gen01 = faj.faj19 @@ -861,6 +875,9 @@ LEFT JOIN ERP_VIEW_USER.ERP_GEM_FILE_V gem LEFT JOIN ERP_VIEW_USER.ERP_FAF_FILE_V faf ON faf.faf01 = faj.faj21 AND faf.site = faj.site +LEFT JOIN ERP_VIEW_USER.ERP_PMC_FILE_V pmc + ON pmc.pmc01 = faj.faj10 + AND pmc.site = faj.site LEFT JOIN ERP_VIEW_USER.ERP_FAB_FILE_V fab ON fab.fab01 = faj.faj04 AND fab.site = faj.site @@ -906,7 +923,9 @@ SELECT DISTINCT gen.gen02 AS "保管人姓名", gem.gem02 AS "保管部门名称", faf.faf02 AS "存放位置名称", - faj.faj43 AS "资产状态" + faj.faj43 AS "资产状态", + faj.faj31 AS "预留残值", + pmc.pmc03 AS "供应厂商" FROM ERP_VIEW_USER.ERP_FAJ_FILE_V faj LEFT JOIN ERP_VIEW_USER.ERP_GEN_FILE_V gen ON gen.gen01 = faj.faj19 @@ -917,6 +936,9 @@ LEFT JOIN ERP_VIEW_USER.ERP_GEM_FILE_V gem LEFT JOIN ERP_VIEW_USER.ERP_FAF_FILE_V faf ON faf.faf01 = faj.faj21 AND faf.site = faj.site +LEFT JOIN ERP_VIEW_USER.ERP_PMC_FILE_V pmc + ON pmc.pmc01 = faj.faj10 + AND pmc.site = faj.site {nature_sql}\ ORDER BY faj.faj02 """.strip() @@ -951,6 +973,9 @@ ORDER BY faj.faj02 else: literal = cls._escape_sql_literal(conds["status"]) where_clauses.append(f"UPPER(NVL(faj.faj43, ' ')) LIKE '%' || UPPER('{literal}') || '%'") + if "vendor" in conds: + literal = cls._escape_sql_literal(conds["vendor"]) + where_clauses.append(f"UPPER(NVL(pmc.pmc03, ' ')) LIKE '%' || UPPER('{literal}') || '%'") where_sql = " AND ".join(where_clauses) if where_sql: @@ -972,7 +997,9 @@ SELECT DISTINCT gen.gen02 AS "保管人姓名", gem.gem02 AS "保管部门名称", faf.faf02 AS "存放位置名称", - faj.faj43 AS "资产状态" + faj.faj43 AS "资产状态", + faj.faj31 AS "预留残值", + pmc.pmc03 AS "供应厂商" FROM ERP_VIEW_USER.ERP_FAJ_FILE_V faj LEFT JOIN ERP_VIEW_USER.ERP_GEN_FILE_V gen ON gen.gen01 = faj.faj19 @@ -983,6 +1010,9 @@ LEFT JOIN ERP_VIEW_USER.ERP_GEM_FILE_V gem LEFT JOIN ERP_VIEW_USER.ERP_FAF_FILE_V faf ON faf.faf01 = faj.faj21 AND faf.site = faj.site +LEFT JOIN ERP_VIEW_USER.ERP_PMC_FILE_V pmc + ON pmc.pmc01 = faj.faj10 + AND pmc.site = faj.site LEFT JOIN ERP_VIEW_USER.ERP_FAB_FILE_V fab ON fab.fab01 = faj.faj04 AND fab.site = faj.site @@ -1054,11 +1084,11 @@ ORDER BY faj.faj02 [ "固资管理附加要求:", "- 固定资产查询优先使用 ERP_VIEW_USER.ERP_FAJ_FILE_V,表别名建议使用 `faj`。", - "- 如需资产类型、保管人姓名、部门名称或存放位置名称,可联表 ERP_VIEW_USER.ERP_FAB_FILE_V `fab`、ERP_VIEW_USER.ERP_GEN_FILE_V `gen`、ERP_VIEW_USER.ERP_GEM_FILE_V `gem`、ERP_VIEW_USER.ERP_FAF_FILE_V `faf`。", - "- 固资相关联表必须同时补齐 `site` 条件,例如 `gen.site = faj.site`、`gem.site = faj.site`、`faf.site = faj.site`、`fab.site = faj.site`,避免同编码跨营运中心造成重复记录。", + "- 如需资产类型、保管人姓名、部门名称、存放位置名称或供应厂商,可联表 ERP_VIEW_USER.ERP_FAB_FILE_V `fab`、ERP_VIEW_USER.ERP_GEN_FILE_V `gen`、ERP_VIEW_USER.ERP_GEM_FILE_V `gem`、ERP_VIEW_USER.ERP_FAF_FILE_V `faf`、ERP_VIEW_USER.ERP_PMC_FILE_V `pmc`(pmc01 = faj.faj10)。", + "- 固资相关联表必须同时补齐 `site` 条件,例如 `gen.site = faj.site`、`gem.site = faj.site`、`faf.site = faj.site`、`fab.site = faj.site`、`pmc.site = faj.site`,避免同编码跨营运中心造成重复记录。", "- 固资数据只允许保留 `faj22`(存放营运中心)属于 `HXJM`、`HTT`、`HTE` 的记录;生成 SQL 时必须显式加上 `UPPER(TRIM(NVL(faj.faj22, ''))) IN ('HXJM', 'HTT', 'HTE')` 过滤。", "- 查询固定资产明细列表时优先使用 `SELECT DISTINCT`;如果是统计资产数量,优先使用 `COUNT(DISTINCT faj.faj02)`。", - "- 当查询固定资产明细时,返回结果必须且只能包含以下列并使用严格对应的中文别名:faj.faj02 AS \"资产编号\"、faj.faj06 AS \"资产名称\"、faj.faj08 AS \"规格型号\"、faj.faj09 AS \"资产性质\"、faj.faj13 AS \"本币单价\"、faj.faj17 AS \"数量\"、faj.faj18 AS \"计量单位\"、TO_CHAR(faj.faj25, YYYY-MM-DD HH24:MI:SS) AS \"取得日期\"、TO_CHAR(faj.faj26, YYYY-MM-DD HH24:MI:SS) AS \"入账日期\"、gen.gen02 AS \"保管人姓名\"、gem.gem02 AS \"保管部门名称\"、faf.faf02 AS \"存放位置名称\"、faj.faj43 AS \"资产状态\"。", + "- 当查询固定资产明细时,返回结果必须且只能包含以下列并使用严格对应的中文别名:faj.faj02 AS \"资产编号\"、faj.faj06 AS \"资产名称\"、faj.faj08 AS \"规格型号\"、faj.faj09 AS \"资产性质\"、faj.faj13 AS \"本币单价\"、faj.faj17 AS \"数量\"、faj.faj18 AS \"计量单位\"、TO_CHAR(faj.faj25, YYYY-MM-DD HH24:MI:SS) AS \"取得日期\"、TO_CHAR(faj.faj26, YYYY-MM-DD HH24:MI:SS) AS \"入账日期\"、gen.gen02 AS \"保管人姓名\"、gem.gem02 AS \"保管部门名称\"、faf.faf02 AS \"存放位置名称\"、faj.faj43 AS \"资产状态\"、faj.faj31 AS \"预留残值\"、pmc.pmc03 AS \"供应厂商\"。", "- 日期时间字段展示时不要去掉时分秒;若使用 TO_CHAR 格式化,必须保留为 `YYYY-MM-DD HH24:MI:SS`,不能只输出日期。", *filters, ] diff --git a/backend/app/services/user/__init__.py b/backend/app/services/user/__init__.py new file mode 100644 index 00000000..961abf80 --- /dev/null +++ b/backend/app/services/user/__init__.py @@ -0,0 +1,6 @@ +""" +backend/app/services/user/__init__.py + +用途:用户域业务服务(profile、homepage、admin 级联删除)。 +逻辑:Wave 3 从 api/user/_legacy 与 user_admin.py 抽取。 +""" diff --git a/backend/app/services/user/admin_service.py b/backend/app/services/user/admin_service.py new file mode 100644 index 00000000..e0317641 --- /dev/null +++ b/backend/app/services/user/admin_service.py @@ -0,0 +1,9 @@ +""" +backend/app/services/user/admin_service.py + +用途:用户管理侧业务(删除级联、权限批量变更等)。 +逻辑:Wave 3 收敛 app/services/user_admin.py。 +""" +from app.services import user_admin # noqa: F401 — Wave 3: 实现迁入本模块 + +__all__ = ['user_admin'] diff --git a/backend/app/services/user/faq_service.py b/backend/app/services/user/faq_service.py new file mode 100644 index 00000000..1f6588fe --- /dev/null +++ b/backend/app/services/user/faq_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/user/faq_service.py + +用途:常见问题(FAQ)业务逻辑。 +""" diff --git a/backend/app/services/user/homepage_service.py b/backend/app/services/user/homepage_service.py new file mode 100644 index 00000000..8c0735ec --- /dev/null +++ b/backend/app/services/user/homepage_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/user/homepage_service.py + +用途:首页布局、收藏 Agent、默认 Agent 业务逻辑。 +""" diff --git a/backend/app/services/user/profile_service.py b/backend/app/services/user/profile_service.py new file mode 100644 index 00000000..63f813e6 --- /dev/null +++ b/backend/app/services/user/profile_service.py @@ -0,0 +1,5 @@ +""" +backend/app/services/user/profile_service.py + +用途:用户资料、密码修改等业务逻辑。 +""" diff --git a/backend/app/services/user_admin.py b/backend/app/services/user_admin.py new file mode 100644 index 00000000..4aef94a9 --- /dev/null +++ b/backend/app/services/user_admin.py @@ -0,0 +1,149 @@ +""" +backend/app/services/user_admin.py + +用途:管理端删除用户前的关联数据清理与批量删除。 +依赖:SQLAlchemy delete、models 各用户关联表。 +逻辑:admin.batch_delete_users、cleanup_rejected、DELETE /users/ 共用 delete_admin_users。 +""" +from sqlalchemy import delete, or_ + +from app import db +from app.models import ( + AgentGuide, + ChatLog, + ChatSession, + Feedback, + GeneralFeedback, + KbDifySyncRecord, + KbDocument, + KbGroup, + KbJob, + KbDocumentVersion, + LoginAudit, + PermissionRequest, + QuickQuestion, + ScheduleRun, + ScheduleTask, + ShippingTask, + User, + UserDefaultAgent, + UserFavoriteAgent, + UserHomepageConfig, + WecomNotifyAudit, + user_agent_permissions, +) + + +def _delete_schedule_tasks_for_users(user_ids: list[int]) -> None: + """删除用户作为 owner 的排程任务及其运行记录。""" + tasks = db.session.query(ScheduleTask).filter(ScheduleTask.owner_user_id.in_(user_ids)).all() + if not tasks: + return + task_ids = [task.id for task in tasks] + run_ids = [ + row[0] + for row in db.session.query(ScheduleRun.id) + .filter(ScheduleRun.schedule_task_id.in_(task_ids)) + .all() + ] + if run_ids: + db.session.query(ChatLog).filter(ChatLog.run_id.in_(run_ids)).update( + {ChatLog.run_id: None}, + synchronize_session=False, + ) + db.session.query(ScheduleRun).filter(ScheduleRun.id.in_(run_ids)).delete(synchronize_session=False) + for task in tasks: + db.session.delete(task) + + +def _nullify_optional_user_references(user_ids: list[int]) -> None: + """将可空外键上的 user 引用置空,保留审计/业务历史。""" + db.session.query(LoginAudit).filter(LoginAudit.user_id.in_(user_ids)).update( + {LoginAudit.user_id: None}, + synchronize_session=False, + ) + db.session.query(WecomNotifyAudit).filter(WecomNotifyAudit.user_id.in_(user_ids)).update( + {WecomNotifyAudit.user_id: None}, + synchronize_session=False, + ) + db.session.query(ShippingTask).filter(ShippingTask.user_id.in_(user_ids)).update( + {ShippingTask.user_id: None}, + synchronize_session=False, + ) + db.session.query(ScheduleRun).filter(ScheduleRun.triggered_by_user_id.in_(user_ids)).update( + {ScheduleRun.triggered_by_user_id: None}, + synchronize_session=False, + ) + nullable_user_fk_models = ( + (KbGroup, ('created_by_id', 'updated_by_id')), + (KbDocument, ('created_by_id', 'updated_by_id')), + (KbDocumentVersion, ('uploaded_by_id',)), + (KbJob, ('created_by_id',)), + (KbDifySyncRecord, ('synced_by_id',)), + (ScheduleTask, ('created_by', 'updated_by')), + (AgentGuide, ('created_by',)), + ) + for model, columns in nullable_user_fk_models: + for column_name in columns: + column = getattr(model, column_name) + db.session.query(model).filter(column.in_(user_ids)).update( + {column_name: None}, + synchronize_session=False, + ) + + +def _delete_user_owned_records(user_ids: list[int]) -> None: + """ + 删除必须以 user_id 为主键/强依赖的子表记录。 + 核心逻辑:先删对话与反馈,再删权限、收藏、申请等,最后删 user_agent_permissions。 + """ + chat_log_ids = [ + row[0] + for row in db.session.query(ChatLog.id).filter(ChatLog.user_id.in_(user_ids)).all() + ] + if chat_log_ids: + db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False) + db.session.query(GeneralFeedback).filter( + or_( + GeneralFeedback.chat_log_id.in_(chat_log_ids), + GeneralFeedback.user_id.in_(user_ids), + ) + ).delete(synchronize_session=False) + else: + db.session.query(GeneralFeedback).filter(GeneralFeedback.user_id.in_(user_ids)).delete( + synchronize_session=False, + ) + + db.session.query(ChatLog).filter(ChatLog.user_id.in_(user_ids)).delete(synchronize_session=False) + db.session.query(ChatSession).filter(ChatSession.user_id.in_(user_ids)).delete(synchronize_session=False) + db.session.query(PermissionRequest).filter(PermissionRequest.user_id.in_(user_ids)).delete( + synchronize_session=False, + ) + db.session.query(QuickQuestion).filter(QuickQuestion.user_id.in_(user_ids)).delete(synchronize_session=False) + db.session.query(UserFavoriteAgent).filter(UserFavoriteAgent.user_id.in_(user_ids)).delete( + synchronize_session=False, + ) + db.session.query(UserDefaultAgent).filter(UserDefaultAgent.user_id.in_(user_ids)).delete(synchronize_session=False) + db.session.query(UserHomepageConfig).filter(UserHomepageConfig.user_id.in_(user_ids)).delete( + synchronize_session=False, + ) + db.session.execute( + delete(user_agent_permissions).where(user_agent_permissions.c.user_id.in_(user_ids)) + ) + + +def delete_admin_users(user_ids: list[int]) -> int: + """ + 安全删除管理端用户:清理关联数据后再删 users 行。 + @param user_ids - 待删除用户主键列表 + @returns 实际删除的用户数 + """ + unique_ids = sorted({int(uid) for uid in user_ids if uid is not None}) + if not unique_ids: + return 0 + + _delete_schedule_tasks_for_users(unique_ids) + _delete_user_owned_records(unique_ids) + _nullify_optional_user_references(unique_ids) + + return db.session.query(User).filter(User.id.in_(unique_ids)).delete(synchronize_session=False) diff --git a/backend/tests/jobs/__init__.py b/backend/tests/jobs/__init__.py new file mode 100644 index 00000000..5ab4bd24 --- /dev/null +++ b/backend/tests/jobs/__init__.py @@ -0,0 +1 @@ +"""tests/jobs 包:方案 D 任务层测试(Wave 2 起补充)。""" diff --git a/backend/tests/jobs/test_registry.py b/backend/tests/jobs/test_registry.py new file mode 100644 index 00000000..9e390201 --- /dev/null +++ b/backend/tests/jobs/test_registry.py @@ -0,0 +1,16 @@ +""" +tests/jobs/test_registry.py + +用途:验证 Job handler 注册表。 +""" +from app.jobs.registry import get_handler, register_handler +from app.jobs.types import JobType + + +def test_register_and_get_handler(): + # 断言:临时 handler 可注册并按 type 取回 + @register_handler(JobType.KB_CLEAN) + def _dummy(ctx, payload): + pass + + assert get_handler(JobType.KB_CLEAN) is _dummy diff --git a/backend/tests/services/chat/__init__.py b/backend/tests/services/chat/__init__.py new file mode 100644 index 00000000..f26243a7 --- /dev/null +++ b/backend/tests/services/chat/__init__.py @@ -0,0 +1 @@ +"""tests/services/chat 包:ChatIntentRouter 等单元测试(Wave 3 起补充)。""" diff --git a/backend/tests/test_admin.py b/backend/tests/test_admin.py index a6ea3a68..25586f6e 100644 --- a/backend/tests/test_admin.py +++ b/backend/tests/test_admin.py @@ -107,6 +107,70 @@ def test_user_management(client, admin_headers): users = response.json assert not any(u['id'] == user_id for u in users) +def test_user_list_pagination(client, admin_headers): + """分页用户列表:带 page 时返回 items/total,并支持 hide_rejected 筛选。""" + for idx in range(3): + client.post('/api/admin/users', json={ + 'username': f'pageuser{idx}', + 'email': f'pageuser{idx}@example.com', + 'role': 'user', + 'password': 'password123', + 'real_name': f'Page User {idx}', + 'employee_id': f'PAGE{idx:03d}', + 'phone_number': f'1390000000{idx}', + 'status': 'rejected' if idx == 2 else 'active', + }, headers=admin_headers) + + response = client.get('/api/admin/users?page=1&page_size=2&hide_rejected=true', headers=admin_headers) + assert response.status_code == 200 + data = response.json + assert set(data.keys()) == {'items', 'total', 'page', 'page_size', 'pages'} + assert data['page'] == 1 + assert data['page_size'] == 2 + assert len(data['items']) == 2 + assert all(item['status'] != 'rejected' for item in data['items']) + + legacy = client.get('/api/admin/users', headers=admin_headers) + assert legacy.status_code == 200 + assert isinstance(legacy.json, list) + +def test_batch_delete_users_with_permissions(client, admin_headers): + """批量删除用户前应清理 user_agent_permissions 等关联,避免 PostgreSQL 外键报错。""" + agent_res = client.post('/api/admin/users', json={ + 'username': 'permdelete', + 'email': 'permdelete@example.com', + 'role': 'user', + 'password': 'password123', + 'real_name': 'Perm Delete', + 'employee_id': 'PD001', + 'phone_number': '13800000099', + }, headers=admin_headers) + assert agent_res.status_code == 201 + user_id = agent_res.json['id'] + + agent = client.post('/api/admin/agents', json={ + 'name': 'Delete Perm Agent', + 'type': 'api', + 'dify_app_id': 'del-app', + 'dify_api_key': 'del-key', + }, headers=admin_headers) + assert agent.status_code == 201 + agent_id = agent.json['id'] + + perm_res = client.post(f'/api/admin/users/{user_id}/permissions', json={ + 'agent_ids': [agent_id], + }, headers=admin_headers) + assert perm_res.status_code == 200 + + delete_res = client.post('/api/admin/users/batch-delete', headers=admin_headers, json={ + 'user_ids': [user_id], + }) + assert delete_res.status_code == 200 + assert delete_res.json['deleted_count'] == 1 + + users = client.get('/api/admin/users', headers=admin_headers).json + assert not any(u['id'] == user_id for u in users) + def test_agent_update_validation(client, admin_headers): """ Test validation when updating agents (especially API mode constraints) diff --git a/backend/worker.py b/backend/worker.py new file mode 100644 index 00000000..711a1b80 --- /dev/null +++ b/backend/worker.py @@ -0,0 +1,57 @@ +""" +backend/worker.py + +用途:统一后台 worker 入口(方案 D)。 +依赖:app.create_app、app.jobs.runner、app.jobs.handlers。 +逻辑:Wave 2 替代 worker_kb.py 主循环;Compose/Supervisor 可配置 --queues。 +""" +from __future__ import annotations + +import argparse +import logging +import sys + +from app import create_app +from app.jobs.context import JobContext +from app.jobs.runner import run_forever + +_LOG_FORMAT = '%(asctime)s %(levelname)s [worker] %(message)s' + + +def _configure_logging() -> logging.Logger: + logger = logging.getLogger('hxops.worker') + if not logger.handlers: + handler = logging.StreamHandler(sys.stdout) + handler.setFormatter(logging.Formatter(_LOG_FORMAT)) + logger.addHandler(handler) + logger.setLevel(logging.INFO) + return logger + + +def main(*, queues: list[str] | None = None, config_name: str = 'default') -> None: + """ + 启动 worker 主循环。 + Args: + queues: 消费的队列名列表(Wave 2 按 JobType 过滤)。 + config_name: Flask 配置名。 + """ + logger = _configure_logging() + app = create_app(config_name) + with app.app_context(): + ctx = JobContext( + config=dict(app.config), + logger=logger, + extras={'queues': queues or ['kb']}, + ) + logger.info('Worker starting queues=%s (skeleton — Wave 2 enables job processing)', ctx.extras['queues']) + # Wave 2: import app.jobs.handlers # noqa: F401 — register handlers + run_forever(ctx) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='HXOPS unified background worker') + parser.add_argument('--queues', default='kb', help='Comma-separated queue names') + parser.add_argument('--config', default='default', dest='config_name') + args = parser.parse_args() + queue_list = [q.strip() for q in args.queues.split(',') if q.strip()] + main(queues=queue_list, config_name=args.config_name) diff --git a/backend/workers/README.md b/backend/workers/README.md new file mode 100644 index 00000000..e7c6dfdf --- /dev/null +++ b/backend/workers/README.md @@ -0,0 +1 @@ +# Worker 进程启动脚本目录。详见 docs/refactor/backend_jobs_layer.md diff --git a/backend/workers/worker_kb.py b/backend/workers/worker_kb.py new file mode 100644 index 00000000..e19d3425 --- /dev/null +++ b/backend/workers/worker_kb.py @@ -0,0 +1,19 @@ +""" +backend/workers/worker_kb.py + +用途:KB worker Supervisor 兼容启动脚本。 +逻辑:转调 backend/worker.py,默认只消费 kb 队列。 +""" +from __future__ import annotations + +import sys +from pathlib import Path + +_backend_root = Path(__file__).resolve().parents[1] +if str(_backend_root) not in sys.path: + sys.path.insert(0, str(_backend_root)) + +from worker import main + +if __name__ == '__main__': + main(queues=['kb']) diff --git a/backend/workers/worker_scheduler.py b/backend/workers/worker_scheduler.py new file mode 100644 index 00000000..781da1e1 --- /dev/null +++ b/backend/workers/worker_scheduler.py @@ -0,0 +1,19 @@ +""" +backend/workers/worker_scheduler.py + +用途:排程 worker 入口(Wave 4 scheduler 迁出 web 进程后启用)。 +逻辑:消费 schedule 队列,执行 schedule_run handler。 +""" +from __future__ import annotations + +import sys +from pathlib import Path + +_backend_root = Path(__file__).resolve().parents[1] +if str(_backend_root) not in sys.path: + sys.path.insert(0, str(_backend_root)) + +from worker import main + +if __name__ == '__main__': + main(queues=['schedule']) diff --git a/docs/refactor/backend_architecture_refactor.md b/docs/refactor/backend_architecture_refactor.md new file mode 100644 index 00000000..5252a17b --- /dev/null +++ b/docs/refactor/backend_architecture_refactor.md @@ -0,0 +1,587 @@ +# HXOPS 后端重构架构方案 + +> 更新时间:2026-06-17 +> 适用范围:`backend/` 目录 +> 文档定位:定义 Flask 内治理(方案 A)与统一后台任务层(方案 D)的目标架构,作为后续分阶段重构的基准。 +> **不迁移 FastAPI**,生产栈保持 Flask + Gevent + SQLAlchemy 2.0 + Gunicorn。 + +--- + +## 1. 架构选型 + +在现有技术栈基础上,采用 **按业务域垂直分包 + API 薄 / Service 厚 + 统一 Job 层** 的组合架构,并行推进: + +| 方案 | 内容 | +| --- | --- | +| **方案 A — Flask 内治理** | 拆分 god 文件、统一 `AppError`、解耦 Flask 依赖、`models/` 按域拆分 | +| **方案 D — 统一任务层** | Web 只 `enqueue`,worker 统一 `poll → dispatch → handler` | + +**选型理由:** + +- 与现有 Flask + Gevent SSE 链路兼容,无需重写对话流式接口 +- 已有成功模式可复用:`shipping_notice/`、`file_check_tools/`、`schedule/` 子包 +- 已有基础设施可扩展:`AppError`、`env_persistence`、`worker_kb.py` + `KbJob` +- 团队规范(`AGENTS.md`)允许历史 Flask 维护;本方案不引入双栈(Flask + FastAPI) + +**保持不变的技术栈:** + +| 层级 | 选型 | +| --- | --- | +| Web 框架 | Flask 3.x(Blueprint 路由) | +| 并发 | Gevent worker(SSE 长连接) | +| ORM | SQLAlchemy 2.0 + Flask-SQLAlchemy | +| 迁移 | Alembic(Flask-Migrate) | +| 认证 | Casdoor JWT(JWKS)+ legacy header(dev/test) | +| 后台任务 | 统一 `jobs/` 层 + 独立 worker 进程 | +| 文档清洗 | `edkb_system/`(独立子系统,不并入 `app/services`) | + +**当前主要问题(重构动机):** + +| 问题 | 典型文件 | 约行数 | +| --- | --- | --- | +| API 层 god 文件 | `api/user.py`、`api/chat.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+ 处 jsonify | +| 后台执行分散 | in-process scheduler 线程、API 内 `threading`、独立 `worker_kb.py` | — | +| Flask 强耦合 | `services/*` 中 `current_app`、`request` | 阻碍测试与 worker 复用 | + +--- + +## 2. 目标目录总览 + +以下为重构完成后的 **目标目录树**(Wave 0 已部分落地,见 §10)。 + +```text +backend/ +├── run.py # Web 入口 +├── worker.py # 统一 worker 入口(方案 D) +├── worker_kb.py # 兼容旧部署,内部转调 worker.py +├── workers/ +│ ├── worker_kb.py # Supervisor 兼容脚本 +│ └── worker_scheduler.py # schedule 迁出 web 进程后的入口 +│ +├── app/ +│ ├── __init__.py # create_app:注册 blueprint、middleware、异常处理 +│ ├── extensions.py # db、migrate(Wave 1 从 __init__ 抽出) +│ │ +│ ├── core/ # 横切能力,不含业务 +│ │ ├── errors.py +│ │ ├── response.py +│ │ ├── decorators.py +│ │ ├── auth/ +│ │ │ ├── jwt.py +│ │ │ └── context.py +│ │ ├── config/ +│ │ │ ├── settings.py +│ │ │ └── env_persistence.py +│ │ └── db/ +│ │ ├── session.py +│ │ └── sequence.py +│ │ +│ ├── models/ # 按域拆分(Wave 1 启用,与 models.py 互斥) +│ │ ├── __init__.py +│ │ ├── base.py +│ │ ├── user.py +│ │ ├── agent.py +│ │ ├── department.py +│ │ ├── chat.py +│ │ ├── content.py +│ │ ├── kb.py +│ │ ├── schedule.py +│ │ ├── shipping.py +│ │ ├── wecom.py +│ │ ├── settings.py +│ │ └── job.py # 方案 D 通用 Job 表 +│ │ +│ ├── schemas/ # 请求/响应 DTO(dataclass 或 Pydantic) +│ │ ├── chat.py +│ │ ├── admin/ +│ │ ├── user/ +│ │ └── kb.py +│ │ +│ ├── api/ # HTTP 层:薄 Blueprint +│ │ ├── __init__.py # register_blueprints(app) +│ │ ├── chat/ +│ │ │ ├── __init__.py +│ │ │ ├── completions.py # POST /completions(SSE) +│ │ │ ├── sessions.py +│ │ │ ├── logs.py +│ │ │ └── preview.py +│ │ ├── user/ +│ │ │ ├── auth.py +│ │ │ ├── profile.py +│ │ │ ├── homepage.py +│ │ │ ├── faq.py +│ │ │ └── wecom.py +│ │ ├── admin/ +│ │ │ ├── users.py +│ │ │ ├── agents.py +│ │ │ ├── departments.py +│ │ │ ├── permissions.py +│ │ │ ├── settings.py +│ │ │ ├── dashboard.py +│ │ │ ├── wecom.py +│ │ │ ├── announcements.py +│ │ │ ├── feedback.py +│ │ │ └── guides.py +│ │ ├── schedule/ # 原 schedule_admin +│ │ │ ├── tasks.py +│ │ │ └── runs.py +│ │ ├── kb/ +│ │ │ ├── groups.py +│ │ │ ├── documents.py +│ │ │ ├── upload.py +│ │ │ └── jobs.py +│ │ ├── agents/ +│ │ ├── integration/ +│ │ ├── workspace/ +│ │ │ ├── schedule.py +│ │ │ ├── shipping_notice.py +│ │ │ └── file_check.py +│ │ ├── tools/ # Dify HTTP Tool API +│ │ │ ├── shipping_notice.py +│ │ │ └── file_check.py +│ │ ├── internal/ +│ │ │ └── jobs.py +│ │ └── speech/ +│ │ +│ ├── services/ # 业务逻辑层(禁止 flask.request) +│ │ ├── chat/ +│ │ │ ├── router.py # Chat Intent Router +│ │ │ ├── session_service.py +│ │ │ ├── log_service.py +│ │ │ ├── preview_service.py +│ │ │ └── perf.py +│ │ ├── user/ +│ │ ├── admin/ +│ │ ├── auth/ +│ │ ├── kb/ # 收敛 knowledge_cleaning/ +│ │ ├── schedule/ # 保留现有子包 +│ │ ├── shipping_notice/ # 保留现有子包 +│ │ ├── file_check_tools/ # 保留现有子包 +│ │ ├── integrations/ +│ │ │ ├── dify.py +│ │ │ ├── minio.py +│ │ │ ├── text2sql.py +│ │ │ ├── oa/ +│ │ │ ├── plm/ +│ │ │ └── wecom/ +│ │ ├── faq/ +│ │ └── speech/ +│ │ +│ ├── jobs/ # 方案 D:统一后台任务层 +│ │ ├── types.py +│ │ ├── registry.py +│ │ ├── queue.py +│ │ ├── store.py +│ │ ├── runner.py +│ │ ├── context.py +│ │ └── handlers/ +│ │ ├── kb_clean.py +│ │ ├── kb_dify_sync.py +│ │ ├── schedule_run.py +│ │ ├── file_check_run.py +│ │ └── wecom_directory_sync.py +│ │ +│ ├── cli/ +│ └── path_utils.py +│ +├── edkb_system/ # 文档清洗管线(独立子系统) +├── migrations/ +├── tests/ +│ ├── api/ +│ ├── services/ +│ └── jobs/ +└── scripts/ +``` + +### 2.1 与现有目录的映射关系 + +| 现有路径 | 目标路径 | 说明 | +| --- | --- | --- | +| `app/__init__.py`(db 定义) | `app/extensions.py` | Wave 1 抽离 `db`、`migrate` | +| `app/errors.py` | `core/errors.py` | 旧路径 re-export 过渡 | +| `app/response_utils.py` | `core/response.py` | 同上 | +| `app/auth_jwt.py` | `core/auth/jwt.py` | 同上 | +| `app/decorators.py` | `core/decorators.py` | 同上 | +| `app/config.py` | `core/config/settings.py` | 同上 | +| `app/env_persistence.py` | `core/config/env_persistence.py` | 同上 | +| `app/models.py` | `models/*.py` | **互斥**,须先删单体再建包 | +| `app/api/user.py` | `api/user/*` + `services/user/*` | Wave 3 | +| `app/api/chat.py` | `api/chat/*` + `services/chat/router.py` | Wave 3 | +| `app/api/admin.py` | `api/admin/*` + `services/admin/*` | Wave 3 | +| `app/api/knowledge_base.py` | `api/kb/*` + `services/kb/*` | Wave 3 | +| `app/api/schedule_admin.py` | `api/schedule/*` | Wave 1 | +| `app/api/workspace_*.py` | `api/workspace/*` | Wave 0 骨架已建 | +| `app/api/shipping_notice_tools.py` | `api/tools/shipping_notice.py` | Wave 0 骨架已建 | +| `app/api/file_check_tools.py` | `api/tools/file_check.py` | Wave 0 骨架已建 | +| `app/api/internal_jobs.py` | `api/internal/jobs.py` | Wave 0 骨架已建 | +| `app/services/dify.py` 等根目录集成 | `services/integrations/*` | Wave 4 | +| `services/knowledge_cleaning/` | `services/kb/` | alias 过渡 | +| `services/user_admin.py` | `services/user/admin_service.py` | Wave 3 | +| `worker_kb.py` | `worker.py` + `jobs/handlers/kb_clean.py` | Wave 2 | +| scheduler in-process thread | `jobs/handlers/schedule_run.py` | Wave 4 | + +### 2.2 迁移互斥约束(重要) + +Python 3 中以下 **不能并存**,否则包会覆盖模块、导致生产 import 静默错误: + +| 冲突 | 处理方式 | +| --- | --- | +| `app/models.py` 与 `app/models/` | Wave 1:拆完再删 `models.py` | +| `app/api/chat.py` 与 `app/api/chat/` | 先 `chat.py` → `chat/_legacy.py`,再建分包 | +| 同理 `user.py`、`admin.py`、`knowledge_base.py` 等 | 标准步骤见 §8.2 | + +**Wave 0 已建、无冲突的分包:** `api/schedule/`、`api/workspace/`、`api/tools/`、`api/internal/`、`core/`、`jobs/`、`schemas/`、`services/{chat,user,admin,...}/`。 + +**Wave 3 前未建的分包:** `api/chat/`、`api/user/`、`api/admin/`、`api/kb/` 等(与现有 `.py` 同名)。 + +--- + +## 3. 分层职责 + +各层职责边界如下,**上层可依赖下层,下层不得反向依赖上层**。 + +```mermaid +flowchart TB + subgraph API["api/(HTTP 层)"] + A1["鉴权、参数解析、调用 service、返回 JSON/SSE"] + end + + subgraph Services["services/(业务层)"] + S1["领域编排、事务边界、组合 integrations"] + end + + subgraph Integrations["services/integrations/(适配层)"] + I1["Dify、OA、PLM、WeCom、MinIO 纯客户端"] + end + + subgraph Jobs["jobs/(任务层)"] + J1["enqueue / handler,worker 与 web 共用 services"] + end + + subgraph Models["models/(数据层)"] + M1["SQLAlchemy 模型"] + end + + subgraph Core["core/(横切)"] + C1["errors、auth、config、response"] + end + + API --> Services + API --> Core + Services --> Integrations + Services --> Models + Services --> Jobs + Jobs --> Services + Jobs --> Models + Jobs --> Core +``` + +### 3.1 api/(HTTP 层) + +- **职责**:Blueprint 路由、鉴权、`request` 解析、调用 service、返回响应 +- **约束**:单个路由函数目标 **< 80 行**;不写复杂业务、不直接编排外部集成 +- **允许**:`request`、`g`、`current_app.config` +- **禁止**:subprocess、大段 SQL、Dify/OA 直连(应经 service) + +### 3.2 services/(业务层) + +- **职责**:领域业务编排、事务边界、组合 integrations 与 models +- **约束**:**禁止** `import flask.request`;config 通过构造函数或参数注入 +- **示例**:`chat/router.py` 按意图选择 PLM / HR / Text2SQL / Dify 流式 generator + +### 3.3 services/integrations/(适配层) + +- **职责**:外部系统 HTTP/SDK 调用、SSE generator 产出 +- **约束**:不做领域模型编排;不依赖 api 层 +- **示例**:`integrations/dify.py` 只负责 Dify API,不含 ChatSession 逻辑 + +### 3.4 jobs/(任务层) + +- **职责**:异步任务 enqueue、claim、handler 分发、重试与状态 +- **约束**:handler 通过 `JobContext` 访问 config/db,禁止读 HTTP request +- **示例**:KB 清洗、排程执行、file-check 异步检核 + +### 3.5 core/(横切层) + +- **职责**:`AppError`、`error_payload`、JWT、装饰器、env 持久化、DB 工具 +- **约束**:无业务域语义 + +--- + +## 4. 各业务域说明 + +### 4.1 chat(对话) + +| 项 | 说明 | +| --- | --- | +| URL 前缀 | `/api/chat` | +| 目标 API | `completions.py`(SSE)、`sessions.py`、`logs.py`、`preview.py` | +| 核心 Service | `services/chat/router.py` — Chat Intent Router | +| 路由策略 | PLM → `integrations/plm`;HR 假期 → `integrations/oa`;ERP → `text2sql`;默认 → `integrations/dify` | +| 设计参考 | `docs/tec.md` §4.1 Chat Intent Router | +| 迁移来源 | `api/chat.py`(~1882 行,含预览/subprocess/openpyxl) | + +### 4.2 user(当前用户 / 认证) + +| 项 | 说明 | +| --- | --- | +| URL 前缀 | `/api/user` | +| 目标 API | `auth.py`(Casdoor OIDC)、`profile.py`、`homepage.py`、`faq.py`、`wecom.py` | +| 核心 Service | `services/auth/casdoor_service.py`、`services/user/*` | +| 迁移来源 | `api/user.py`(~2223 行:登录、企微 OAuth、首页、FAQ) | + +### 4.3 admin(管理后台) + +| 项 | 说明 | +| --- | --- | +| URL 前缀 | `/api/admin` | +| 目标 API | `users/`、`agents/`、`departments/`、`settings/`、`dashboard/`、`wecom/` 等 | +| 核心 Service | `services/admin/*` | +| 注意 | `schedule_admin_bp` 与 `admin_bp` 共用 `/api/admin`,路由命名勿冲突 | +| 迁移来源 | `api/admin.py`(~1455 行,54 个路由) | + +### 4.4 kb(知识库) + +| 项 | 说明 | +| --- | --- | +| URL 前缀 | `/api/kb` | +| 目标 API | `groups.py`、`documents.py`、`upload.py`、`jobs.py` | +| 核心 Service | `services/kb/*`(收敛 `knowledge_cleaning/`) | +| 异步 | 上传 → `jobs.enqueue(KB_CLEAN)` → worker → `edkb_system` → Dify sync | +| 迁移来源 | `api/knowledge_base.py`(~1063 行) | + +### 4.5 schedule(排程管理) + +| 项 | 说明 | +| --- | --- | +| URL 前缀 | `/api/admin`(与 admin 同前缀) | +| 目标 API | `api/schedule/tasks.py`、`runs.py` | +| 核心 Service | `services/schedule/*`(保留现有) | +| Wave 4 | cron 触发改为 `enqueue(SCHEDULE_RUN)`,迁出 web 进程内 thread | + +### 4.6 workspace / tools(工作台与 Tool API) + +| 项 | 说明 | +| --- | --- | +| workspace | `/api/workspace` — 排程记录、出货通知、文件检核工作台 | +| tools | `/api/shipping-notice`、`/api/file-check` — Dify HTTP Tool,已有 OpenAPI export | +| 保留 | `shipping_notice/`、`file_check_tools/` 子包继续作为拆分模板 | + +### 4.7 integrations(外部集成) + +| 子目录 | 现有模块 | 用途 | +| --- | --- | --- | +| `integrations/dify.py` | `services/dify.py` | Dify SSE、上传、workflow | +| `integrations/oa/` | `oa_sqlserver.py`、`oa_leave_workflow.py` | OA SQL Server、SOAP 请假 | +| `integrations/plm/` | `plm_oracle.py` | PLM Oracle 查询 | +| `integrations/wecom/` | `wecom_notify.py`、`wecom_directory_sync.py` | 企微通知、通讯录 | +| `integrations/minio.py` | `minio_service.py` | 对象存储 | +| `integrations/text2sql.py` | `text2sql.py` | ERP 知识库 SQL | + +--- + +## 5. 统一后台任务层(方案 D) + +### 5.1 背景 + +Web 进程内存在多种后台执行方式(scheduler thread、API 内 `threading`、`worker_kb.py`),缺少统一的重试、监控与扩缩容模型。 + +**目标数据流:** + +```text +Flask API → jobs.queue.enqueue(type, payload) → 立即返回 job_id +Worker → jobs.runner.poll → registry → handler → services/* +``` + +### 5.2 模块职责 + +| 模块 | 职责 | +| --- | --- | +| `jobs/types.py` | `JobType`、`JobStatus` 枚举 | +| `jobs/registry.py` | `job_type → handler` 注册 | +| `jobs/store.py` | Job 表 CRUD、`claim_next`(`FOR UPDATE SKIP LOCKED`) | +| `jobs/queue.py` | 对外 `enqueue()`、`enqueue_delayed()` | +| `jobs/runner.py` | worker 主循环 | +| `jobs/context.py` | `JobContext(config, logger)` 注入 | +| `jobs/handlers/*.py` | 各类型任务执行体 | + +### 5.3 JobType 规划 + +| JobType | 来源 | Handler | Wave | +| --- | --- | --- | --- | +| `KB_CLEAN` | KB 上传/重洗 | `handlers/kb_clean.py` | 2 | +| `KB_DIFY_SYNC` | 清洗完成 | `handlers/kb_dify_sync.py` | 2 | +| `SCHEDULE_RUN` | cron | `handlers/schedule_run.py` | 4 | +| `FILE_CHECK_RUN` | Tool API 异步检核 | `handlers/file_check_run.py` | 4 | +| `WECOM_DIRECTORY_SYNC` | 管理端/定时 | `handlers/wecom_directory_sync.py` | 4 | + +### 5.4 与 KbJob 的过渡 + +Wave 2 采用 **Adapter 双轨**:`enqueue` 写通用 `Job` 表,同时 adapter 写 `KbJob`,兼容现有 KB 状态查询 API;Wave 4 再统一读 Job 表。 + +### 5.5 Worker 部署 + +| 入口 | 用途 | +| --- | --- | +| `backend/worker.py` | 统一入口,`--queues kb,schedule` | +| `backend/worker_kb.py` | 兼容旧 Compose/Supervisor 配置 | +| `backend/workers/worker_scheduler.py` | 仅 schedule queue(Wave 4) | + +--- + +## 6. URL 注册(保持不变) + +对外 URL **不变**,前端零改动: + +| Blueprint | url_prefix | 目标模块 | +| --- | --- | --- | +| chat_bp | `/api/chat` | `api/chat/` | +| admin_bp | `/api/admin` | `api/admin/` | +| schedule_admin_bp | `/api/admin` | `api/schedule/` | +| user_bp | `/api/user` | `api/user/` | +| knowledge_base_bp | `/api/kb` | `api/kb/` | +| agents_bp | `/api/agents` | `api/agents/` | +| integration_bp | `/api/integration` | `api/integration/` | +| workspace_* | `/api/workspace` | `api/workspace/` | +| shipping_notice_bp | `/api/shipping-notice` | `api/tools/shipping_notice.py` | +| file_check_bp | `/api/file-check` | `api/tools/file_check.py` | +| internal_jobs_bp | `/api/internal/jobs` | `api/internal/jobs.py` | +| speech_bp | `/api/speech` | `api/speech/` | + +`app/api/__init__.py` 提供 `register_blueprints(app)` 集中注册(Wave 1 接入 `create_app`)。 + +--- + +## 7. 编码约定 + +### 7.1 错误处理 + +- 业务层 **必须** `raise AppError` 子类(`ValidationError`、`NotFoundError` 等) +- **禁止** 新增 `return jsonify({'error': ...}), 4xx` +- 全局 handler(`create_app`)统一输出 `error_payload` + +### 7.2 Import 方向 + +```text +api → services → integrations + → models + → jobs.queue(仅 enqueue) +jobs/handlers → services +core ← 所有层 +``` + +### 7.3 注释 + +遵循 `AGENTS.md` §5 与 `.cursor/rules/code-comments.mdc`:文件层 + 函数层注释;修改逻辑须同步更新注释。 + +### 7.4 测试目录 + +```text +tests/api// +tests/services// +tests/jobs/handlers/ +``` + +与 `docs/test_plan_matrix.md` 域矩阵对齐。 + +--- + +## 8. 分阶段迁移计划 + +```text +Wave 0 骨架建立 ← 当前(目录 + 占位模块,行为不变) +Wave 1 基础设施 core/ 接线、models 拆分、AppError 统一、register_blueprints +Wave 2 任务层 jobs/ 实现 + worker.py 接 KB 清洗 +Wave 3 拆 god 文件 user → chat → admin → kb +Wave 4 集成收敛 integrations/、scheduler/file-check 迁出 web 进程 +``` + +### 8.1 Wave 1 — 基础设施 + +- `extensions.py` 抽离 `db`、`migrate` +- `core/*` 迁入并保留旧路径 re-export +- `models.py` 拆为 `models/*.py`(**先拆后删**) +- 完成 `migrate_jsonify_errors.py`;修复 `gunicorn_config.py` workers 未赋值 +- `create_app` 改用 `register_blueprints(app)` + +### 8.2 Wave 3 — API 单体迁包标准步骤 + +以 `user.py` 为例: + +```text +1. app/api/user.py → app/api/user/_legacy.py +2. app/api/user/__init__.py re-export user_bp 及测试依赖符号 +3. 新建 auth.py、profile.py … 从 _legacy 逐步剪切 +4. _legacy 归零后删除 +``` + +测试 `monkeypatch('app.api.user._get_current_user')` 须保持可用:在 `__init__.py` 显式 re-export。 + +### 8.3 完成定义 + +- [ ] 无 >800 行业务源文件(`edkb_system/` 除外) +- [ ] API 统一 `AppError` +- [ ] `services/` 无 `flask.request` +- [ ] 后台任务统一经 `jobs/` +- [ ] web 进程无 scheduler thread + +--- + +## 9. 值得保留的模式 + +| 模式 | 说明 | +| --- | --- | +| `AppError` 体系 | 扩展即可,勿另造轮子 | +| `env_persistence.py` | DB 持久化配置 + env 镜像 | +| 领域 service 子包 | `shipping_notice/`、`file_check_tools/` 为拆分模板 | +| Chat 意图路由概念 | `supports()` + `stream_chat()` 插件式扩展 | +| KB worker 分离 | `worker_kb.py` + `KbJob` 方向正确 | +| SQLAlchemy 2.0 `Mapped[]` | 迁移时直接沿用 | +| Tool API OpenAPI | `export_*_openapi.py` 脚本 | +| Schema drift 工具 | `check_schema_drift.py` 等运维脚本 | + +--- + +## 10. Wave 0 骨架落地(已实现) + +Wave 0 目标:**建立目录与占位模块,不改变运行时行为**(`create_app` 仍从原单体 import Blueprint)。 + +### 10.1 已建目录 + +```text +app/extensions.py +app/core/{errors,response,decorators,auth,config,db}/ +app/jobs/{types,registry,queue,store,runner,context,handlers}/ +app/schemas/{chat,kb,admin,user}/ +app/services/{chat,user,admin,auth,kb,integrations,faq,speech}/ +app/api/{__init__,schedule,workspace,tools,internal}/ +backend/worker.py +backend/workers/ +tests/jobs/ +``` + +### 10.2 占位策略 + +- `core/*`、`services/integrations/*` 等多为 **re-export** 旧模块 +- `jobs/queue.py`、`jobs/store.py` 为 `NotImplementedError`(Wave 2 实现) +- `services/chat/router.py` 为占位(Wave 3 从 `api/chat.py` 迁入) +- **未创建** `app/models/`、`app/api/chat/` 等(与现有文件互斥) + +### 10.3 下一步(Wave 1) + +1. `create_app` → `register_blueprints(app)` +2. `extensions.py` 接线 `db` / `migrate` +3. 启动 `models/` 拆分 + +--- + +## 11. 相关文档 + +- [项目上下文与技术栈](../project_context.md) +- [技术架构(Chat Router、KB 异步)](../tec.md) +- [测试计划矩阵](../test_plan_matrix.md) +- [前端重构架构方案](./frontend_architecture_refactor.md) +- [AGENTS.md](../../AGENTS.md) diff --git a/frontend/src/features/admin/api/admin.api.ts b/frontend/src/features/admin/api/admin.api.ts index 03870870..bea744e9 100644 --- a/frontend/src/features/admin/api/admin.api.ts +++ b/frontend/src/features/admin/api/admin.api.ts @@ -4,13 +4,56 @@ */ import { getAuthHeaders } from '@/shared/utils/auth'; import { requestJson } from '@/shared/api/client'; +import type { AdminUserRow } from '../types/admin.types'; import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.types'; +import type { PaginatedResult } from '@/shared/types/pagination.types'; const auth = () => ({ headers: getAuthHeaders() }); const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } }); // Users -export const listAdminUsers = () => requestJson('/api/admin/users', auth()); +export const listAdminUsers = () => requestJson('/api/admin/users', auth()); + +export interface ListAdminUsersPageParams { + page?: number; + pageSize?: number; + username?: string; + email?: string; + department?: string; + role?: string; + status?: string; + real_name?: string; + employee_id?: string; + phone_number?: string; + hideRejected?: boolean; +} + +/** + * 分页拉取用户列表(服务端筛选 + 分页,供用户管理页使用)。 + * @param params - 页码、每页条数与各字段模糊筛选 + */ +export const listAdminUsersPage = (params: ListAdminUsersPageParams) => { + const qs = new URLSearchParams(); + qs.set('page', String(params.page ?? 1)); + qs.set('page_size', String(params.pageSize ?? 20)); + const textFilters: Array<{ paramKey: keyof ListAdminUsersPageParams; queryKey: string }> = [ + { paramKey: 'username', queryKey: 'username' }, + { paramKey: 'email', queryKey: 'email' }, + { paramKey: 'department', queryKey: 'department' }, + { paramKey: 'role', queryKey: 'role' }, + { paramKey: 'status', queryKey: 'status' }, + { paramKey: 'real_name', queryKey: 'real_name' }, + { paramKey: 'employee_id', queryKey: 'employee_id' }, + { paramKey: 'phone_number', queryKey: 'phone_number' }, + ]; + for (const { paramKey, queryKey } of textFilters) { + const raw = params[paramKey]; + const value = typeof raw === 'string' ? raw.trim() : ''; + if (value) qs.set(queryKey, value); + } + if (params.hideRejected) qs.set('hide_rejected', 'true'); + return requestJson>(`/api/admin/users?${qs.toString()}`, auth()); +}; export const createAdminUser = (payload: Record) => requestJson('/api/admin/users', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) }); export const updateAdminUser = (id: number, payload: Record) => diff --git a/frontend/src/features/admin/modules/users/UsersPage.vue b/frontend/src/features/admin/modules/users/UsersPage.vue index 77128436..f95044b7 100644 --- a/frontend/src/features/admin/modules/users/UsersPage.vue +++ b/frontend/src/features/admin/modules/users/UsersPage.vue @@ -1,12 +1,15 @@ /** * features/admin/modules/users/UsersPage.vue - * 用户管理独立页面。路由:/admin/users + * 用途:用户管理独立页面(服务端筛选分页、批量操作)。 + * 依赖:useUsersAdmin、PaginationBar、用户相关 Modal。 + * 逻辑:路由 /admin/users;列表经 listAdminUsersPage 按页拉取。 */