diff --git a/backend/app/api/__init__.py b/backend/app/api/__init__.py index 5b902989..afcd5f91 100644 --- a/backend/app/api/__init__.py +++ b/backend/app/api/__init__.py @@ -31,6 +31,7 @@ def register_blueprints(app: Flask) -> None: from app.api.kb import knowledge_base_bp from app.api.schedule import schedule_admin_bp from app.api.workspace import ( + workspace_announcements_bp, workspace_file_check_bp, workspace_schedule_bp, workspace_shipping_notice_bp, @@ -46,6 +47,7 @@ def register_blueprints(app: Flask) -> None: 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_announcements_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') diff --git a/backend/app/api/admin.py b/backend/app/api/admin.py deleted file mode 100644 index 0299f19a..00000000 --- a/backend/app/api/admin.py +++ /dev/null @@ -1,1866 +0,0 @@ -""" -backend/app/api/admin.py - -用途:管理员相关 API 路由(Agent、用户、权限、企业微信等)。 -依赖:flask、models、decorators、app.api.user(Casdoor 用户同步)。 -逻辑:供前端 Admin 控制台调用;创建/编辑用户时委托 user._sync_casdoor_* 与 IdP 保持同步。 -""" -from flask import Blueprint, request, jsonify, current_app -from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, GeneralFeedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig, LoginAudit, WecomNotifyAudit, AgentGuide, KbDocument -from app.services.minio_service import minio_service -from app.core.decorators import require_admin -from app.core.config.settings import Config -from app import db -from app.core.config.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 -import math -import re -import requests -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.core.auth.jwt import get_current_user as _get_auth_user -from app.core.errors import ( - AppError, - ConflictError, - ForbiddenError, - NotFoundError, - ServiceUnavailableError, - UnauthorizedError, - ValidationError, - raise_for_status, -) -admin_bp = Blueprint('admin', __name__) - -def _raise_user_integrity_conflict(exc: IntegrityError) -> None: - message = str(getattr(exc, 'orig', exc)) - if 'users_email_key' in message: - raise ConflictError('Email already exists', code='USER.EMAIL_EXISTS') - if 'users_employee_id_key' in message: - raise ConflictError('Employee ID already exists', code='USER.EMPLOYEE_ID_EXISTS') - if 'users_phone_number_key' in message: - raise ConflictError('Phone number already exists', code='USER.PHONE_EXISTS') - if 'users_username_key' in message or 'ix_users_username' in message: - raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS') - raise ConflictError('Data uniqueness conflict', code='USER.UNIQUENESS_CONFLICT') - -def _assert_user_unique_fields(exclude_user_id: int | None, **fields: str | None) -> None: - """ - 校验用户唯一字段(邮箱、工号、手机号)不与其它账号冲突。 - 核心逻辑:对传入的非 None 字段查询 User 表;编辑时 exclude_user_id 排除当前用户。 - @param exclude_user_id: 编辑场景传当前用户 id;创建场景传 None - @param fields: email / employee_id / phone_number 等待校验值 - @raises ConflictError: 唯一字段已被占用 - """ - checks = ( - ('email', 'USER.EMAIL_EXISTS', 'Email already exists'), - ('employee_id', 'USER.EMPLOYEE_ID_EXISTS', 'Employee ID already exists'), - ('phone_number', 'USER.PHONE_EXISTS', 'Phone number already exists'), - ) - for field, code, message in checks: - value = fields.get(field) - if value is None: - continue - query = db.session.query(User.id).filter(getattr(User, field) == value) - if exclude_user_id is not None: - query = query.filter(User.id != exclude_user_id) - if query.first(): - raise ConflictError(message, code=code, details={'field': field}) - -def _empty_to_none(value): - if value is None: - return None - if isinstance(value, str) and value.strip() == '': - return None - return value - -def _is_valid_email(email: str) -> bool: - if not isinstance(email, str): - return False - email = email.strip() - if len(email) > 254: - return False - pattern = '^[A-Za-z0-9._%+\\-]+@[A-Za-z0-9.\\-]+\\.[A-Za-z]{2,}$' - return re.match(pattern, email) is not None - -def _serialize_wecom_notify_settings(): - return {'enabled': bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)), 'base_url': current_app.config.get('WECOM_NOTIFY_BASE_URL') or '', 'events': [x for x in str(current_app.config.get('WECOM_NOTIFY_EVENTS', '')).split(',') if x]} - -def _serialize_wecom_system_settings(): - return {'enabled': bool(current_app.config.get('WECOM_ENABLED', False)), 'corp_id': current_app.config.get('WECOM_CORP_ID') or '', 'agent_id': str(current_app.config.get('WECOM_AGENT_ID') or ''), 'secret': current_app.config.get('WECOM_SECRET') or '', 'redirect_uri': current_app.config.get('WECOM_REDIRECT_URI') or '', 'auto_create_user': bool(current_app.config.get('WECOM_AUTO_CREATE_USER', True)), 'match_rules': current_app.config.get('WECOM_MATCH_RULES') or 'employee_id,mobile', 'match_operator': str(current_app.config.get('WECOM_MATCH_OPERATOR') or 'AND').upper(), 'first_login_bind_mode': str(current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE') or 'match_rules').lower(), 'first_login_input_fields': current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS') or 'employee_id,mobile,email', 'employee_id_source': current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE') or 'userid', 'mobile_normalize': bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True)), 'callback_token': current_app.config.get('WECOM_CALLBACK_TOKEN') or '', 'encoding_aes_key': current_app.config.get('WECOM_ENCODING_AES_KEY') or '', 'callback_url': current_app.config.get('WECOM_CALLBACK_URL') or '', 'homepage_url': current_app.config.get('WECOM_HOMEPAGE_URL') or '', 'trusted_domain': current_app.config.get('WECOM_TRUSTED_DOMAIN') or '', 'public_base_url': current_app.config.get('WECOM_PUBLIC_BASE_URL') or ''} - -def _default_public_base(): - for key in ('WECOM_PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'): - configured = current_app.config.get(key) or '' - if configured: - return configured.rstrip('/') - return request.host_url.rstrip('/') - -def _serialize_wecom_integration_manifest(): - settings = _serialize_wecom_system_settings() - public_base = _default_public_base() - callback_url = settings.get('callback_url') or f'{public_base}/api/user/wecom/callback' - homepage_url = settings.get('homepage_url') or f'{public_base}/workspace' - trusted_domain = settings.get('trusted_domain') or request.host.split(':')[0] - return {'public_base_url': public_base, 'callback_url': callback_url, 'callback_token': settings.get('callback_token') or '', 'encoding_aes_key': settings.get('encoding_aes_key') or '', 'oauth_redirect_uri': settings.get('redirect_uri') or homepage_url, 'homepage_url': homepage_url, 'trusted_domain': trusted_domain, 'authorize_api': f'{public_base}/api/user/wecom/authorize-url', 'login_api': f'{public_base}/api/user/wecom/login'} - -def _serialize_debug_match_user(user: User) -> dict: - return {'id': user.id, 'username': user.username, 'real_name': user.real_name, 'employee_id': user.employee_id, 'phone_number': user.phone_number, 'email': user.email, 'status': user.status, 'wecom_userid': user.wecom_userid, 'wecom_unionid': user.wecom_unionid} - -def _build_wecom_match_preview(identity: dict, rules: list[str], operator: str) -> dict: - from app.api import user as user_api - bind_mode = user_api._get_wecom_first_login_bind_mode() - preview = {'bind_mode': bind_mode, 'rules': {'fields': rules, 'operator': operator}, 'auto_create_user': bool(current_app.config.get('WECOM_AUTO_CREATE_USER', True))} - bound_user = None - if identity.get('wecom_userid'): - bound_user = db.session.query(User).filter_by(wecom_userid=identity['wecom_userid']).first() - if not bound_user and identity.get('wecom_unionid'): - bound_user = db.session.query(User).filter_by(wecom_unionid=identity['wecom_unionid']).first() - if bound_user: - preview['decision'] = 'already_bound' - preview['bound_user'] = _serialize_debug_match_user(bound_user) - return preview - if bind_mode == 'input_verify': - preview['decision'] = 'input_verification_required' - preview['allowed_fields'] = user_api._get_wecom_first_login_input_fields() - return preview - matched_users, missing_fields = user_api._find_users_by_match_rules(identity, rules, operator) - preview['missing_fields'] = missing_fields - preview['matched_users'] = [_serialize_debug_match_user(user) for user in matched_users] - if missing_fields: - preview['decision'] = 'missing_match_fields' - elif len(matched_users) == 1: - preview['decision'] = 'matched_existing_user' - elif len(matched_users) > 1: - preview['decision'] = 'ambiguous_match' - elif preview['auto_create_user']: - preview['decision'] = 'would_auto_create_user' - else: - preview['decision'] = 'bind_required' - return preview - -@admin_bp.route('/wecom/debug-user-by-code', methods=['POST']) -@require_admin -def debug_wecom_user_by_code(): - from app.api import user as user_api - if not user_api._is_wecom_configured(): - raise ValidationError('WeCom login is not configured') - data = request.get_json() or {} - code = str(data.get('code') or '').strip() - if not code: - raise ValidationError('code is required') - access_token = user_api._get_wecom_access_token() - info_resp = requests.get('https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo', params={'access_token': access_token, 'code': code}, timeout=8) - auth_info = info_resp.json() - userid = auth_info.get('userid') or auth_info.get('UserId') - openid = auth_info.get('openid') or auth_info.get('OpenId') - payload = {'auth_info': auth_info} - if auth_info.get('errcode') != 0: - raise AppError( - code='WECOM_AUTH_FAILED', - message=f"WeCom auth failed: {auth_info.get('errmsg', 'unknown error')}", - http_status=401, - details={'auth_info': auth_info}, - ) - if not userid: - raise AppError( - code='WECOM_NOT_IN_AGENT_SCOPE', - message='当前 code 对应的账号不在应用可见范围内,或不是本企业成员。', - http_status=401, - details={'auth_info': auth_info, 'openid': openid}, - ) - user_resp = requests.get('https://qyapi.weixin.qq.com/cgi-bin/user/get', params={'access_token': access_token, 'userid': userid}, timeout=8) - wecom_user = user_resp.json() - payload['wecom_user'] = wecom_user - if wecom_user.get('errcode') != 0: - raise AppError( - code='WECOM_USER_FETCH_FAILED', - message=f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}", - http_status=401, - details={'auth_info': auth_info, 'wecom_user': wecom_user}, - ) - identity = user_api._extract_wecom_identity(wecom_user) - rules, operator = user_api._get_wecom_match_config() - payload['normalized_identity'] = identity - payload['match_preview'] = _build_wecom_match_preview(identity, rules, operator) - return jsonify(payload) - -def _compute_dashboard_summary(): - """ - 聚合仪表盘四张卡片所需的统计值(仅 COUNT/AVG,不返回列表)。 - - 返回字段: - - agent_count: 启用中的 Agent 数量 - - user_count: 用户总数 - - total_conversations: 对话日志总数 - - avg_score: 反馈平均分(保留 1 位小数) - """ - total_users = db.session.query(func.count(User.id)).scalar() or 0 - active_agents = db.session.query(func.count(Agent.id)).filter_by(is_active=True).scalar() or 0 - total_conversations = db.session.query(func.count(ChatLog.id)).scalar() or 0 - avg_score = db.session.query(func.avg(Feedback.score)).scalar() - avg_score = round(float(avg_score), 1) if avg_score else 0.0 - return { - 'agent_count': active_agents, - 'user_count': total_users, - 'total_conversations': total_conversations, - 'avg_score': avg_score, - } - -def _compute_dashboard_badges(): - """ - 聚合侧栏角标所需的待办数量(仅 COUNT,不拉 users / permission_requests 全表)。 - - 返回字段: - - pending_approvals: status=pending 的注册用户数量(「用户审批」角标) - - pending_requests: status=pending 的权限申请数量(「权限申请」角标) - """ - pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar() or 0 - pending_requests = db.session.query(func.count(PermissionRequest.id)).filter_by(status='pending').scalar() or 0 - return { - 'pending_approvals': pending_approvals, - 'pending_requests': pending_requests, - } - -@admin_bp.route('/dashboard/summary', methods=['GET']) -@require_admin -def dashboard_summary(): - """ - 管理后台仪表盘概览(供 Dashboard 页单次请求)。 - - GET /api/admin/dashboard/summary - 响应示例:{"agent_count": 5, "user_count": 120, "total_conversations": 3000, "avg_score": 4.2} - """ - return jsonify(_compute_dashboard_summary()) - -@admin_bp.route('/dashboard/badges', methods=['GET']) -@require_admin -def dashboard_badges(): - """ - 管理后台侧栏待办角标(供 AdminLayout 轻量轮询/缓存刷新)。 - - GET /api/admin/dashboard/badges - 响应示例:{"pending_approvals": 2, "pending_requests": 5} - """ - return jsonify(_compute_dashboard_badges()) - -@admin_bp.route('/dashboard', methods=['GET']) -@require_admin -def dashboard_stats(): - """ - 仪表盘统计(遗留接口,字段名与早期前端兼容;新代码请用 /dashboard/summary 与 /dashboard/badges)。 - - GET /api/admin/dashboard - 响应含 summary 四指标 + pending_approvals / pending_requests。 - """ - summary = _compute_dashboard_summary() - badges = _compute_dashboard_badges() - return jsonify({ - 'total_users': summary['user_count'], - 'active_agents': summary['agent_count'], - 'total_conversations': summary['total_conversations'], - 'avg_score': summary['avg_score'], - 'pending_approvals': badges['pending_approvals'], - 'pending_requests': badges['pending_requests'], - }) - -@admin_bp.route('/departments', methods=['GET']) -@require_admin -def list_departments(): - depts = db.session.query(Department).order_by(Department.name.asc()).all() - return jsonify([{'id': d.id, 'name': d.name, 'code': d.code, 'company': d.company, 'description': d.description} for d in depts]) - -@admin_bp.route('/departments', methods=['POST']) -@require_admin -def create_department(): - data = request.get_json() or {} - if not data.get('name'): - raise ValidationError('Name is required') - if db.session.query(Department).filter_by(name=data['name']).first(): - raise ValidationError('Name exists') - if data.get('code') and db.session.query(Department).filter_by(code=data['code']).first(): - raise ValidationError('Code exists') - dept = Department(name=data['name'], code=data.get('code'), company=data.get('company'), description=data.get('description')) - db.session.add(dept) - db.session.commit() - return (jsonify({'id': dept.id, 'name': dept.name}), 201) - -@admin_bp.route('/departments/', methods=['PUT']) -@require_admin -def update_department(id): - dept = db.session.get(Department, id) - if not dept: - raise NotFoundError('Not found') - data = request.get_json() or {} - if 'name' in data: - if db.session.query(Department).filter(Department.name == data['name'], Department.id != id).first(): - raise ValidationError('Name exists') - dept.name = data['name'] - if 'code' in data: - if data['code'] and db.session.query(Department).filter(Department.code == data['code'], Department.id != id).first(): - raise ValidationError('Code exists') - dept.code = data['code'] - if 'company' in data: - dept.company = data['company'] - if 'description' in data: - dept.description = data['description'] - db.session.commit() - return jsonify({'status': 'ok'}) - -@admin_bp.route('/departments/', methods=['DELETE']) -@require_admin -def delete_department(id): - dept = db.session.get(Department, id) - if dept: - db.session.delete(dept) - db.session.commit() - return jsonify({'status': 'ok'}) - -@admin_bp.route('/agents', methods=['GET']) -@require_admin -def list_agents(): - agents = db.session.query(Agent).order_by(Agent.id.asc()).all() - return jsonify([{'id': a.id, 'name': a.name, 'dify_app_id': a.dify_app_id, 'dify_api_key': a.dify_api_key, 'is_active': a.is_active, 'description': a.description, 'type': a.type, 'api_base_url': a.api_base_url, 'extra_config': a.extra_config} for a in agents]) - -@admin_bp.route('/agents', methods=['POST']) -@require_admin -def create_agent(): - data = request.get_json() or {} - if not data.get('name'): - raise ValidationError('Name is required') - agent_type = data.get('type', 'api') - if agent_type == 'api' and (not data.get('dify_app_id')): - raise ValidationError('App ID is required for API agents') - agent = Agent(name=data['name'], dify_app_id=data.get('dify_app_id') or None, dify_api_key=data.get('dify_api_key') or None, description=data.get('description'), type=agent_type, api_base_url=data.get('api_base_url'), extra_config=data.get('extra_config'), is_active=data.get('is_active', True)) - db.session.add(agent) - db.session.commit() - return (jsonify({'id': agent.id}), 201) - -@admin_bp.route('/agents/', methods=['PUT']) -@require_admin -def update_agent(id): - agent = db.session.get(Agent, id) - if not agent: - raise NotFoundError('Not found') - data = request.get_json() or {} - for k in ['name', 'dify_app_id', 'description', 'type', 'api_base_url', 'extra_config', 'is_active']: - if k in data: - setattr(agent, k, data[k]) - if 'dify_api_key' in data and data['dify_api_key']: - agent.dify_api_key = data['dify_api_key'] - db.session.commit() - return jsonify({'status': 'ok'}) - -@admin_bp.route('/agents/', methods=['DELETE']) -@require_admin -def delete_agent(id): - agent = db.session.get(Agent, id) - if agent: - db.session.delete(agent) - db.session.commit() - return jsonify({'status': 'ok'}) - -@admin_bp.route('/agents//test', methods=['POST']) -@require_admin -def test_agent(id): - """ - 测试应用连通性。 - 返回:请求地址、输出信息、结果分析。 - 若测试通过,则自动将应用状态置为启用。 - """ - agent = db.session.get(Agent, id) - if not agent: - raise NotFoundError('Not found') - tested_at = datetime.utcnow().isoformat() - if agent.type == 'iframe': - iframe_url = (agent.extra_config or {}).get('iframe_url') - if not iframe_url: - return (jsonify({'passed': False, 'request_url': '', 'output_info': 'Missing iframe_url in extra_config.', 'analysis': '测试失败:未配置 iframe URL。', 'http_status': 0, 'tested_at': tested_at}), 200) - try: - resp = requests.get(iframe_url, timeout=(5, 15), allow_redirects=True) - passed = 200 <= resp.status_code < 400 - if passed and (not agent.is_active): - agent.is_active = True - db.session.commit() - return (jsonify({'passed': passed, 'request_url': iframe_url, 'output_info': f'HTTP {resp.status_code}; response length={len(resp.text)}', 'analysis': '测试通过:iframe 地址可访问。' if passed else '测试失败:iframe 地址不可访问或返回异常状态。', 'http_status': resp.status_code, 'tested_at': tested_at}), 200) - except requests.RequestException as e: - return (jsonify({'passed': False, 'request_url': iframe_url, 'output_info': str(e), 'analysis': '测试失败:请求 iframe 地址异常。', 'http_status': 0, 'tested_at': tested_at}), 200) - if not agent.dify_api_key: - return (jsonify({'passed': False, 'request_url': '', 'output_info': 'Missing dify_api_key.', 'analysis': '测试失败:未配置 API Key。', 'http_status': 0, 'tested_at': tested_at}), 200) - base_url = (agent.api_base_url or Config.DIFY_API_BASE or '').rstrip('/') - if not base_url: - return (jsonify({'passed': False, 'request_url': '', 'output_info': 'Missing api_base_url.', 'analysis': '测试失败:未配置 API Base URL。', 'http_status': 0, 'tested_at': tested_at}), 200) - extra_config = agent.extra_config or {} - dify_app_type = str(extra_config.get('dify_app_type') or 'chatflow').strip().lower() - if dify_app_type not in ('chatflow', 'workflow'): - dify_app_type = 'chatflow' - if dify_app_type == 'workflow': - request_url = DifyService._build_workflow_url(base_url) - payload = {'inputs': {'query': '系统连通性测试,请简短回复OK。'}, 'response_mode': 'blocking', 'user': 'admin_test'} - else: - request_url = DifyService._build_chat_messages_url(base_url) - payload = {'inputs': {}, 'query': '系统连通性测试,请简短回复OK。', 'response_mode': 'blocking', 'user': 'admin_test'} - headers = {'Authorization': f'Bearer {agent.dify_api_key}', 'Content-Type': 'application/json'} - try: - resp = requests.post(request_url, headers=headers, json=payload, timeout=(5, 25)) - raw_text = (resp.text or '')[:4000] - output_info = raw_text - passed = False - analysis = f'测试失败:HTTP {resp.status_code}。' - if dify_app_type == 'workflow' and 200 <= resp.status_code < 300: - passed = True - analysis = '测试通过:Workflow 接口可访问且认证通过。' - try: - data = resp.json() - if dify_app_type == 'workflow': - workflow_data = data.get('data') if isinstance(data, dict) else None - outputs = workflow_data.get('outputs') if isinstance(workflow_data, dict) else None - status = workflow_data.get('status') if isinstance(workflow_data, dict) else None - message = data.get('message') if isinstance(data, dict) else None - if isinstance(outputs, dict) and outputs: - output_info = str(outputs)[:4000] - elif isinstance(message, str) and message.strip(): - output_info = message[:4000] - elif isinstance(data, dict): - output_info = str(data)[:4000] - if resp.ok and status in ('succeeded', 'success'): - analysis = '测试通过:Workflow 接口可访问且业务返回成功。' - elif resp.ok: - analysis = '测试通过:Workflow 接口可访问且认证通过(本次未返回业务成功状态)。' - else: - answer = data.get('answer') if isinstance(data, dict) else None - if answer: - output_info = str(answer)[:4000] - if resp.ok and isinstance(answer, str) and answer.strip(): - passed = True - analysis = '测试通过:Chatflow 接口可访问且已返回回答。' - elif resp.ok: - analysis = '测试未通过:Chatflow 接口可访问,但未返回有效回答。' - else: - message = data.get('message') if isinstance(data, dict) else None - if message: - output_info = str(message)[:4000] - except ValueError: - if resp.ok and raw_text.strip(): - if dify_app_type == 'workflow': - passed = True - analysis = '测试通过:Workflow 接口可访问并返回了文本内容。' - else: - passed = True - analysis = '测试通过:Chatflow 接口可访问并返回了文本内容。' - if passed and (not agent.is_active): - agent.is_active = True - db.session.commit() - return (jsonify({'passed': passed, 'dify_app_type': dify_app_type, 'request_url': request_url, 'output_info': output_info, 'analysis': analysis, 'http_status': resp.status_code, 'tested_at': tested_at}), 200) - except requests.RequestException as e: - return (jsonify({'passed': False, 'dify_app_type': dify_app_type, 'request_url': request_url, 'output_info': str(e), 'analysis': '测试失败:请求异常(网络、超时或认证问题)。', 'http_status': 0, 'tested_at': tested_at}), 200) - -@admin_bp.route('/agents//permissions', methods=['POST']) -@require_admin -def update_agent_permissions(id): - agent = db.session.get(Agent, id) - if not agent: - raise NotFoundError('Not found') - data = request.get_json() or {} - user_ids = data.get('user_ids', []) - users = db.session.query(User).filter(User.id.in_(user_ids)).all() - current_users = db.session.query(User).filter(User.agents.contains(agent)).all() - current_user_ids = set((u.id for u in current_users)) - new_user_ids = set(user_ids) - to_add = new_user_ids - current_user_ids - if to_add: - users_to_add = db.session.query(User).filter(User.id.in_(to_add)).all() - for u in users_to_add: - u.agents.append(agent) - to_remove = current_user_ids - new_user_ids - if to_remove: - users_to_remove = db.session.query(User).filter(User.id.in_(to_remove)).all() - for u in users_to_remove: - u.agents.remove(agent) - 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(): - """ - 列出管理端用户。无 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 -def create_user(): - """ - 管理端创建用户:本地入库前先同步 Casdoor add-user,与改密一样保持 IdP 一致。 - 核心逻辑:校验 → 构建 User → _sync_casdoor_create_user → commit;Casdoor 失败则 rollback。 - Request JSON: username, password, email, real_name, employee_id, phone_number 等 - Returns: - 201 + { id };Casdoor/唯一约束失败时抛出 AppError/ConflictError - """ - from app.api import user as user_api - data = request.get_json() or {} - required_field_errors = ( - ('username', 'USER.USERNAME_REQUIRED', 'Username is required'), - ('password', 'USER.PASSWORD_REQUIRED', 'Password is required'), - ('email', 'USER.EMAIL_REQUIRED', 'Email is required'), - ('real_name', 'USER.REAL_NAME_REQUIRED', 'Real name is required'), - ('employee_id', 'USER.EMPLOYEE_ID_REQUIRED', 'Employee ID is required'), - ('phone_number', 'USER.PHONE_REQUIRED', 'Phone number is required'), - ) - for field, code, message in required_field_errors: - if _empty_to_none(data.get(field)) is None: - raise AppError(code=code, message=message, http_status=400, details={'field': field}) - if db.session.query(User).filter_by(username=data['username']).first(): - raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS', details={'field': 'username'}) - email = _empty_to_none(data.get('email')) - if not _is_valid_email(email): - raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'}) - _assert_user_unique_fields( - None, - email=email, - employee_id=_empty_to_none(data.get('employee_id')), - phone_number=_empty_to_none(data.get('phone_number')), - ) - user = User(username=data['username'], email=email, department=_empty_to_none(data.get('department')), role=data.get('role', 'user'), status=data.get('status', 'active'), real_name=_empty_to_none(data.get('real_name')), employee_id=_empty_to_none(data.get('employee_id')), phone_number=_empty_to_none(data.get('phone_number'))) - user.set_password(data['password']) - db.session.add(user) - try: - if data.get('agent_ids'): - agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all() - user.agents = agents - user_api._sync_casdoor_create_user( - username=user.username, - password=data['password'], - email=email, - real_name=user.real_name, - phone_number=user.phone_number, - status=user.status, - department=user.department, - ) - db.session.commit() - except IntegrityError as e: - db.session.rollback() - _raise_user_integrity_conflict(e) - except AppError: - db.session.rollback() - raise - except RuntimeError as e: - db.session.rollback() - user_api._raise_casdoor_add_user_error(e) - return (jsonify({'id': user.id}), 201) - -@admin_bp.route('/users/', methods=['PUT']) -@require_admin -def update_user(id): - """ - 管理端编辑用户:资料仅写本地库;仅改密时同步 Casdoor set-password。 - 核心逻辑:唯一字段预校验 → 应用本地字段与 agent_ids →(有 new_password 时)_sync_casdoor_update_user → commit。 - Request JSON: email, department, role, status, password 等;password 为空表示不改密 - Returns: - { status: ok };Casdoor 改密/唯一约束失败时抛出 AppError/ConflictError - """ - from app.api import user as user_api - user = db.session.get(User, id) - if not user: - raise NotFoundError('User not found') - data = request.get_json() or {} - if 'email' in data: - email = _empty_to_none(data.get('email')) - if email is not None and (not _is_valid_email(email)): - raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'}) - unique_updates = { - field: _empty_to_none(data[field]) - for field in ('email', 'employee_id', 'phone_number') - if field in data - } - _assert_user_unique_fields(id, **unique_updates) - new_password = _empty_to_none(data.get('password')) - try: - for k in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']: - if k in data: - if k in ['email', 'department', 'real_name', 'employee_id', 'phone_number']: - setattr(user, k, _empty_to_none(data[k])) - else: - setattr(user, k, data[k]) - if new_password: - user.set_password(new_password) - if 'agent_ids' in data: - agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all() - user.agents = agents - if new_password: - user_api._sync_casdoor_update_user(user, new_password=new_password) - db.session.commit() - except IntegrityError as e: - db.session.rollback() - _raise_user_integrity_conflict(e) - except AppError: - db.session.rollback() - raise - except RuntimeError as e: - db.session.rollback() - user_api._raise_casdoor_set_password_error(e) - return jsonify({'status': 'ok'}) - -@admin_bp.route('/users/cleanup-rejected', methods=['POST']) -@require_admin -def cleanup_rejected_users(): - 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}) - -@admin_bp.route('/users/batch-delete', methods=['POST']) -@require_admin -def batch_delete_users(): - data = request.get_json() or {} - ids = data.get('user_ids', []) - current_user = _get_auth_user() - current_user_id = current_user.id if current_user else None - target_ids = [uid for uid in ids if str(uid) != str(current_user_id)] - if not target_ids: - raise ValidationError('No valid users') - 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(): - """ - Batch update user permissions - """ - data = request.get_json() or {} - user_ids = data.get('user_ids', []) - agent_ids = data.get('agent_ids', []) - action = data.get('action', 'add') - if not user_ids: - raise ValidationError('No users selected') - users = db.session.query(User).filter(User.id.in_(user_ids)).all() - agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all() - if not agents and action != 'set': - if action == 'remove': - return jsonify({'status': 'ok'}) - for user in users: - if action == 'set': - user.agents = agents - elif action == 'add': - for agent in agents: - if agent not in user.agents: - user.agents.append(agent) - elif action == 'remove': - for agent in agents: - if agent in user.agents: - user.agents.remove(agent) - if user.wecom_userid: - action_label = {'add': '新增', 'remove': '移除', 'set': '重置为'}[action] - agent_names = '、'.join([a.name for a in agents]) if agents else '无' - send_wecom_event_message(event_type='permission_batch_updated', user=user, title='应用权限已更新', content=f'管理员已{action_label}你的应用权限:{agent_names}', jump_path='/workspace') - db.session.commit() - return jsonify({'status': 'ok', 'updated_count': len(users)}) - -@admin_bp.route('/users//permissions', methods=['POST']) -@require_admin -def update_user_permissions(id): - user = db.session.get(User, id) - if not user: - raise NotFoundError('Not found') - data = request.get_json() or {} - agent_ids = data.get('agent_ids', []) - agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all() - user.agents = agents - db.session.commit() - return jsonify({'status': 'ok'}) - -@admin_bp.route('/users//approve', methods=['POST']) -@require_admin -def approve_user(id): - user = db.session.get(User, id) - if user: - user.status = 'active' - db.session.commit() - return jsonify({'status': 'ok'}) - -@admin_bp.route('/users//reject', methods=['POST']) -@require_admin -def reject_user(id): - user = db.session.get(User, id) - if user: - user.status = 'rejected' - db.session.commit() - return jsonify({'status': 'ok'}) - -@admin_bp.route('/permission-requests', methods=['GET']) -@require_admin -def list_permission_requests(): - reqs = db.session.query(PermissionRequest).order_by(PermissionRequest.created_at.desc()).all() - return jsonify([{'id': r.id, 'user_id': r.user_id, 'agent_id': r.agent_id, 'reason': r.reason, 'status': r.status, 'created_at': r.created_at.isoformat()} for r in reqs]) - -@admin_bp.route('/permission-requests//approve', methods=['POST']) -@require_admin -def approve_request(id): - req = db.session.get(PermissionRequest, id) - if not req: - raise NotFoundError('Not found') - req.status = 'approved' - req.reviewed_at = datetime.utcnow() - user = db.session.get(User, req.user_id) - agent = db.session.get(Agent, req.agent_id) - if user and agent and (agent not in user.agents): - user.agents.append(agent) - if user and user.wecom_userid: - send_wecom_event_message(event_type='permission_request_approved', user=user, title='权限申请已通过', content=f'你申请的应用权限已通过:{(agent.name if agent else req.agent_id)}', jump_path='/workspace') - db.session.commit() - return jsonify({'status': 'ok'}) - -@admin_bp.route('/permission-requests//reject', methods=['POST']) -@require_admin -def reject_request(id): - req = db.session.get(PermissionRequest, id) - if not req: - raise NotFoundError('Not found') - req.status = 'rejected' - req.reviewed_at = datetime.utcnow() - user = db.session.get(User, req.user_id) - agent = db.session.get(Agent, req.agent_id) - if user and user.wecom_userid: - send_wecom_event_message(event_type='permission_request_rejected', user=user, title='权限申请未通过', content=f'你申请的应用权限未通过:{(agent.name if agent else req.agent_id)}', jump_path='/workspace') - db.session.commit() - return jsonify({'status': 'ok'}) - -@admin_bp.route('/quick-questions', methods=['GET']) -@require_admin -def list_quick_questions(): - """ - 列出全局常用问题(含 FAQ 缓存字段)。 - @query stale_only - 可选,true 时仅返回待复审(stale_at 非空)条目 - @returns JSON 数组,每项含 answer/cache_enabled/hit_count/stale_* 等扩展字段 - """ - stale_only = str(request.args.get('stale_only', '')).lower() in {'1', 'true', 'yes'} - query = ( - db.session.query(QuickQuestion) - .filter(QuickQuestion.user_id.is_(None)) - .order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc()) - ) - if stale_only: - query = query.filter(QuickQuestion.stale_at.isnot(None)) - qqs = query.all() - res = [] - for q in qqs: - agent = db.session.get(Agent, q.agent_id) - stale_doc = db.session.get(KbDocument, q.stale_kb_document_id) if q.stale_kb_document_id else None - res.append(_serialize_admin_quick_question(q, agent.name if agent else 'Unknown', stale_doc)) - return jsonify(res) - - -def _parse_aliases(raw_aliases) -> list[str]: - """ - 解析别名列表,支持 JSON 数组或换行分隔字符串。 - @param raw_aliases - 请求体 aliases 字段 - @returns 去重后的别名字符串列表 - """ - if raw_aliases is None: - return [] - if isinstance(raw_aliases, list): - items = [str(item).strip() for item in raw_aliases if str(item).strip()] - elif isinstance(raw_aliases, str): - items = [line.strip() for line in raw_aliases.splitlines() if line.strip()] - else: - return [] - seen: set[str] = set() - result: list[str] = [] - for item in items: - if item not in seen: - seen.add(item) - result.append(item) - return result - - -def _parse_expires_at(raw_value) -> datetime | None: - """ - 解析 FAQ 过期时间。 - @param raw_value - ISO 字符串或 None - @returns datetime 或 None - """ - if not raw_value: - return None - text = str(raw_value).strip() - if not text: - return None - try: - return datetime.fromisoformat(text.replace('Z', '+00:00')).replace(tzinfo=None) - except ValueError: - raise ValidationError('Invalid expires_at format') - - -def _serialize_admin_quick_question( - q: QuickQuestion, - agent_name: str, - stale_kb_document: KbDocument | None = None, -) -> dict: - """ - 序列化全局常用问题供管理端展示。 - @param q - QuickQuestion 实例 - @param agent_name - 所属应用名称 - @param stale_kb_document - 触发待复审的 KB 文档(可选) - @returns 可 JSON 化的字典 - """ - return { - 'id': q.id, - 'title': q.title, - 'question': q.question, - 'answer': q.answer, - 'aliases': q.aliases if isinstance(q.aliases, list) else [], - 'cache_enabled': bool(q.cache_enabled), - 'is_enabled': bool(q.is_enabled), - 'hit_count': q.hit_count or 0, - 'agent_id': q.agent_id, - 'agent_name': agent_name, - 'sort_order': q.sort_order, - 'expires_at': q.expires_at.isoformat() if q.expires_at else None, - 'updated_at': q.updated_at.isoformat() if getattr(q, 'updated_at', None) else None, - 'source_kb_document_ids': q.source_kb_document_ids if isinstance(q.source_kb_document_ids, list) else [], - 'stale_at': q.stale_at.isoformat() if getattr(q, 'stale_at', None) else None, - 'stale_reason': q.stale_reason, - 'stale_kb_document_id': q.stale_kb_document_id, - 'stale_kb_document_title': stale_kb_document.title if stale_kb_document else None, - } - - -def _apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answer: bool = False) -> None: - """ - 将请求体字段写入 QuickQuestion 实例。 - @param qq - 待更新的 QuickQuestion - @param data - 请求 JSON - @param require_answer - 创建时为 True,cache_enabled 时强制校验 answer - """ - if 'title' in data: - qq.title = str(data['title']).strip() - if 'question' in data: - qq.question = str(data['question']).strip() - if 'agent_id' in data: - qq.agent_id = data['agent_id'] - if 'sort_order' in data: - qq.sort_order = data.get('sort_order', 0) - if 'answer' in data: - qq.answer = str(data['answer']).strip() or None - if 'aliases' in data: - qq.aliases = _parse_aliases(data['aliases']) - if 'cache_enabled' in data: - qq.cache_enabled = bool(data['cache_enabled']) - if 'is_enabled' in data: - qq.is_enabled = bool(data['is_enabled']) - if 'expires_at' in data: - qq.expires_at = _parse_expires_at(data['expires_at']) - if 'retriever_resources' in data and isinstance(data.get('retriever_resources'), list): - from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq - - apply_retriever_resources_to_faq(qq, data['retriever_resources']) - if data.get('clear_stale'): - from app.services.faq_kb_invalidation import clear_faq_stale - - clear_faq_stale(qq) - - if qq.cache_enabled and not str(qq.answer or '').strip(): - raise ValidationError('启用 FAQ 缓存时必须填写标准答案') - if require_answer and (not qq.title or not qq.question or not qq.agent_id): - raise ValidationError('Missing required fields') - - -@admin_bp.route('/quick-questions', methods=['POST']) -@require_admin -def create_quick_question(): - """ - 创建全局常用问题,可选启用 FAQ 缓存。 - @returns 201 + {id} - """ - data = request.get_json() or {} - qq = QuickQuestion(user_id=None) - _apply_quick_question_payload(qq, data, require_answer=True) - if isinstance(data.get('retriever_resources'), list): - from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq - - apply_retriever_resources_to_faq(qq, data['retriever_resources']) - qq.updated_at = datetime.utcnow() - db.session.add(qq) - db.session.commit() - return (jsonify({'id': qq.id}), 201) - - -@admin_bp.route('/quick-questions/', methods=['PUT']) -@require_admin -def update_quick_question(id): - """ - 更新全局常用问题及 FAQ 缓存配置。 - @returns {status: ok} - """ - qq = db.session.get(QuickQuestion, id) - if not qq or qq.user_id is not None: - raise NotFoundError('Not found') - data = request.get_json() or {} - _apply_quick_question_payload(qq, data) - qq.updated_at = datetime.utcnow() - db.session.commit() - return jsonify({'status': 'ok'}) - -@admin_bp.route('/quick-questions/', methods=['DELETE']) -@require_admin -def delete_quick_question(id): - qq = db.session.get(QuickQuestion, id) - if qq: - db.session.delete(qq) - db.session.commit() - return jsonify({'status': 'ok'}) - - -@admin_bp.route('/faq-candidates', methods=['GET']) -@require_admin -def list_faq_candidates(): - """ - 列出 PostgreSQL 中的热点 FAQ 候选(离线聚合结果)。 - @query agent_id - 可选,按应用筛选 - @returns { items, stats, rules } - """ - from app.services.hot_faq_aggregator import HotFaqAggregator - from app.services.hot_faq_candidate_store import HotFaqCandidateStore - - agent_id = request.args.get('agent_id', type=int) - items = HotFaqCandidateStore.list_candidates(agent_id) - stats = HotFaqCandidateStore.summarize(items) - return jsonify({ - 'items': items, - 'stats': stats, - 'rules': HotFaqAggregator.get_rules_document(), - }) - - -@admin_bp.route('/faq-candidates/refresh', methods=['POST']) -@require_admin -def refresh_faq_candidates(): - """ - 手动触发离线热点聚合。 - @body agent_id - 可选;dry_run - 可选,仅预览 - @returns 聚合结果摘要 - """ - from app.services.hot_faq_aggregator import HotFaqAggregator - - data = request.get_json(silent=True) or {} - agent_id = data.get('agent_id') - dry_run = bool(data.get('dry_run')) - if agent_id is not None: - agent_id = int(agent_id) - - result = HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run) - return jsonify(result) - - -@admin_bp.route('/faq-candidates/promote', methods=['POST']) -@require_admin -def promote_faq_candidate(): - """ - 将热点候选晋升为全局 QuickQuestion(启用 FAQ 缓存),同事务更新候选状态。 - @body agent_id, q_norm - 必填;title - 可选 - @returns { id } 新建 QuickQuestion 主键 - """ - from app.services.faq_text_utils import normalize_faq_query - from app.services.hot_faq_candidate_store import HotFaqCandidateStore - - data = request.get_json() or {} - agent_id = data.get('agent_id') - q_norm = normalize_faq_query(str(data.get('q_norm') or '')) - if not agent_id or not q_norm: - raise ValidationError('agent_id and q_norm are required') - - candidate = HotFaqCandidateStore.get_candidate(int(agent_id), q_norm) - if not candidate: - raise NotFoundError('FAQ candidate not found') - - title = str(data.get('title') or candidate.get('canonical_query') or q_norm).strip()[:100] - question = str(candidate.get('canonical_query') or q_norm).strip() - answer = str(candidate.get('answer') or '').strip() - if not answer: - raise ValidationError('Candidate has no answer') - - aliases = [q for q in (candidate.get('sample_queries') or []) if normalize_faq_query(q) != q_norm] - - retriever_resources = candidate.get('retriever_resources') if isinstance(candidate.get('retriever_resources'), list) else None - qq = QuickQuestion( - user_id=None, - agent_id=int(agent_id), - title=title, - question=question, - answer=answer, - aliases=aliases or None, - cache_enabled=True, - is_enabled=True, - retriever_resources=retriever_resources, - sort_order=int(data.get('sort_order') or 0), - updated_at=datetime.utcnow(), - ) - from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq - - apply_retriever_resources_to_faq(qq, retriever_resources) - db.session.add(qq) - db.session.flush() - if not HotFaqCandidateStore.mark_promoted(int(agent_id), q_norm, qq.id): - db.session.rollback() - raise NotFoundError('FAQ candidate not found') - db.session.commit() - return jsonify({'id': qq.id, 'status': 'ok'}) - - -@admin_bp.route('/faq-candidates/dismiss', methods=['POST']) -@require_admin -def dismiss_faq_candidate(): - """ - 忽略热点候选:标记 dismissed 并设置 deny_until。 - @body agent_id, q_norm - 必填 - @returns { status: ok } - """ - from app.services.faq_text_utils import normalize_faq_query - from app.services.hot_faq_candidate_store import HotFaqCandidateStore - - data = request.get_json() or {} - agent_id = data.get('agent_id') - q_norm = normalize_faq_query(str(data.get('q_norm') or '')) - if not agent_id or not q_norm: - raise ValidationError('agent_id and q_norm are required') - - HotFaqCandidateStore.dismiss(int(agent_id), q_norm) - return jsonify({'status': 'ok'}) - - -USAGE_BY_USER_TOP_LIMIT = 50 - - -@admin_bp.route('/reports/usage', methods=['GET']) -@require_admin -def usage_report(): - """ - 聊天使用分析:按应用汇总全部;按用户仅 TOP N(默认 50)并支持分页。 - Query: user_page(默认 1)、user_page_size(默认 10,最大 50) - """ - total = db.session.query(ChatLog).count() - by_agent = ( - db.session.query(Agent.name, func.count(ChatLog.id)) - .join(ChatLog) - .group_by(Agent.name) - .order_by(desc(func.count(ChatLog.id)), Agent.name) - .all() - ) - try: - user_page = int(request.args.get('user_page', 1)) - except (TypeError, ValueError): - user_page = 1 - try: - user_page_size = int(request.args.get('user_page_size', 10)) - except (TypeError, ValueError): - user_page_size = 10 - user_page = max(1, user_page) - user_page_size = max(1, min(user_page_size, USAGE_BY_USER_TOP_LIMIT)) - - by_user_top = ( - db.session.query(User.username, func.count(ChatLog.id)) - .join(ChatLog) - .group_by(User.username) - .order_by(desc(func.count(ChatLog.id)), User.username) - .limit(USAGE_BY_USER_TOP_LIMIT) - .all() - ) - user_total = len(by_user_top) - user_pages = max(1, math.ceil(user_total / user_page_size)) if user_total else 1 - user_page = min(user_page, user_pages) - offset = (user_page - 1) * user_page_size - by_user_page = by_user_top[offset:offset + user_page_size] - - return jsonify({ - 'total': total, - 'by_user': [{'username': u, 'count': c} for u, c in by_user_page], - 'by_agent': [{'agent': a, 'count': c} for a, c in by_agent], - 'user_total': user_total, - 'user_page': user_page, - 'user_page_size': user_page_size, - 'user_pages': user_pages, - 'user_top_limit': USAGE_BY_USER_TOP_LIMIT, - }) - -@admin_bp.route('/reports/feedback', methods=['GET']) -@require_admin -def feedback_report(): - total = db.session.query(Feedback).count() - avg = db.session.query(func.avg(Feedback.score)).scalar() or 0 - dist = db.session.query(Feedback.score, func.count(Feedback.id)).group_by(Feedback.score).all() - return jsonify({'total': total, 'avg_score': float(avg), 'distribution': [{'score': s, 'count': c} for s, c in dist]}) - -@admin_bp.route('/reports/general-feedbacks', methods=['GET']) -@require_admin -def list_general_feedbacks_report(): - """ - List rows from general_feedbacks for report page display. - Supports simple fuzzy filters by column name and optional limit. - """ - query = db.session.query(GeneralFeedback, User.real_name.label('real_name'), User.department.label('department')).outerjoin(User, User.id == GeneralFeedback.user_id) - reserved = {'limit', 'offset', 'page', 'page_size'} - for key, value in request.args.items(): - if key in reserved: - continue - if not value: - continue - if hasattr(GeneralFeedback, key): - col = getattr(GeneralFeedback, key) - elif key == 'real_name': - col = User.real_name - elif key == 'department': - col = User.department - else: - continue - query = query.filter(col.cast(db.String).ilike(f'%{value}%')) - query = query.order_by(desc(GeneralFeedback.created_at), desc(GeneralFeedback.id)) - try: - limit = int(request.args.get('limit', 200)) - except (TypeError, ValueError): - limit = 200 - limit = max(1, min(limit, 1000)) - items = query.limit(limit).all() - rows = [] - for item, real_name, department in items: - row = {} - for col in item.__table__.columns: - val = getattr(item, col.name) - if isinstance(val, datetime): - val = val.isoformat() - row[col.name] = val - row['real_name'] = real_name - row['department'] = department - rows.append(row) - return jsonify(rows) - -@admin_bp.route('/reports/general-feedbacks/count', methods=['GET']) -@require_admin -def count_general_feedbacks_report(): - query = db.session.query(GeneralFeedback).outerjoin(User, User.id == GeneralFeedback.user_id) - reserved = {'limit', 'offset', 'page', 'page_size'} - for key, value in request.args.items(): - if key in reserved: - continue - if not value: - continue - if hasattr(GeneralFeedback, key): - col = getattr(GeneralFeedback, key) - elif key == 'real_name': - col = User.real_name - elif key == 'department': - col = User.department - else: - continue - query = query.filter(col.cast(db.String).ilike(f'%{value}%')) - total = query.count() - return jsonify({'table': 'general_feedbacks', 'total': int(total)}) - -def _chat_logs_report_query(): - """ - 聊天日志报表查询:关联用户与应用,供管理后台数据报表展示。 - 核心逻辑:ChatLog JOIN User、Agent,按创建时间倒序。 - """ - return ( - db.session.query( - ChatLog, - User.username.label('username'), - User.real_name.label('real_name'), - Agent.name.label('agent_name'), - ) - .join(User, User.id == ChatLog.user_id) - .join(Agent, Agent.id == ChatLog.agent_id) - ) - - -def _serialize_chat_log_report_row(log: ChatLog, username: str | None, real_name: str | None, agent_name: str | None) -> dict: - """ - 将 ChatLog 及关联字段序列化为报表行(隐藏 run_id / 原始 ID 类外键列)。 - 保留 id 供前端批量删除使用,默认不在表格列中展示。 - """ - created_at = log.created_at.isoformat() if log.created_at else None - return { - 'id': log.id, - 'agent_name': agent_name or '', - 'username': username or '', - 'real_name': real_name or '', - 'created_at': created_at, - 'query': log.query, - 'answer': log.answer, - 'tokens_used': log.tokens_used, - } - - -def _apply_chat_logs_report_filters(query): - """ - 对聊天日志报表查询应用列筛选(支持展示列名与 ChatLog 字段名)。 - """ - reserved = {'limit', 'offset', 'page', 'page_size'} - for key, value in request.args.items(): - if key in reserved or not value: - continue - if key == 'agent_name': - query = query.filter(Agent.name.cast(db.String).ilike(f'%{value}%')) - elif key == 'username': - query = query.filter(User.username.cast(db.String).ilike(f'%{value}%')) - elif key == 'real_name': - query = query.filter(User.real_name.cast(db.String).ilike(f'%{value}%')) - elif hasattr(ChatLog, key): - col = getattr(ChatLog, key) - query = query.filter(col.cast(db.String).ilike(f'%{value}%')) - return query - - -def _list_chat_logs_report(): - """管理后台聊天日志报表数据列表(最多 100 条,支持列筛选)。""" - query = _apply_chat_logs_report_filters(_chat_logs_report_query()) - query = query.order_by(desc(ChatLog.created_at), desc(ChatLog.id)) - items = query.limit(100).all() - rows = [_serialize_chat_log_report_row(log, username, real_name, agent_name) for log, username, real_name, agent_name in items] - return jsonify(rows) - - -@admin_bp.route('/database/', methods=['GET']) -@require_admin -def get_table_data(table): - if table == 'chat_logs': - return _list_chat_logs_report() - - model_map = {'users': User, 'agents': Agent, 'chat_logs': ChatLog, 'feedbacks': Feedback, 'permission_requests': PermissionRequest, 'departments': Department, 'quick_questions': QuickQuestion, 'user_homepage_configs': UserHomepageConfig, 'user_favorite_agents': UserFavoriteAgent, 'user_default_agents': UserDefaultAgent} - model = model_map.get(table) - if not model: - raise ValidationError('Invalid table') - query = db.session.query(model) - for k, v in request.args.items(): - if hasattr(model, k): - col = getattr(model, k) - query = query.filter(col.cast(db.String).ilike(f'%{v}%')) - items = query.limit(100).all() - res = [] - for item in items: - d = {} - for col in item.__table__.columns: - val = getattr(item, col.name) - if isinstance(val, datetime): - val = val.isoformat() - d[col.name] = val - res.append(d) - return jsonify(res) - -@admin_bp.route('/database/chat_logs/batch-delete', methods=['POST']) -@require_admin -def batch_delete_chat_logs(): - """ - Batch delete chat logs by ids. - Only accepts chat_log ids to avoid accidental table-wide deletion. - """ - data = request.get_json() or {} - raw_ids = data.get('ids', []) - if not isinstance(raw_ids, list) or not raw_ids: - raise ValidationError('ids is required') - ids = [] - for v in raw_ids: - try: - ids.append(int(v)) - except (TypeError, ValueError): - continue - if not ids: - raise ValidationError('No valid ids') - cnt = db.session.query(ChatLog).filter(ChatLog.id.in_(ids)).delete(synchronize_session=False) - db.session.commit() - return jsonify({'deleted_count': cnt}) - -@admin_bp.route('/database/
/count', methods=['GET']) -@require_admin -def get_table_count(table): - """ - Return total row count for admin report tables. - """ - if table == 'chat_logs': - query = _apply_chat_logs_report_filters(_chat_logs_report_query()) - total = query.count() - return jsonify({'table': table, 'total': int(total or 0)}) - - model_map = {'users': User, 'agents': Agent, 'chat_logs': ChatLog, 'feedbacks': Feedback, 'permission_requests': PermissionRequest, 'departments': Department, 'quick_questions': QuickQuestion, 'user_homepage_configs': UserHomepageConfig, 'user_favorite_agents': UserFavoriteAgent, 'user_default_agents': UserDefaultAgent} - model = model_map.get(table) - if not model: - raise ValidationError('Invalid table') - total = db.session.query(func.count(model.id)).scalar() - return jsonify({'table': table, 'total': int(total or 0)}) - -@admin_bp.route('/wecom/bindings', methods=['GET']) -@require_admin -def list_wecom_bindings(): - """ - 分页列出用户企微绑定,支持 keyword 模糊搜索与 bound_only 筛选。 - - Query: bound_only, keyword, page, page_size - Returns: { items, total, page, page_size, pages } - """ - bound_only = request.args.get('bound_only', 'false').lower() == 'true' - keyword = (request.args.get('keyword') or '').strip() - 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)) - - query = db.session.query(User) - if bound_only: - query = query.filter(User.wecom_userid.isnot(None)) - if keyword: - pattern = f'%{keyword}%' - query = query.filter(or_( - User.username.ilike(pattern), - User.real_name.ilike(pattern), - User.employee_id.ilike(pattern), - User.wecom_userid.ilike(pattern), - )) - - total = query.count() - pages = max(1, (total + page_size - 1) // page_size) if total else 1 - if page > pages: - page = pages - - users = ( - query.order_by(User.id.asc()) - .offset((page - 1) * page_size) - .limit(page_size) - .all() - ) - items = [ - { - 'id': u.id, - 'username': u.username, - 'real_name': u.real_name, - 'employee_id': u.employee_id, - 'email': u.email, - 'role': u.role, - 'status': u.status, - 'wecom_userid': u.wecom_userid, - 'wecom_unionid': u.wecom_unionid, - 'bound': bool(u.wecom_userid), - } - for u in users - ] - return jsonify({ - 'items': items, - 'total': int(total), - 'page': page, - 'page_size': page_size, - 'pages': pages, - }) - -@admin_bp.route('/guides/upload', methods=['POST']) -@require_admin -def upload_guide(): - if 'file' not in request.files: - raise ValidationError('No file part') - file = request.files['file'] - if file.filename == '': - raise ValidationError('No selected file') - - content_type = file.content_type - file_size = len(file.read()) - file.seek(0) - - try: - object_name = minio_service.upload_file(file, file.filename, content_type, file_size) - return jsonify({ - 'file_path': object_name, - 'file_name': file.filename, - 'file_size': file_size, - 'file_type': 'video' if content_type.startswith('video') else 'pdf' if 'pdf' in content_type else 'image' - }) - except Exception as e: - import traceback - traceback.print_exc() - raise AppError(f"Upload failed: {str(e)}") - -@admin_bp.route('/guides', methods=['POST']) -@require_admin -def create_guide(): - data = request.json - guide = AgentGuide( - agent_id=data['agent_id'], - file_name=data['file_name'], - file_type=data['file_type'], - file_path=data['file_path'], - file_size=data.get('file_size'), - remark=data.get('remark'), - sort_order=data.get('sort_order', 0), - status=data.get('status', 1), - created_by=_get_auth_user().id - ) - db.session.add(guide) - db.session.commit() - return jsonify({'id': guide.id}) - -@admin_bp.route('/guides', methods=['GET']) -@require_admin -def list_guides(): - agent_id = request.args.get('agent_id') - query = db.session.query(AgentGuide) - if agent_id: - query = query.filter_by(agent_id=agent_id) - guides = query.order_by(AgentGuide.sort_order).all() - - result = [] - for g in guides: - result.append({ - 'id': g.id, - 'agent_id': g.agent_id, - 'file_name': g.file_name, - 'file_type': g.file_type, - 'file_path': g.file_path, - 'file_url': minio_service.get_public_url(g.file_path), - 'file_size': g.file_size, - 'remark': g.remark, - 'sort_order': g.sort_order, - 'status': g.status, - 'created_at': g.created_at.isoformat() - }) - return jsonify(result) - -@admin_bp.route('/guides/', methods=['PUT']) -@require_admin -def update_guide(id): - guide = db.session.query(AgentGuide).get(id) - if not guide: - raise NotFoundError('Guide not found') - - data = request.json - if 'file_name' in data: guide.file_name = data['file_name'] - if 'remark' in data: guide.remark = data['remark'] - if 'sort_order' in data: guide.sort_order = data['sort_order'] - if 'status' in data: guide.status = data['status'] - - db.session.commit() - return jsonify({'success': True}) - -@admin_bp.route('/guides/', methods=['DELETE']) -@require_admin -def delete_guide(id): - guide = db.session.query(AgentGuide).get(id) - if not guide: - raise NotFoundError('Guide not found') - - minio_service.delete_file(guide.file_path) - db.session.delete(guide) - db.session.commit() - return jsonify({'success': True}) - -@admin_bp.route('/wecom/bind', methods=['POST']) -@require_admin -def bind_wecom_user(): - """ - Bind a local user to a WeCom account (manual operation by admin). - """ - data = request.get_json() or {} - user_id = data.get('user_id') - wecom_userid = data.get('wecom_userid') - wecom_unionid = data.get('wecom_unionid') - if not user_id or not wecom_userid: - raise ValidationError('user_id and wecom_userid are required') - try: - user_id = int(user_id) - except (TypeError, ValueError): - raise ValidationError('user_id must be integer') - user = db.session.get(User, user_id) - if not user: - raise NotFoundError('User not found') - dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first() - if dup: - raise ValidationError(f'wecom_userid already bound to user {dup.username}') - if wecom_unionid: - dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first() - if dup_union: - raise ValidationError(f'wecom_unionid already bound to user {dup_union.username}') - user.wecom_userid = wecom_userid - if wecom_unionid is not None: - user.wecom_unionid = wecom_unionid - db.session.commit() - return jsonify({'status': 'ok', 'message': 'WeCom binding updated'}) - -@admin_bp.route('/wecom/unbind', methods=['POST']) -@require_admin -def unbind_wecom_user(): - """ - Unbind WeCom account from local user by admin. - """ - data = request.get_json() or {} - user_id = data.get('user_id') - if not user_id: - raise ValidationError('user_id is required') - try: - user_id = int(user_id) - except (TypeError, ValueError): - raise ValidationError('user_id must be integer') - user = db.session.get(User, user_id) - if not user: - raise NotFoundError('User not found') - user.wecom_userid = None - user.wecom_unionid = None - db.session.commit() - return jsonify({'status': 'ok', 'message': 'WeCom account unbound'}) - -@admin_bp.route('/wecom/provision', methods=['POST']) -@require_admin -def provision_wecom_user(): - """ - Atomic admin helper to create user (optional), bind WeCom identity and assign agent permissions. - """ - data = request.get_json() or {} - create_user = bool(data.get('create_user', True)) - user_data = data.get('user') or {} - bind_data = data.get('bind') or {} - user_id = data.get('user_id') - permission_updated = False - wecom_userid = (bind_data.get('wecom_userid') or '').strip() - wecom_unionid = (bind_data.get('wecom_unionid') or '').strip() - if not wecom_userid: - raise ValidationError('bind.wecom_userid is required') - if create_user: - username = (user_data.get('username') or '').strip() - if not username: - raise ValidationError('user.username is required when create_user=true') - if db.session.query(User).filter_by(username=username).first(): - raise ValidationError('Username exists') - email = (user_data.get('email') or '').strip() or None - employee_id = (user_data.get('employee_id') or '').strip() or None - phone_number = (user_data.get('phone_number') or '').strip() or None - if email and db.session.query(User).filter_by(email=email).first(): - raise ValidationError('Email already exists') - if employee_id and db.session.query(User).filter_by(employee_id=employee_id).first(): - raise ValidationError('Employee ID already exists') - if phone_number and db.session.query(User).filter_by(phone_number=phone_number).first(): - raise ValidationError('Phone number already exists') - user = User(username=username, email=email, department=user_data.get('department'), role=user_data.get('role', 'user'), status=user_data.get('status', 'active'), real_name=user_data.get('real_name'), employee_id=employee_id, phone_number=phone_number) - password = user_data.get('password') - user.set_password(password or uuid.uuid4().hex) - db.session.add(user) - db.session.flush() - binding_status = 'created' - else: - if user_id is None: - user_id = user_data.get('id') - if user_id is None: - raise ValidationError('user_id is required when create_user=false') - try: - user_id = int(user_id) - except (TypeError, ValueError): - raise ValidationError('user_id must be integer') - user = db.session.get(User, user_id) - if not user: - raise NotFoundError('User not found') - binding_status = 'updated' - dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first() - if dup: - db.session.rollback() - raise ValidationError(f'wecom_userid already bound to user {dup.username}') - if wecom_unionid: - dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first() - if dup_union: - db.session.rollback() - raise ValidationError(f'wecom_unionid already bound to user {dup_union.username}') - user.wecom_userid = wecom_userid - if wecom_unionid: - user.wecom_unionid = wecom_unionid - has_agent_ids = 'agent_ids' in data - if has_agent_ids: - agent_ids = data.get('agent_ids', []) - if not isinstance(agent_ids, list): - db.session.rollback() - raise ValidationError('agent_ids must be array') - if agent_ids: - try: - unique_ids = sorted({int(i) for i in agent_ids}) - except (TypeError, ValueError): - db.session.rollback() - raise ValidationError('agent_ids must be integer array') - agents = db.session.query(Agent).filter(Agent.id.in_(unique_ids)).all() - if len(agents) != len(unique_ids): - db.session.rollback() - raise ValidationError('Some agent_ids are invalid') - user.agents = agents - else: - user.agents = [] - permission_updated = True - try: - db.session.commit() - except IntegrityError: - db.session.rollback() - raise ValidationError('Provision failed due to data uniqueness conflict') - return (jsonify({'status': 'ok', 'user_id': user.id, 'binding': binding_status, 'permission_updated': permission_updated}), 201 if create_user else 200) - -@admin_bp.route('/wecom/login-audits', methods=['GET']) -@require_admin -def get_wecom_login_audits(): - """ - Query login audits for WeCom/password source. - """ - source = request.args.get('source') - status = request.args.get('status') - limit = request.args.get('limit', 100) - try: - limit = max(1, min(int(limit), 500)) - except ValueError: - limit = 100 - query = db.session.query(LoginAudit) - if source: - query = query.filter(LoginAudit.source == source) - if status: - query = query.filter(LoginAudit.status == status) - rows = query.order_by(LoginAudit.created_at.desc()).limit(limit).all() - return jsonify([{'id': r.id, 'user_id': r.user_id, 'username': r.username, 'source': r.source, 'status': r.status, 'reason': r.reason, 'error_code': r.error_code, 'match_rules': r.match_rules, 'match_operator': r.match_operator, 'match_result': r.match_result, 'wecom_userid': r.wecom_userid, 'ip': r.ip, 'user_agent': r.user_agent, 'created_at': r.created_at.isoformat() if r.created_at else None} for r in rows]) - -@admin_bp.route('/wecom/notify-settings', methods=['GET', 'PUT']) -@require_admin -def wecom_notify_settings(): - if request.method == 'GET': - return jsonify(_serialize_wecom_notify_settings()) - data = request.get_json() or {} - updates = {} - if 'enabled' in data: - updates['WECOM_NOTIFY_ENABLED'] = bool(data.get('enabled')) - if 'base_url' in data: - updates['WECOM_NOTIFY_BASE_URL'] = str(data.get('base_url') or '').strip() - if 'events' in data: - events = data.get('events') or [] - if isinstance(events, list): - updates['WECOM_NOTIFY_EVENTS'] = ','.join([str(x).strip() for x in events if str(x).strip()]) - for key, value in updates.items(): - current_app.config[key] = value - persist_env_settings(updates) - return jsonify({'status': 'ok', 'settings': _serialize_wecom_notify_settings()}) - -@admin_bp.route('/wecom/system-settings', methods=['GET', 'PUT']) -@require_admin -def wecom_system_settings(): - if request.method == 'GET': - return jsonify(_serialize_wecom_system_settings()) - data = request.get_json() or {} - bool_keys = {'enabled': 'WECOM_ENABLED', 'auto_create_user': 'WECOM_AUTO_CREATE_USER', 'mobile_normalize': 'WECOM_MOBILE_NORMALIZE'} - str_keys = {'corp_id': 'WECOM_CORP_ID', 'agent_id': 'WECOM_AGENT_ID', 'secret': 'WECOM_SECRET', 'redirect_uri': 'WECOM_REDIRECT_URI', 'match_rules': 'WECOM_MATCH_RULES', 'match_operator': 'WECOM_MATCH_OPERATOR', 'first_login_bind_mode': 'WECOM_FIRST_LOGIN_BIND_MODE', 'first_login_input_fields': 'WECOM_FIRST_LOGIN_INPUT_FIELDS', 'employee_id_source': 'WECOM_EMPLOYEE_ID_SOURCE', 'callback_token': 'WECOM_CALLBACK_TOKEN', 'encoding_aes_key': 'WECOM_ENCODING_AES_KEY', 'callback_url': 'WECOM_CALLBACK_URL', 'homepage_url': 'WECOM_HOMEPAGE_URL', 'trusted_domain': 'WECOM_TRUSTED_DOMAIN', 'public_base_url': 'WECOM_PUBLIC_BASE_URL'} - updates = {} - for req_key, cfg_key in bool_keys.items(): - if req_key in data: - updates[cfg_key] = bool(data.get(req_key)) - for req_key, cfg_key in str_keys.items(): - if req_key in data: - updates[cfg_key] = str(data.get(req_key) or '').strip() - for key, value in updates.items(): - current_app.config[key] = value - if current_app.config.get('WECOM_MATCH_OPERATOR') not in {'AND', 'OR'}: - current_app.config['WECOM_MATCH_OPERATOR'] = 'AND' - updates['WECOM_MATCH_OPERATOR'] = 'AND' - if current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE') not in {'match_rules', 'input_verify'}: - current_app.config['WECOM_FIRST_LOGIN_BIND_MODE'] = 'match_rules' - updates['WECOM_FIRST_LOGIN_BIND_MODE'] = 'match_rules' - persist_env_settings(updates) - return jsonify({'status': 'ok', 'settings': _serialize_wecom_system_settings()}) - -@admin_bp.route('/wecom/integration-manifest', methods=['GET']) -@require_admin -def wecom_integration_manifest(): - return jsonify(_serialize_wecom_integration_manifest()) - -@admin_bp.route('/wecom/notify-metrics', methods=['GET']) -@require_admin -def wecom_notify_metrics(): - now = datetime.utcnow() - from_time = now - timedelta(days=30) - total = db.session.query(func.count(WecomNotifyAudit.id)).filter(WecomNotifyAudit.created_at >= from_time).scalar() or 0 - sent = db.session.query(func.count(WecomNotifyAudit.id)).filter(WecomNotifyAudit.created_at >= from_time, WecomNotifyAudit.status == 'sent').scalar() or 0 - opened_24h = db.session.query(func.count(WecomNotifyAudit.id)).filter(WecomNotifyAudit.created_at >= from_time, WecomNotifyAudit.opened_at.isnot(None)).scalar() or 0 - by_event_rows = db.session.query(WecomNotifyAudit.event_type, WecomNotifyAudit.status, func.count(WecomNotifyAudit.id)).filter(WecomNotifyAudit.created_at >= from_time).group_by(WecomNotifyAudit.event_type, WecomNotifyAudit.status).all() - by_event = {} - for event_type, status, cnt in by_event_rows: - if event_type not in by_event: - by_event[event_type] = {'sent': 0, 'failed': 0} - by_event[event_type][status] = int(cnt) - return jsonify({'window_days': 30, 'total': int(total), 'sent': int(sent), 'failed': int(total - sent), 'send_success_rate': round(sent / total * 100, 2) if total else 0, 'opened_24h': int(opened_24h), 'opened_24h_rate': round(opened_24h / sent * 100, 2) if sent else 0, 'by_event': by_event}) - - -@admin_bp.route('/wecom/binding-stats', methods=['GET']) -@require_admin -def wecom_binding_stats(): - """ - 返回活跃用户的企微 userid 绑定统计,供管理端概览卡片使用。 - """ - total_active = db.session.query(func.count(User.id)).filter(User.status == 'active').scalar() or 0 - bound = ( - db.session.query(func.count(User.id)) - .filter(User.status == 'active', User.wecom_userid.isnot(None), User.wecom_userid != '') - .scalar() - or 0 - ) - total_active = int(total_active) - bound = int(bound) - return jsonify( - { - 'total_active': total_active, - 'bound': bound, - 'unbound': max(total_active - bound, 0), - 'bound_rate': round(bound / total_active * 100, 2) if total_active else 0, - } - ) - - -@admin_bp.route('/wecom/sync-userids', methods=['POST']) -@require_admin -def sync_wecom_userids_admin(): - """ - 从 OA userInfo_view 按工号同步 users.wecom_userid(workcode→employee_id,id→wecom_userid)。 - Request JSON: { "apply": false } - """ - data = request.get_json() or {} - apply = bool(data.get('apply')) - try: - summary = sync_wecom_userids_from_oa(apply=apply) - current_app.logger.info( - '[wecom_sync] oa apply=%s updated=%s would_update=%s conflicts=%s local_matched=%s', - apply, - summary.get('updated'), - summary.get('would_update'), - len(summary.get('conflicts') or []), - summary.get('local_matched'), - ) - return jsonify(summary) - except RuntimeError as exc: - message = str(exc) - if 'conflicts detected' in message.lower(): - raise ConflictError(message, details={'error_code': 'WECOM_SYNC_CONFLICTS'}) - if '未找到可用的 SQL Server ODBC 驱动' in message or 'pyodbc' in message.lower(): - raise AppError( - code='SYSTEM.SERVICE_UNAVAILABLE', - message='OA SQL Server driver is not available on this server', - http_status=503, - details={'error_code': 'OA_SQLSERVER_DRIVER_MISSING', 'technical': message[:300]}, - ) - raise AppError( - code='SYSTEM.HTTP_ERROR', - message='OA SQL Server sync failed. Check OA_SQLSERVER_* env and network access.', - http_status=502, - details={'error_code': 'OA_SQLSERVER_SYNC_FAILED', 'technical': message[:300]}, - ) - except Exception as exc: - current_app.logger.exception('[wecom_sync] oa unexpected failure: %s', exc) - raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500) - diff --git a/backend/app/api/admin/__init__.py b/backend/app/api/admin/__init__.py new file mode 100644 index 00000000..de51361d --- /dev/null +++ b/backend/app/api/admin/__init__.py @@ -0,0 +1,23 @@ +""" +backend/app/api/admin/__init__.py + +用途:管理后台 Blueprint 入口(Wave 3 分包)。 +依赖:admin/blueprint.py 及各子模块路由。 +逻辑:import 子模块注册路由;register_blueprints 从本包 import admin_bp。 +""" +from app.api.admin.blueprint import admin_bp + +import app.api.admin.dashboard # noqa: F401 +import app.api.admin.departments # noqa: F401 +import app.api.admin.agents # noqa: F401 +import app.api.admin.guides # noqa: F401 +import app.api.admin.quick_questions # noqa: F401 +import app.api.admin.faq_candidates # noqa: F401 +import app.api.admin.reports # noqa: F401 +import app.api.admin.database # noqa: F401 +import app.api.admin.permissions # noqa: F401 +import app.api.admin.users # noqa: F401 +import app.api.admin.wecom # noqa: F401 +import app.api.admin.announcements # noqa: F401 + +__all__ = ['admin_bp'] diff --git a/backend/app/api/admin/agents.py b/backend/app/api/admin/agents.py new file mode 100644 index 00000000..b39b4aa7 --- /dev/null +++ b/backend/app/api/admin/agents.py @@ -0,0 +1,63 @@ +""" +backend/app/api/admin/agents.py + +用途:管理后台 Agent CRUD、连通性测试、权限绑定 API(薄路由层)。 +依赖:admin.blueprint、services/admin/agent_service。 +逻辑:/agents* 路由。 +""" +from flask import jsonify, request + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.services.admin import agent_service + + +@admin_bp.route('/agents', methods=['GET']) +@require_admin +def list_agents(): + """返回全部 Agent 列表。""" + return jsonify(agent_service.list_agents()) + + +@admin_bp.route('/agents', methods=['POST']) +@require_admin +def create_agent(): + """创建 Agent。""" + data = request.get_json() or {} + payload = agent_service.create_agent(data) + return jsonify(payload), 201 + + +@admin_bp.route('/agents/', methods=['PUT']) +@require_admin +def update_agent(id: int): + """更新 Agent。""" + data = request.get_json() or {} + agent_service.update_agent(id, data) + return jsonify({'status': 'ok'}) + + +@admin_bp.route('/agents/', methods=['DELETE']) +@require_admin +def delete_agent(id: int): + """删除 Agent。""" + agent_service.delete_agent(id) + return jsonify({'status': 'ok'}) + + +@admin_bp.route('/agents//test', methods=['POST']) +@require_admin +def test_agent(id: int): + """测试 Agent 连通性。""" + payload = agent_service.test_agent_connectivity(id) + return jsonify(payload), 200 + + +@admin_bp.route('/agents//permissions', methods=['POST']) +@require_admin +def update_agent_permissions(id: int): + """设置 Agent 授权用户列表。""" + data = request.get_json() or {} + user_ids = data.get('user_ids', []) + agent_service.update_agent_permissions(id, user_ids) + return jsonify({'status': 'ok'}) diff --git a/backend/app/api/admin/announcements.py b/backend/app/api/admin/announcements.py new file mode 100644 index 00000000..edf26fee --- /dev/null +++ b/backend/app/api/admin/announcements.py @@ -0,0 +1,43 @@ +""" +backend/app/api/admin/announcements.py + +用途:管理后台公告 CRUD API(薄路由层)。 +依赖:admin.blueprint、services/admin/announcement_service。 +逻辑:/announcements* 路由;工作台只读见 api/workspace/announcements.py。 +""" +from flask import jsonify, request + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.services.admin import announcement_service + + +@admin_bp.route('/announcements', methods=['GET']) +@require_admin +def list_announcements(): + """列出全部公告(含 is_active)。""" + return jsonify(announcement_service.list_announcements()) + + +@admin_bp.route('/announcements', methods=['POST']) +@require_admin +def create_announcement(): + """创建公告。""" + data = request.get_json() or {} + payload = announcement_service.create_announcement(data) + return jsonify(payload), 201 + + +@admin_bp.route('/announcements/', methods=['PUT']) +@require_admin +def update_announcement(id: int): + """更新公告。""" + data = request.get_json() or {} + return jsonify(announcement_service.update_announcement(id, data)) + + +@admin_bp.route('/announcements/', methods=['DELETE']) +@require_admin +def delete_announcement(id: int): + """删除公告。""" + return jsonify(announcement_service.delete_announcement(id)) diff --git a/backend/app/api/admin/blueprint.py b/backend/app/api/admin/blueprint.py new file mode 100644 index 00000000..2b8a1bb3 --- /dev/null +++ b/backend/app/api/admin/blueprint.py @@ -0,0 +1,10 @@ +""" +backend/app/api/admin/blueprint.py + +用途:管理后台 API 共享 Blueprint(Wave 3 分包后各子模块共用)。 +依赖:Flask Blueprint。 +逻辑:dashboard、departments、users、wecom 等子模块在此 bp 上注册路由;__init__ 导出 admin_bp。 +""" +from flask import Blueprint + +admin_bp = Blueprint('admin', __name__) diff --git a/backend/app/api/admin/dashboard.py b/backend/app/api/admin/dashboard.py new file mode 100644 index 00000000..48603c5b --- /dev/null +++ b/backend/app/api/admin/dashboard.py @@ -0,0 +1,42 @@ +""" +backend/app/api/admin/dashboard.py + +用途:管理后台仪表盘 API(薄路由层)。 +依赖:admin.blueprint、services/admin/dashboard_service。 +逻辑:/dashboard* 路由。 +""" +from flask import jsonify + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.services.admin import dashboard_service + + +@admin_bp.route('/dashboard/summary', methods=['GET']) +@require_admin +def dashboard_summary(): + """ + 管理后台仪表盘概览(供 Dashboard 页单次请求)。 + GET /api/admin/dashboard/summary + """ + return jsonify(dashboard_service.compute_dashboard_summary()) + + +@admin_bp.route('/dashboard/badges', methods=['GET']) +@require_admin +def dashboard_badges(): + """ + 管理后台侧栏待办角标(供 AdminLayout 轻量轮询/缓存刷新)。 + GET /api/admin/dashboard/badges + """ + return jsonify(dashboard_service.compute_dashboard_badges()) + + +@admin_bp.route('/dashboard', methods=['GET']) +@require_admin +def dashboard_stats(): + """ + 仪表盘统计(遗留接口;新代码请用 /dashboard/summary 与 /dashboard/badges)。 + GET /api/admin/dashboard + """ + return jsonify(dashboard_service.compute_legacy_dashboard_stats()) diff --git a/backend/app/api/admin/database.py b/backend/app/api/admin/database.py new file mode 100644 index 00000000..0367ee0b --- /dev/null +++ b/backend/app/api/admin/database.py @@ -0,0 +1,38 @@ +""" +backend/app/api/admin/database.py + +用途:管理后台数据表浏览 API(薄路由层)。 +依赖:admin.blueprint、services/admin/database_admin_service。 +逻辑:/database/* 路由。 +""" +from flask import jsonify, request + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.services.admin import database_admin_service + + +def _query_params() -> dict[str, str]: + return {k: str(v) for k, v in request.args.items()} + + +@admin_bp.route('/database/
', methods=['GET']) +@require_admin +def get_table_data(table: str): + """浏览指定表数据(最多 100 行)。""" + return jsonify(database_admin_service.get_table_data(table, _query_params())) + + +@admin_bp.route('/database/chat_logs/batch-delete', methods=['POST']) +@require_admin +def batch_delete_chat_logs(): + """批量删除 chat_logs。""" + data = request.get_json() or {} + return jsonify(database_admin_service.batch_delete_chat_logs(data.get('ids', []))) + + +@admin_bp.route('/database/
/count', methods=['GET']) +@require_admin +def get_table_count(table: str): + """返回表行数。""" + return jsonify(database_admin_service.get_table_count(table, _query_params())) diff --git a/backend/app/api/admin/departments.py b/backend/app/api/admin/departments.py new file mode 100644 index 00000000..f740a667 --- /dev/null +++ b/backend/app/api/admin/departments.py @@ -0,0 +1,45 @@ +""" +backend/app/api/admin/departments.py + +用途:管理后台部门 CRUD API(薄路由层)。 +依赖:admin.blueprint、services/admin/department_service。 +逻辑:/departments* 路由。 +""" +from flask import jsonify, request + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.services.admin import department_service + + +@admin_bp.route('/departments', methods=['GET']) +@require_admin +def list_departments(): + """返回全部部门列表。""" + return jsonify(department_service.list_departments()) + + +@admin_bp.route('/departments', methods=['POST']) +@require_admin +def create_department(): + """创建部门。""" + data = request.get_json() or {} + payload = department_service.create_department(data) + return jsonify(payload), 201 + + +@admin_bp.route('/departments/', methods=['PUT']) +@require_admin +def update_department(id: int): + """更新部门。""" + data = request.get_json() or {} + department_service.update_department(id, data) + return jsonify({'status': 'ok'}) + + +@admin_bp.route('/departments/', methods=['DELETE']) +@require_admin +def delete_department(id: int): + """删除部门。""" + department_service.delete_department(id) + return jsonify({'status': 'ok'}) diff --git a/backend/app/api/admin/faq_candidates.py b/backend/app/api/admin/faq_candidates.py new file mode 100644 index 00000000..94a76614 --- /dev/null +++ b/backend/app/api/admin/faq_candidates.py @@ -0,0 +1,50 @@ +""" +backend/app/api/admin/faq_candidates.py + +用途:热点 FAQ 候选管理 API(薄路由层)。 +依赖:admin.blueprint、services/admin/faq_service。 +逻辑:/faq-candidates* 路由。 +""" +from flask import jsonify, request + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.services.admin import faq_service + + +@admin_bp.route('/faq-candidates', methods=['GET']) +@require_admin +def list_faq_candidates(): + """列出 PostgreSQL 热点 FAQ 候选。""" + agent_id = request.args.get('agent_id', type=int) + return jsonify(faq_service.list_faq_candidates(agent_id=agent_id)) + + +@admin_bp.route('/faq-candidates/refresh', methods=['POST']) +@require_admin +def refresh_faq_candidates(): + """手动触发离线热点聚合。""" + data = request.get_json(silent=True) or {} + agent_id = data.get('agent_id') + dry_run = bool(data.get('dry_run')) + if agent_id is not None: + agent_id = int(agent_id) + return jsonify(faq_service.refresh_faq_candidates(agent_id=agent_id, dry_run=dry_run)) + + +@admin_bp.route('/faq-candidates/promote', methods=['POST']) +@require_admin +def promote_faq_candidate(): + """将热点候选晋升为 QuickQuestion。""" + data = request.get_json() or {} + return jsonify(faq_service.promote_faq_candidate(data)) + + +@admin_bp.route('/faq-candidates/dismiss', methods=['POST']) +@require_admin +def dismiss_faq_candidate(): + """忽略热点 FAQ 候选。""" + data = request.get_json() or {} + agent_id = data.get('agent_id') + q_norm = str(data.get('q_norm') or '') + return jsonify(faq_service.dismiss_faq_candidate(agent_id=int(agent_id), q_norm=q_norm)) diff --git a/backend/app/api/admin/guides.py b/backend/app/api/admin/guides.py new file mode 100644 index 00000000..65d13450 --- /dev/null +++ b/backend/app/api/admin/guides.py @@ -0,0 +1,57 @@ +""" +backend/app/api/admin/guides.py + +用途:Agent 引导资料 API(薄路由层)。 +依赖:admin.blueprint、services/admin/guide_service。 +逻辑:/guides* 路由。 +""" +from flask import jsonify, request + +from app.api.admin.blueprint import admin_bp +from app.core.auth.jwt import get_current_user +from app.core.decorators import require_admin +from app.services.admin import guide_service + + +@admin_bp.route('/guides/upload', methods=['POST']) +@require_admin +def upload_guide(): + """上传引导文件至 MinIO。""" + file = request.files.get('file') + return jsonify(guide_service.upload_guide_file(file)) + + +@admin_bp.route('/guides', methods=['POST']) +@require_admin +def create_guide(): + """创建引导记录。""" + data = request.get_json(silent=True) or {} + current_user = get_current_user() + payload = guide_service.create_guide(data, created_by_id=getattr(current_user, 'id', None)) + return jsonify(payload) + + +@admin_bp.route('/guides', methods=['GET']) +@require_admin +def list_guides(): + """列出引导资料,可按 agent_id 过滤。""" + agent_id_raw = request.args.get('agent_id') + agent_id = int(agent_id_raw) if agent_id_raw else None + return jsonify(guide_service.list_guides(agent_id=agent_id)) + + +@admin_bp.route('/guides/', methods=['PUT']) +@require_admin +def update_guide(id: int): + """更新引导元数据。""" + data = request.get_json(silent=True) or {} + guide_service.update_guide(id, data) + return jsonify({'success': True}) + + +@admin_bp.route('/guides/', methods=['DELETE']) +@require_admin +def delete_guide(id: int): + """删除引导及 MinIO 文件。""" + guide_service.delete_guide(id) + return jsonify({'success': True}) diff --git a/backend/app/api/admin/permissions.py b/backend/app/api/admin/permissions.py new file mode 100644 index 00000000..f3063677 --- /dev/null +++ b/backend/app/api/admin/permissions.py @@ -0,0 +1,49 @@ +""" +backend/app/api/admin/permissions.py + +用途:管理后台权限批量更新与权限申请审批 API(薄路由层)。 +依赖:admin.blueprint、services/admin/permission_service。 +逻辑:/permissions/*、/permission-requests/*、/users//permissions 路由。 +""" +from flask import jsonify, request + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.services.admin import permission_service + + +@admin_bp.route('/permissions/batch', methods=['POST']) +@require_admin +def batch_update_permissions(): + """批量更新用户 Agent 权限(add / remove / set)。""" + data = request.get_json() or {} + return jsonify(permission_service.batch_update_permissions(data)) + + +@admin_bp.route('/users//permissions', methods=['POST']) +@require_admin +def update_user_permissions(id: int): + """将指定用户的 Agent 权限重置为请求体 agent_ids。""" + data = request.get_json() or {} + return jsonify(permission_service.update_user_permissions(id, data)) + + +@admin_bp.route('/permission-requests', methods=['GET']) +@require_admin +def list_permission_requests(): + """列出全部权限申请。""" + return jsonify(permission_service.list_permission_requests()) + + +@admin_bp.route('/permission-requests//approve', methods=['POST']) +@require_admin +def approve_request(id: int): + """批准权限申请。""" + return jsonify(permission_service.approve_permission_request(id)) + + +@admin_bp.route('/permission-requests//reject', methods=['POST']) +@require_admin +def reject_request(id: int): + """拒绝权限申请。""" + return jsonify(permission_service.reject_permission_request(id)) diff --git a/backend/app/api/admin/quick_questions.py b/backend/app/api/admin/quick_questions.py new file mode 100644 index 00000000..14e37c78 --- /dev/null +++ b/backend/app/api/admin/quick_questions.py @@ -0,0 +1,46 @@ +""" +backend/app/api/admin/quick_questions.py + +用途:全局常用问题 CRUD API(薄路由层)。 +依赖:admin.blueprint、services/admin/faq_service。 +逻辑:/quick-questions* 路由。 +""" +from flask import jsonify, request + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.services.admin import faq_service + + +@admin_bp.route('/quick-questions', methods=['GET']) +@require_admin +def list_quick_questions(): + """列出全局常用问题,可选 stale_only 过滤。""" + stale_only = str(request.args.get('stale_only', '')).lower() in {'1', 'true', 'yes'} + return jsonify(faq_service.list_quick_questions(stale_only=stale_only)) + + +@admin_bp.route('/quick-questions', methods=['POST']) +@require_admin +def create_quick_question(): + """创建全局常用问题。""" + data = request.get_json() or {} + payload = faq_service.create_quick_question(data) + return jsonify(payload), 201 + + +@admin_bp.route('/quick-questions/', methods=['PUT']) +@require_admin +def update_quick_question(id: int): + """更新全局常用问题。""" + data = request.get_json() or {} + faq_service.update_quick_question(id, data) + return jsonify({'status': 'ok'}) + + +@admin_bp.route('/quick-questions/', methods=['DELETE']) +@require_admin +def delete_quick_question(id: int): + """删除全局常用问题。""" + faq_service.delete_quick_question(id) + return jsonify({'status': 'ok'}) diff --git a/backend/app/api/admin/reports.py b/backend/app/api/admin/reports.py new file mode 100644 index 00000000..99b056fb --- /dev/null +++ b/backend/app/api/admin/reports.py @@ -0,0 +1,52 @@ +""" +backend/app/api/admin/reports.py + +用途:管理后台报表 API(薄路由层)。 +依赖:admin.blueprint、services/admin/report_service。 +逻辑:/reports/* 路由。 +""" +from flask import jsonify, request + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.services.admin import report_service + + +def _query_params() -> dict[str, str]: + return {k: str(v) for k, v in request.args.items()} + + +@admin_bp.route('/reports/usage', methods=['GET']) +@require_admin +def usage_report(): + """聊天使用分析报表。""" + try: + user_page = int(request.args.get('user_page', 1)) + except (TypeError, ValueError): + user_page = 1 + try: + user_page_size = int(request.args.get('user_page_size', 10)) + except (TypeError, ValueError): + user_page_size = 10 + return jsonify(report_service.build_usage_report(user_page=user_page, user_page_size=user_page_size)) + + +@admin_bp.route('/reports/feedback', methods=['GET']) +@require_admin +def feedback_report(): + """反馈评分分布报表。""" + return jsonify(report_service.build_feedback_report()) + + +@admin_bp.route('/reports/general-feedbacks', methods=['GET']) +@require_admin +def list_general_feedbacks_report(): + """通用反馈列表。""" + return jsonify(report_service.list_general_feedbacks_report(_query_params())) + + +@admin_bp.route('/reports/general-feedbacks/count', methods=['GET']) +@require_admin +def count_general_feedbacks_report(): + """通用反馈计数。""" + return jsonify(report_service.count_general_feedbacks_report(_query_params())) diff --git a/backend/app/api/admin/users.py b/backend/app/api/admin/users.py new file mode 100644 index 00000000..4f669863 --- /dev/null +++ b/backend/app/api/admin/users.py @@ -0,0 +1,82 @@ +""" +backend/app/api/admin/users.py + +用途:管理后台用户 CRUD API(薄路由层)。 +依赖:admin.blueprint、services/admin/user_service、core.auth.jwt。 +逻辑:/users* 路由。 +""" +from flask import jsonify, request + +from app.api.admin.blueprint import admin_bp +from app.core.auth.jwt import get_current_user as _get_auth_user +from app.core.decorators import require_admin +from app.services.admin import user_service + + +def _query_params() -> dict[str, str]: + return {k: str(v) for k, v in request.args.items()} + + +@admin_bp.route('/users', methods=['GET']) +@require_admin +def list_users(): + """列出管理端用户(支持分页与筛选)。""" + result = user_service.list_users(_query_params()) + return jsonify(result) + + +@admin_bp.route('/users', methods=['POST']) +@require_admin +def create_user(): + """创建用户并同步 Casdoor。""" + data = request.get_json() or {} + payload = user_service.create_user(data) + return jsonify(payload), 201 + + +@admin_bp.route('/users/', methods=['PUT']) +@require_admin +def update_user(id: int): + """更新用户资料;有 password 时同步 Casdoor 改密。""" + data = request.get_json() or {} + return jsonify(user_service.update_user(id, data)) + + +@admin_bp.route('/users/cleanup-rejected', methods=['POST']) +@require_admin +def cleanup_rejected_users(): + """批量删除 status=rejected 的用户。""" + return jsonify(user_service.cleanup_rejected_users()) + + +@admin_bp.route('/users/batch-delete', methods=['POST']) +@require_admin +def batch_delete_users(): + """批量删除用户(排除当前登录管理员)。""" + data = request.get_json() or {} + current_user = _get_auth_user() + current_user_id = current_user.id if current_user else None + return jsonify(user_service.batch_delete_users(data.get('user_ids', []), current_user_id=current_user_id)) + + +@admin_bp.route('/users/', methods=['DELETE']) +@require_admin +def delete_user(id: int): + """删除单个用户。""" + current_user = _get_auth_user() + current_user_id = current_user.id if current_user else None + return jsonify(user_service.delete_user(id, current_user_id=current_user_id)) + + +@admin_bp.route('/users//approve', methods=['POST']) +@require_admin +def approve_user(id: int): + """审批通过用户。""" + return jsonify(user_service.approve_user(id)) + + +@admin_bp.route('/users//reject', methods=['POST']) +@require_admin +def reject_user(id: int): + """拒绝用户注册。""" + return jsonify(user_service.reject_user(id)) diff --git a/backend/app/api/admin/wecom.py b/backend/app/api/admin/wecom.py new file mode 100644 index 00000000..c09a3ec9 --- /dev/null +++ b/backend/app/api/admin/wecom.py @@ -0,0 +1,118 @@ +""" +backend/app/api/admin/wecom.py + +用途:管理后台企微绑定、配置与诊断 API(薄路由层)。 +依赖:admin.blueprint、services/admin/wecom_admin_service。 +逻辑:/wecom/* 路由。 +""" +from flask import jsonify, request + +from app.api.admin.blueprint import admin_bp +from app.core.decorators import require_admin +from app.services.admin import wecom_admin_service + + +def _query_params() -> dict[str, str]: + return {k: str(v) for k, v in request.args.items()} + + +@admin_bp.route('/wecom/debug-user-by-code', methods=['POST']) +@require_admin +def debug_wecom_user_by_code(): + """通过 OAuth code 诊断企微用户匹配结果。""" + data = request.get_json() or {} + return jsonify(wecom_admin_service.debug_user_by_code(data.get('code'))) + + +@admin_bp.route('/wecom/bindings', methods=['GET']) +@require_admin +def list_wecom_bindings(): + """分页列出企微绑定。""" + return jsonify(wecom_admin_service.list_bindings(_query_params())) + + +@admin_bp.route('/wecom/bind', methods=['POST']) +@require_admin +def bind_wecom_user(): + """管理员手动绑定企微账号。""" + data = request.get_json() or {} + return jsonify(wecom_admin_service.bind_user(data)) + + +@admin_bp.route('/wecom/unbind', methods=['POST']) +@require_admin +def unbind_wecom_user(): + """管理员解绑企微账号。""" + data = request.get_json() or {} + return jsonify(wecom_admin_service.unbind_user(data)) + + +@admin_bp.route('/wecom/provision', methods=['POST']) +@require_admin +def provision_wecom_user(): + """创建/更新用户并绑定企微、分配权限。""" + data = request.get_json() or {} + payload, status_code = wecom_admin_service.provision_user(data) + return jsonify(payload), status_code + + +@admin_bp.route('/wecom/login-audits', methods=['GET']) +@require_admin +def get_wecom_login_audits(): + """查询登录审计(企微/密码等来源)。""" + return jsonify(wecom_admin_service.list_login_audits(_query_params())) + + +@admin_bp.route('/wecom/notify-settings', methods=['GET', 'PUT']) +@require_admin +def wecom_notify_settings(): + """读取或更新企微通知配置。""" + if request.method == 'GET': + return jsonify(wecom_admin_service.serialize_notify_settings()) + data = request.get_json() or {} + return jsonify(wecom_admin_service.update_notify_settings(data)) + + +@admin_bp.route('/wecom/system-settings', methods=['GET', 'PUT']) +@require_admin +def wecom_system_settings(): + """读取或更新企微 OAuth 系统配置。""" + if request.method == 'GET': + return jsonify(wecom_admin_service.serialize_system_settings()) + data = request.get_json() or {} + return jsonify(wecom_admin_service.update_system_settings(data)) + + +@admin_bp.route('/wecom/integration-manifest', methods=['GET']) +@require_admin +def wecom_integration_manifest(): + """返回企微集成 manifest(回调 URL、OAuth 端点等)。""" + return jsonify( + wecom_admin_service.integration_manifest( + host_url=request.host_url, + host=request.host, + ) + ) + + +@admin_bp.route('/wecom/notify-metrics', methods=['GET']) +@require_admin +def wecom_notify_metrics(): + """企微通知发送/打开率指标(近 30 天)。""" + return jsonify(wecom_admin_service.notify_metrics()) + + +@admin_bp.route('/wecom/binding-stats', methods=['GET']) +@require_admin +def wecom_binding_stats(): + """活跃用户企微绑定统计。""" + return jsonify(wecom_admin_service.binding_stats()) + + +@admin_bp.route('/wecom/sync-userids', methods=['POST']) +@require_admin +def sync_wecom_userids_admin(): + """从 OA 按工号同步 users.wecom_userid。""" + data = request.get_json() or {} + apply = bool(data.get('apply')) + return jsonify(wecom_admin_service.sync_userids(apply=apply)) diff --git a/backend/app/api/schedule/__init__.py b/backend/app/api/schedule/__init__.py index ad1b1391..acd3ea17 100644 --- a/backend/app/api/schedule/__init__.py +++ b/backend/app/api/schedule/__init__.py @@ -1,10 +1,15 @@ """ backend/app/api/schedule/__init__.py -用途:排程管理 Blueprint 入口(Wave 3:自 schedule_admin 单体迁入 _legacy)。 -依赖:schedule/_legacy.py(路由实现)、schedule/* services。 -逻辑:register_blueprints 从本包 import schedule_admin_bp;后续从 _legacy 拆 tasks.py / runs.py。 +用途:排程管理 Blueprint 入口(Wave 3 分包)。 +依赖:schedule/blueprint.py、config、tasks、runs。 +逻辑:import 子模块注册路由;register_blueprints 从本包 import schedule_admin_bp。 """ -from app.api.schedule._legacy import schedule_admin_bp +from app.api.schedule.blueprint import schedule_admin_bp + +import app.api.schedule.common # noqa: F401 +import app.api.schedule.config # noqa: F401 +import app.api.schedule.tasks # noqa: F401 +import app.api.schedule.runs # noqa: F401 __all__ = ['schedule_admin_bp'] diff --git a/backend/app/api/schedule/_legacy.py b/backend/app/api/schedule/_legacy.py deleted file mode 100644 index 9b501f4c..00000000 --- a/backend/app/api/schedule/_legacy.py +++ /dev/null @@ -1,529 +0,0 @@ -""" -backend/app/api/schedule/_legacy.py - -用途:排程任务与运行记录管理 API(admin 域,Wave 3 迁包源文件)。 -依赖:app.core.decorators、app.core.auth.jwt、app.core.errors、schedule/* services。 -逻辑:管理员 CRUD ScheduleTask、触发运行、导出;后续拆至 schedule/tasks.py、runs.py。 -""" -from __future__ import annotations -import threading -from datetime import datetime -from flask import Blueprint, current_app, jsonify, request, send_file -from flask import Response -from io import BytesIO -import json -from app.core.decorators import require_admin -from app import db -from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig -from app.core.auth.jwt import get_current_user -from app.services.schedule.query_service import get_run, list_runs, list_tasks, serialize_run, serialize_task -from app.services.schedule.scheduler_service import create_task, run_task_now, update_task, _generate_run_no, _generate_test_run_no, _notify_schedule_run_wecom -from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id, upsert_schedule_task_config, _build_fetch_sql -from app.services.schedule.srm_service import _fetch_records -from app.core.errors import ( - AppError, - ConflictError, - ForbiddenError, - NotFoundError, - ServiceUnavailableError, - UnauthorizedError, - ValidationError, - raise_for_status, -) -schedule_admin_bp = Blueprint('schedule_admin', __name__) - -def _serialize_task_for_export(task: ScheduleTask, cfg_model: ScheduleTaskConfig | None) -> dict: - payload = serialize_task(task) - payload['config'] = _serialize_task_config(cfg_model) if cfg_model else None - return payload - -def _serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict: - return {'row_id_key': cfg_model.row_id_key or 'id', 'log_prefix': cfg_model.log_prefix or '', 'base_fetch_sql': cfg_model.base_fetch_sql or '', 'fetch_where_conditions': cfg_model.fetch_where_conditions or '', 'fetch_order_by': cfg_model.fetch_order_by or '', 'writeback_sql': cfg_model.writeback_sql or '', 'detail_sql': cfg_model.detail_sql or '', 'alias_order': cfg_model.alias_order or [], 'detail_alias_order': cfg_model.detail_alias_order or [], 'header_labels': cfg_model.header_labels or {}, 'data_source': {'db_type': cfg_model.ds_db_type or 'sqlserver', 'host': cfg_model.ds_host or '', 'port': cfg_model.ds_port or '', 'database': cfg_model.ds_database or '', 'username': cfg_model.ds_username or '', 'password': cfg_model.ds_password or '', 'driver': cfg_model.ds_driver or '', 'encrypt': cfg_model.ds_encrypt or '', 'trust_cert': cfg_model.ds_trust_cert or ''}, 'external_api': {'url': cfg_model.api_url or '', 'method': cfg_model.api_method or 'POST', 'headers': cfg_model.api_headers or {}, 'body_template': cfg_model.api_body_template or ''}, 'dify_system_prompt': cfg_model.dify_system_prompt or ''} - -@schedule_admin_bp.route('/schedule-config/', methods=['GET']) -@require_admin -def get_schedule_task_config(task_id: int): - task = db.session.get(ScheduleTask, task_id) - if not task: - raise NotFoundError('Not found') - cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first() - if not cfg_model: - return jsonify({'data_source_type': task.data_source_type, 'config': None}) - return jsonify({'data_source_type': task.data_source_type, 'config': _serialize_task_config(cfg_model)}) - -@schedule_admin_bp.route('/schedule-config/', methods=['PUT']) -@require_admin -def update_schedule_task_config(task_id: int): - task = db.session.get(ScheduleTask, task_id) - if not task: - raise NotFoundError('Not found') - data = request.get_json(silent=True) or {} - try: - if 'data_source_type' in data: - task.data_source_type = str(data['data_source_type']) - db.session.commit() - config_data = data.get('config', data) - cfg = upsert_schedule_task_config(task_id, config_data) - cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first() - return jsonify({'data_source_type': task.data_source_type, 'config': _serialize_task_config(cfg_model) if cfg_model else None}) - except Exception as e: - db.session.rollback() - raise ValidationError(str(e)) - -@schedule_admin_bp.route('/schedule-config//test-sql', methods=['POST']) -@require_admin -def test_schedule_sql(task_id: int): - cfg = get_schedule_sql_config_by_task_id(task_id) - if not cfg: - raise NotFoundError(f'Config for task {task_id} not found') - data = request.get_json(silent=True) or {} - custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip() - custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip() - limit = min(int(data.get('limit') or 10), 100) - base = cfg.base_fetch_sql or cfg.fetch_sql - if cfg.base_fetch_sql: - sql = _build_fetch_sql(base, custom_where, custom_order_by) - else: - sql = base - try: - from app.services.schedule import _build_srm_conn_str - import decimal, datetime - if cfg.data_source and (not cfg.data_source.is_empty()): - conn_str = cfg.data_source.build_connection_string() - else: - conn_str = _build_srm_conn_str() - rows = _fetch_records(conn_str, sql) - - def _safe(v): - if isinstance(v, decimal.Decimal): - return float(v) - if isinstance(v, (datetime.date, datetime.datetime)): - return v.isoformat() - if isinstance(v, datetime.timedelta): - return str(v) - return v - result_rows = [{k: _safe(v) for k, v in r.items()} for r in rows[:limit]] - return jsonify({'total': len(rows), 'showing': len(result_rows), 'limit': limit, 'sql': sql, 'columns': list(result_rows[0].keys()) if result_rows else [], 'rows': result_rows}) - except Exception as e: - raise AppError(code='SYSTEM.HTTP_ERROR', message=str(e), http_status=400, details={'sql': sql}) - -@schedule_admin_bp.route('/schedule-config//test-run', methods=['POST']) -@require_admin -def test_schedule_run(task_id: int): - import time as _time - from app.services.schedule.excel_service import export_schedule_result_excel - task = db.session.get(ScheduleTask, task_id) - if not task: - raise NotFoundError('Not found') - cfg = get_schedule_sql_config_by_task_id(task_id) - if not cfg: - raise NotFoundError(f'Config for task {task_id} not found') - data = request.get_json(silent=True) or {} - custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip() - custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip() - limit = min(int(data.get('limit') or 3), 10) - raw_kb_sync = data.get('kb_sync_enabled', False) - if isinstance(raw_kb_sync, str): - test_kb_sync_enabled = raw_kb_sync.strip().lower() in ('1', 'true', 'yes', 'on') - else: - test_kb_sync_enabled = bool(raw_kb_sync) - base = cfg.base_fetch_sql or cfg.fetch_sql - if cfg.base_fetch_sql: - test_sql = _build_fetch_sql(base, custom_where, custom_order_by) - else: - test_sql = base - from app.services.schedule import _build_srm_conn_str, _resolve_dify_agent, _resolve_schedule_user - from app.services.schedule.srm_service import _fetch_records, _run_check_job_loop, _build_record_text, _execute_writeback - if cfg.data_source and (not cfg.data_source.is_empty()): - conn_str = cfg.data_source.build_connection_string() - else: - conn_str = _build_srm_conn_str() - agent = _resolve_dify_agent(task) if task else None - user = _resolve_schedule_user(task) if task else 'test_user' - wait_seconds = task.wait_seconds if task else 120 - dify_agent_id = task.dify_agent_id if task else None - run = ScheduleRun(run_no=_generate_test_run_no(), schedule_task_id=task_id, trigger_type='test', triggered_by_user_id=getattr(get_current_user(), 'id', None), started_at=datetime.utcnow(), status='running') - db.session.add(run) - db.session.commit() - from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot - capture_dify_execution_snapshot(run, task) - db.session.commit() - if not cfg.fetch_sql: - run.status = 'success' - run.finished_at = datetime.utcnow() - run.error_message = '无抓取SQL,跳过外部系统数据抓取' - try: - if task.notify_enabled: - _notify_schedule_run_wecom(task, run) - except Exception as wecom_exc: - current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc) - db.session.commit() - return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': '', 'limit': 0, 'total_count': 0, 'success_count': 0, 'failed_count': 0, 'skipped_count': 0, 'details': [], 'errors': [], 'step_logs': [{'step': 'no_fetch_sql', 'status': 'skipped', 'detail': '无抓取SQL,跳过外部系统数据抓取'}], 'dify_agent_id': dify_agent_id}) - - def _test_fetch_fn(conn_str_arg): - return _fetch_records(conn_str_arg, test_sql) - - def _test_writeback_fn(conn_str_arg, *, row_id, run_no, dify_result, dify_message): - _execute_writeback(conn_str_arg, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id))) - test_pre_dify = None - test_build_record = None - if cfg.detail_sql: - - def _test_pre_dify(conn_str_arg, item, row_id_value): - try: - detail_rows = _fetch_records(conn_str_arg, cfg.detail_sql, params=(str(row_id_value),)) - except Exception as detail_exc: - return {'dify_result': '人工判定', 'dify_message': f'查询成分明细失败:{detail_exc}', 'writeback_srm': False, 'writeback_err': str(detail_exc)} - detail_lines = [] - for dr in detail_rows: - parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order] - detail_lines.append(', '.join(parts)) - item['detail_text'] = '; '.join(detail_lines) if detail_lines else '' - item['_detail_rows'] = detail_rows - return None - test_pre_dify = _test_pre_dify - - def _test_build_with_detail(conn_str_arg, item, row_id_value): - detail_rows = item.get('_detail_rows', []) - text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order) - return (text, item.get('attachment')) - test_build_record = _test_build_with_detail - else: - - def _test_build_simple(conn_str_arg, item, row_id_value): - text = _build_record_text(item, cfg.alias_order, cfg.header_labels) - return (text, item.get('attachment')) - test_build_record = _test_build_simple - start_ts = _time.time() - try: - total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop(conn_str=conn_str, run_no=run.run_no, agent=agent, user=user, wait_seconds=wait_seconds, run_id=run.id, fetch_fn=_test_fetch_fn, build_record_fn=test_build_record, writeback_fn=_test_writeback_fn, writeback_sql=cfg.writeback_sql, row_id_key=cfg.row_id_key, log_prefix=cfg.log_prefix, fetch_sql=test_sql, max_rows=limit, pre_dify_fn=test_pre_dify, dify_system_prompt=cfg.dify_system_prompt) - duration_ms = int((_time.time() - start_ts) * 1000) - if total_count == 0 and (not errors): - status = 'success' - elif failed_count == 0: - status = 'success' - elif success_count == 0: - status = 'failed' - else: - status = 'partial_failed' - header_order = cfg.alias_order if cfg.alias_order else None - header_labels = cfg.header_labels if cfg.header_labels else None - detail_alias_order = cfg.detail_alias_order or [] - try: - file_data, file_name, file_size = export_schedule_result_excel(run_no=run.run_no, summary={'status': status, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'duration_ms': duration_ms}, details=details, header_order=header_order, header_labels=header_labels, detail_alias_order=detail_alias_order) - except Exception as excel_exc: - current_app.logger.error('[schedule-test-run] excel export failed: %s', excel_exc, exc_info=True) - file_data, file_name, file_size = (None, None, 0) - run.finished_at = datetime.utcnow() - run.duration_ms = duration_ms - run.status = status - run.total_count = total_count - run.success_count = success_count - run.failed_count = failed_count - run.skipped_count = skipped_count - run.step_logs = step_logs if step_logs else None - run.error_message = '; '.join(errors[:3]) if errors else None - run.excel_file_data = file_data - run.excel_file_name = file_name - run.excel_file_size = file_size or 0 - db.session.commit() - if test_kb_sync_enabled: - try: - from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb - - db.session.refresh(task) - db.session.refresh(run) - sync_schedule_run_excel_to_kb(task, run, enabled=True, process_inline=True) - db.session.refresh(run) - except Exception as kb_exc: - db.session.rollback() - db.session.refresh(run) - current_app.logger.error('[schedule-test-run] kb sync failed: %s', kb_exc, exc_info=True) - run.kb_sync_status = 'failed' - run.kb_group_id = getattr(task, 'kb_group_id', None) - run.kb_sync_error = str(kb_exc) - db.session.commit() - try: - if task.notify_enabled: - _notify_schedule_run_wecom(task, run) - except Exception as wecom_exc: - current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc) - import decimal, datetime as dt - - def _safe(v): - if isinstance(v, decimal.Decimal): - return float(v) - if isinstance(v, (dt.date, dt.datetime)): - return v.isoformat() - if isinstance(v, dt.timedelta): - return str(v) - return v - safe_details = [] - for item in details: - safe_item = {k: _safe(v) for k, v in item.items()} - safe_details.append(safe_item) - return jsonify({'run_no': run.run_no, 'run_id': run.id, 'sql': test_sql, 'limit': limit, 'total_count': total_count, 'success_count': success_count, 'failed_count': failed_count, 'skipped_count': skipped_count, 'details': safe_details, 'errors': errors, 'step_logs': step_logs, 'dify_agent_id': dify_agent_id, 'dify_execution_snapshot': run.dify_execution_snapshot, 'kb_sync_status': run.kb_sync_status, 'kb_sync_error': run.kb_sync_error, 'kb_document_id': run.kb_document_id}) - except Exception as e: - db.session.rollback() - run = db.session.get(ScheduleRun, run.id) - duration_ms = int((_time.time() - start_ts) * 1000) - run.finished_at = datetime.utcnow() - run.duration_ms = duration_ms - run.status = 'failed' - run.error_message = str(e) - db.session.commit() - import traceback - raise AppError(code='SYSTEM.HTTP_ERROR', message=str(e), http_status=400, details={'sql': test_sql, 'traceback': traceback.format_exc()}) - -@schedule_admin_bp.route('/schedules', methods=['GET']) -@require_admin -def get_schedules(): - return jsonify(list_tasks()) - -@schedule_admin_bp.route('/schedules//export', methods=['GET']) -@require_admin -def export_schedule(task_id: int): - task = db.session.get(ScheduleTask, task_id) - if not task: - raise NotFoundError('Not found') - cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first() - payload = {'schema_version': 1, 'exported_at': datetime.utcnow().isoformat(), 'schedules': [_serialize_task_for_export(task, cfg_model)]} - body = json.dumps(payload, ensure_ascii=False, indent=2) - filename = f"{task.schedule_no or f'schedule_{task.id}'}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json" - return Response(body, mimetype='application/json; charset=utf-8', headers={'Content-Disposition': f'attachment; filename="{filename}"'}) - -@schedule_admin_bp.route('/schedules/import', methods=['POST']) -@require_admin -def import_schedules(): - data = request.get_json(silent=True) or {} - schedules = data.get('schedules') - if not isinstance(schedules, list): - raise ValidationError('Invalid import file: schedules missing') - user = get_current_user() - imported = 0 - skipped = 0 - errors: list[str] = [] - for item in schedules: - if not isinstance(item, dict): - skipped += 1 - continue - try: - name = str(item.get('name') or '').strip() - cron_expr = str(item.get('cron_expr') or '').strip() - owner_user_id = int(item.get('owner_user_id')) - if not name or not cron_expr: - raise ValueError('name or cron_expr missing') - existing = None - schedule_no = str(item.get('schedule_no') or '').strip() - if schedule_no: - existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first() - task_payload = {'name': name, 'schedule_type': str(item.get('schedule_type') or 'platform_app'), 'owner_user_id': owner_user_id, 'cron_expr': cron_expr, 'schedule_timezone': item.get('schedule_timezone'), 'wait_seconds': int(item.get('wait_seconds') or 0), 'dify_agent_id': item.get('dify_agent_id'), 'platform_api_path': item.get('platform_api_path'), 'notify_user_ids_json': item.get('notify_user_ids_json') if isinstance(item.get('notify_user_ids_json'), list) else [], 'notify_enabled': bool(item.get('notify_enabled', True)), 'enabled': bool(item.get('enabled', True)), 'data_source_type': str(item.get('data_source_type') or 'database'), 'kb_sync_enabled': bool(item.get('kb_sync_enabled', False)), 'kb_group_id': item.get('kb_group_id')} - cfg = item.get('config') if isinstance(item.get('config'), dict) else None - if existing: - update_task(existing, payload=task_payload, actor_id=getattr(user, 'id', None)) - existing.data_source_type = task_payload['data_source_type'] - if cfg: - upsert_schedule_task_config(existing.id, cfg) - else: - task = create_task(name=name, schedule_type=task_payload['schedule_type'], owner_user_id=owner_user_id, cron_expr=cron_expr, schedule_timezone=task_payload['schedule_timezone'], wait_seconds=task_payload['wait_seconds'], dify_agent_id=task_payload['dify_agent_id'], platform_api_path=task_payload['platform_api_path'], notify_user_ids_json=task_payload['notify_user_ids_json'], notify_enabled=task_payload['notify_enabled'], enabled=task_payload['enabled'], actor_id=getattr(user, 'id', None)) - task.data_source_type = task_payload['data_source_type'] - task.kb_sync_enabled = task_payload['kb_sync_enabled'] - task.kb_group_id = int(task_payload['kb_group_id']) if task_payload.get('kb_group_id') not in (None, '', 0, '0') else None - db.session.commit() - if cfg: - upsert_schedule_task_config(task.id, cfg) - imported += 1 - except Exception as exc: - errors.append(str(exc)) - skipped += 1 - db.session.commit() - return jsonify({'ok': True, 'imported': imported, 'skipped': skipped, 'errors': errors[:20]}) - -@schedule_admin_bp.route('/schedules', methods=['POST']) -@require_admin -def post_schedule(): - data = request.get_json(silent=True) or {} - user = get_current_user() - data_source_type = str(data.get('data_source_type') or 'database') - task = create_task(name=str(data.get('name') or '').strip(), schedule_type='platform_app', owner_user_id=int(data.get('owner_user_id')), cron_expr=str(data.get('cron_expr') or '').strip(), schedule_timezone=data.get('schedule_timezone'), wait_seconds=int(data.get('wait_seconds') or 0), dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None, platform_api_path=str(data.get('platform_api_path') or '').strip() or None, notify_user_ids_json=data.get('notify_user_ids_json') if isinstance(data.get('notify_user_ids_json'), list) else [], notify_enabled=bool(data.get('notify_enabled', True)), enabled=bool(data.get('enabled', True)), actor_id=getattr(user, 'id', None)) - task.data_source_type = data_source_type - task.kb_sync_enabled = bool(data.get('kb_sync_enabled', False)) - raw_kb_group_id = data.get('kb_group_id') - task.kb_group_id = int(raw_kb_group_id) if raw_kb_group_id not in (None, '', 0, '0') else None - if data_source_type == 'faq_hot_aggregate': - task.platform_api_path = 'faq-aggregate-hot' - else: - task.platform_api_path = f'/{task.id}' - db.session.commit() - db.session.refresh(task) - config_data = data.get('config') - if config_data and data_source_type != 'faq_hot_aggregate': - upsert_schedule_task_config(task.id, config_data) - if not task.dify_agent_id: - cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first() - if cfg_model and cfg_model.dify_system_prompt: - cfg_model.dify_system_prompt = None - db.session.commit() - return (jsonify(serialize_task(task)), 201) - -@schedule_admin_bp.route('/schedules/', methods=['GET']) -@require_admin -def get_schedule(task_id: int): - task = db.session.get(ScheduleTask, task_id) - if not task: - raise NotFoundError('Not found') - return jsonify(serialize_task(task)) - -@schedule_admin_bp.route('/schedules/', methods=['PATCH']) -@require_admin -def patch_schedule(task_id: int): - task = db.session.get(ScheduleTask, task_id) - if not task: - raise NotFoundError('Not found') - data = request.get_json(silent=True) or {} - user = get_current_user() - if 'data_source_type' in data: - task.data_source_type = str(data['data_source_type']) - db.session.commit() - config_data = data.get('config') - if config_data: - upsert_schedule_task_config(task_id, config_data) - task = update_task(task, payload=data, actor_id=getattr(user, 'id', None)) - if not task.dify_agent_id: - cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first() - if cfg_model and cfg_model.dify_system_prompt: - cfg_model.dify_system_prompt = None - db.session.commit() - return jsonify(serialize_task(task)) - -@schedule_admin_bp.route('/schedules/', methods=['DELETE']) -@require_admin -def delete_schedule(task_id: int): - task = db.session.get(ScheduleTask, task_id) - if not task: - raise NotFoundError('Not found') - from app.services.schedule.scheduler_service import request_cancel_run - running_runs = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status == 'running').all() - for rr in running_runs: - request_cancel_run(rr.id) - rr.status = 'failed' - rr.error_message = '排程已被删除,执行中断' - rr.finished_at = datetime.utcnow() - if running_runs: - db.session.commit() - db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False) - db.session.delete(task) - db.session.commit() - return jsonify({'ok': True}) - -@schedule_admin_bp.route('/schedules//enable', methods=['POST']) -@require_admin -def enable_schedule(task_id: int): - task = db.session.get(ScheduleTask, task_id) - if not task: - raise NotFoundError('Not found') - from app.services.schedule.cron_util import normalize_cron_expr - from app.services.schedule.query_service import serialize_task - from app.services.schedule.timezone_util import compute_next_run_at - - from app.services.schedule.timezone_util import normalize_schedule_timezone - - task.enabled = True - if task.cron_expr: - task.cron_expr = normalize_cron_expr(task.cron_expr) - task.schedule_timezone = normalize_schedule_timezone(getattr(task, 'schedule_timezone', None)) - task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone) - db.session.commit() - return jsonify(serialize_task(task)) - -@schedule_admin_bp.route('/schedules//disable', methods=['POST']) -@require_admin -def disable_schedule(task_id: int): - task = db.session.get(ScheduleTask, task_id) - if not task: - raise NotFoundError('Not found') - task.enabled = False - task.next_run_at = None - db.session.commit() - return jsonify({'ok': True}) - -@schedule_admin_bp.route('/schedules//run', methods=['POST']) -@require_admin -def run_schedule(task_id: int): - task = db.session.get(ScheduleTask, task_id) - if not task: - raise NotFoundError('Not found') - user = get_current_user() - existing = db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task.id, ScheduleRun.status == 'running').first() - if existing: - raise ConflictError('该排程正在执行中,请等待完成后再试', details={'run_id': existing.id}) - run = ScheduleRun(run_no=_generate_run_no(), schedule_task_id=task.id, trigger_type='manual', triggered_by_user_id=getattr(user, 'id', None), started_at=datetime.utcnow(), status='running') - db.session.add(run) - db.session.commit() - app = current_app._get_current_object() - run_id = run.id - - def _background(): - with app.app_context(): - t = db.session.get(ScheduleTask, task_id) - r = db.session.get(ScheduleRun, run_id) - if not t or not r: - return - try: - run_task_now(t, trigger_type='manual', triggered_by_user_id=r.triggered_by_user_id, run=r) - except Exception as exc: - try: - r = db.session.get(ScheduleRun, run_id) - if r and r.status == 'running': - r.status = 'failed' - r.error_message = str(exc) - r.finished_at = datetime.utcnow() - db.session.commit() - except Exception: - db.session.rollback() - current_app.logger.error('[schedule-run] run_id=%s failed: %s', run_id, exc, exc_info=True) - t = threading.Thread(target=_background, daemon=True, name=f'schedule-run-{run_id}') - t.start() - fresh = db.session.get(ScheduleRun, run_id) - return jsonify(serialize_run(fresh)) - -@schedule_admin_bp.route('/schedules//runs', methods=['GET']) -@require_admin -def get_schedule_runs(task_id: int): - status = str(request.args.get('status') or '').strip() or None - limit = int(request.args.get('limit') or 100) - started_after = None - started_before = None - sa = request.args.get('started_after') - sb = request.args.get('started_before') - if sa: - try: - started_after = datetime.fromisoformat(sa.replace('Z', '+00:00')) - except (ValueError, TypeError): - pass - if sb: - try: - started_before = datetime.fromisoformat(sb.replace('Z', '+00:00')) - except (ValueError, TypeError): - pass - return jsonify(list_runs(task_id=task_id, status=status, started_after=started_after, started_before=started_before, limit=limit)) - -@schedule_admin_bp.route('/schedule-runs/', methods=['GET']) -@require_admin -def get_schedule_run(run_id: int): - run = get_run(run_id) - if not run: - raise NotFoundError('Not found') - return jsonify(serialize_run(run)) - -@schedule_admin_bp.route('/schedule-runs//excel', methods=['GET']) -@require_admin -def get_schedule_run_excel(run_id: int): - from io import BytesIO - run = get_run(run_id) - if not run: - raise NotFoundError('Not found') - if not run.excel_file_data: - raise NotFoundError('Excel not found') - buf = BytesIO(run.excel_file_data) - return send_file(buf, as_attachment=True, download_name=run.excel_file_name or 'result.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') diff --git a/backend/app/api/schedule/blueprint.py b/backend/app/api/schedule/blueprint.py new file mode 100644 index 00000000..266e5b79 --- /dev/null +++ b/backend/app/api/schedule/blueprint.py @@ -0,0 +1,10 @@ +""" +backend/app/api/schedule/blueprint.py + +用途:排程管理 API 共享 Blueprint(Wave 3 分包后各子模块共用)。 +依赖:Flask Blueprint。 +逻辑:config/tasks/runs 子模块在此 bp 上注册路由;__init__ 导出 schedule_admin_bp。 +""" +from flask import Blueprint + +schedule_admin_bp = Blueprint('schedule_admin', __name__) diff --git a/backend/app/api/schedule/common.py b/backend/app/api/schedule/common.py new file mode 100644 index 00000000..32b39d3f --- /dev/null +++ b/backend/app/api/schedule/common.py @@ -0,0 +1,59 @@ +""" +backend/app/api/schedule/common.py + +用途:排程 API 共享序列化 helper。 +依赖:models、services/schedule/query_service。 +逻辑:config/tasks 子模块导出任务配置 JSON 时共用。 +""" +from __future__ import annotations + +from app.models import ScheduleTask, ScheduleTaskConfig +from app.services.schedule.query_service import serialize_task +from app.services.schedule.serialization import safe_json_value + + +def serialize_task_config(cfg_model: ScheduleTaskConfig) -> dict: + """ + 将 ScheduleTaskConfig ORM 转为 API 响应 dict。 + 核心逻辑:扁平化 data_source / external_api 嵌套结构。 + """ + return { + 'row_id_key': cfg_model.row_id_key or 'id', + 'log_prefix': cfg_model.log_prefix or '', + 'base_fetch_sql': cfg_model.base_fetch_sql or '', + 'fetch_where_conditions': cfg_model.fetch_where_conditions or '', + 'fetch_order_by': cfg_model.fetch_order_by or '', + 'writeback_sql': cfg_model.writeback_sql or '', + 'detail_sql': cfg_model.detail_sql or '', + 'alias_order': cfg_model.alias_order or [], + 'detail_alias_order': cfg_model.detail_alias_order or [], + 'header_labels': cfg_model.header_labels or {}, + 'data_source': { + 'db_type': cfg_model.ds_db_type or 'sqlserver', + 'host': cfg_model.ds_host or '', + 'port': cfg_model.ds_port or '', + 'database': cfg_model.ds_database or '', + 'username': cfg_model.ds_username or '', + 'password': cfg_model.ds_password or '', + 'driver': cfg_model.ds_driver or '', + 'encrypt': cfg_model.ds_encrypt or '', + 'trust_cert': cfg_model.ds_trust_cert or '', + }, + 'external_api': { + 'url': cfg_model.api_url or '', + 'method': cfg_model.api_method or 'POST', + 'headers': cfg_model.api_headers or {}, + 'body_template': cfg_model.api_body_template or '', + }, + 'dify_system_prompt': cfg_model.dify_system_prompt or '', + } + + +def serialize_task_for_export(task: ScheduleTask, cfg_model: ScheduleTaskConfig | None) -> dict: + """组装单条排程导出 JSON(含 config 快照)。""" + payload = serialize_task(task) + payload['config'] = serialize_task_config(cfg_model) if cfg_model else None + return payload + + +__all__ = ['safe_json_value', 'serialize_task_config', 'serialize_task_for_export'] diff --git a/backend/app/api/schedule/config.py b/backend/app/api/schedule/config.py new file mode 100644 index 00000000..5c5fcd63 --- /dev/null +++ b/backend/app/api/schedule/config.py @@ -0,0 +1,79 @@ +""" +backend/app/api/schedule/config.py + +用途:排程任务 SQL/数据源配置 API 与测试接口(薄路由层)。 +依赖:schedule.blueprint、schedule.common、services/schedule/*。 +逻辑:/schedule-config/* 路由。 +""" +from __future__ import annotations + +from flask import jsonify, request + +from app import db +from app.api.schedule.blueprint import schedule_admin_bp +from app.api.schedule.common import serialize_task_config +from app.core.auth.jwt import get_current_user +from app.core.decorators import require_admin +from app.core.errors import NotFoundError, ValidationError +from app.models import ScheduleTask, ScheduleTaskConfig +from app.services.schedule.sql_config import upsert_schedule_task_config +from app.services.schedule.sql_preview_service import preview_fetch_sql +from app.services.schedule.test_run_service import execute_test_run + + +@schedule_admin_bp.route('/schedule-config/', methods=['GET']) +@require_admin +def get_schedule_task_config(task_id: int): + """返回排程任务关联的 SQL/数据源配置。""" + task = db.session.get(ScheduleTask, task_id) + if not task: + raise NotFoundError('Not found') + cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first() + if not cfg_model: + return jsonify({'data_source_type': task.data_source_type, 'config': None}) + return jsonify({'data_source_type': task.data_source_type, 'config': serialize_task_config(cfg_model)}) + + +@schedule_admin_bp.route('/schedule-config/', methods=['PUT']) +@require_admin +def update_schedule_task_config(task_id: int): + """更新排程 data_source_type 与 ScheduleTaskConfig。""" + task = db.session.get(ScheduleTask, task_id) + if not task: + raise NotFoundError('Not found') + data = request.get_json(silent=True) or {} + try: + if 'data_source_type' in data: + task.data_source_type = str(data['data_source_type']) + db.session.commit() + config_data = data.get('config', data) + upsert_schedule_task_config(task_id, config_data) + cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first() + return jsonify({ + 'data_source_type': task.data_source_type, + 'config': serialize_task_config(cfg_model) if cfg_model else None, + }) + except Exception as exc: + db.session.rollback() + raise ValidationError(str(exc)) + + +@schedule_admin_bp.route('/schedule-config//test-sql', methods=['POST']) +@require_admin +def test_schedule_sql(task_id: int): + """预览抓取 SQL 执行结果(最多 100 行)。""" + data = request.get_json(silent=True) or {} + return jsonify(preview_fetch_sql(task_id, data)) + + +@schedule_admin_bp.route('/schedule-config//test-run', methods=['POST']) +@require_admin +def test_schedule_run(task_id: int): + """同步执行小规模排程测试跑(默认 3 条),可选 KB 同步。""" + data = request.get_json(silent=True) or {} + payload = execute_test_run( + task_id, + data, + triggered_by_user_id=getattr(get_current_user(), 'id', None), + ) + return jsonify(payload) diff --git a/backend/app/api/schedule/runs.py b/backend/app/api/schedule/runs.py new file mode 100644 index 00000000..a22eed32 --- /dev/null +++ b/backend/app/api/schedule/runs.py @@ -0,0 +1,139 @@ +""" +backend/app/api/schedule/runs.py + +用途:排程运行触发与运行记录查询 API。 +依赖:schedule.blueprint、services/schedule/query_service、scheduler_service。 +逻辑:/schedules//run、/schedules//runs、/schedule-runs/* 路由。 +""" +from __future__ import annotations + +import threading +from datetime import datetime +from io import BytesIO + +from flask import current_app, jsonify, request, send_file + +from app import db +from app.api.schedule.blueprint import schedule_admin_bp +from app.core.auth.jwt import get_current_user +from app.core.decorators import require_admin +from app.core.errors import ConflictError, NotFoundError +from app.models import ScheduleRun, ScheduleTask +from app.services.schedule.query_service import get_run, list_runs, serialize_run +from app.services.schedule.scheduler_service import _generate_run_no, run_task_now + + +@schedule_admin_bp.route('/schedules//run', methods=['POST']) +@require_admin +def run_schedule(task_id: int): + """ + 手动触发排程后台执行。 + 核心逻辑:创建 running ScheduleRun → 守护线程内 run_task_now。 + """ + task = db.session.get(ScheduleTask, task_id) + if not task: + raise NotFoundError('Not found') + user = get_current_user() + existing = ( + db.session.query(ScheduleRun) + .filter(ScheduleRun.schedule_task_id == task.id, ScheduleRun.status == 'running') + .first() + ) + if existing: + raise ConflictError('该排程正在执行中,请等待完成后再试', details={'run_id': existing.id}) + run = ScheduleRun( + run_no=_generate_run_no(), + schedule_task_id=task.id, + trigger_type='manual', + triggered_by_user_id=getattr(user, 'id', None), + started_at=datetime.utcnow(), + status='running', + ) + db.session.add(run) + db.session.commit() + app = current_app._get_current_object() + run_id = run.id + + def _background(): + with app.app_context(): + t = db.session.get(ScheduleTask, task_id) + r = db.session.get(ScheduleRun, run_id) + if not t or not r: + return + try: + run_task_now(t, trigger_type='manual', triggered_by_user_id=r.triggered_by_user_id, run=r) + except Exception as exc: + try: + r = db.session.get(ScheduleRun, run_id) + if r and r.status == 'running': + r.status = 'failed' + r.error_message = str(exc) + r.finished_at = datetime.utcnow() + db.session.commit() + except Exception: + db.session.rollback() + current_app.logger.error('[schedule-run] run_id=%s failed: %s', run_id, exc, exc_info=True) + + t = threading.Thread(target=_background, daemon=True, name=f'schedule-run-{run_id}') + t.start() + fresh = db.session.get(ScheduleRun, run_id) + return jsonify(serialize_run(fresh)) + + +@schedule_admin_bp.route('/schedules//runs', methods=['GET']) +@require_admin +def get_schedule_runs(task_id: int): + """按任务 ID 分页/过滤返回运行记录。""" + status = str(request.args.get('status') or '').strip() or None + limit = int(request.args.get('limit') or 100) + started_after = None + started_before = None + sa = request.args.get('started_after') + sb = request.args.get('started_before') + if sa: + try: + started_after = datetime.fromisoformat(sa.replace('Z', '+00:00')) + except (ValueError, TypeError): + pass + if sb: + try: + started_before = datetime.fromisoformat(sb.replace('Z', '+00:00')) + except (ValueError, TypeError): + pass + return jsonify( + list_runs( + task_id=task_id, + status=status, + started_after=started_after, + started_before=started_before, + limit=limit, + ) + ) + + +@schedule_admin_bp.route('/schedule-runs/', methods=['GET']) +@require_admin +def get_schedule_run(run_id: int): + """返回单条运行记录详情。""" + run = get_run(run_id) + if not run: + raise NotFoundError('Not found') + return jsonify(serialize_run(run)) + + +@schedule_admin_bp.route('/schedule-runs//excel', methods=['GET']) +@require_admin +def get_schedule_run_excel(run_id: int): + """下载运行结果 Excel 附件。""" + run = get_run(run_id) + if not run: + raise NotFoundError('Not found') + if not run.excel_file_data: + raise NotFoundError('Excel not found') + buf = BytesIO(run.excel_file_data) + return send_file( + buf, + as_attachment=True, + download_name=run.excel_file_name or 'result.xlsx', + mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + ) diff --git a/backend/app/api/schedule/tasks.py b/backend/app/api/schedule/tasks.py new file mode 100644 index 00000000..725f4c4e --- /dev/null +++ b/backend/app/api/schedule/tasks.py @@ -0,0 +1,204 @@ +""" +backend/app/api/schedule/tasks.py + +用途:排程任务 CRUD、导入导出、启用/禁用 API。 +依赖:schedule.blueprint、schedule.common、services/schedule/*。 +逻辑:/schedules* 路由(不含 run 触发与运行记录)。 +""" +from __future__ import annotations + +import json +from datetime import datetime + +from flask import Response, jsonify, request + +from app import db +from app.api.schedule.blueprint import schedule_admin_bp +from app.api.schedule.common import serialize_task_for_export +from app.core.auth.jwt import get_current_user +from app.core.decorators import require_admin +from app.core.errors import NotFoundError +from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig +from app.services.schedule.query_service import list_tasks, serialize_task +from app.services.schedule.import_service import import_schedules_from_payload +from app.services.schedule.scheduler_service import create_task, update_task +from app.services.schedule.sql_config import upsert_schedule_task_config + + +@schedule_admin_bp.route('/schedules', methods=['GET']) +@require_admin +def get_schedules(): + """返回全部排程任务列表。""" + return jsonify(list_tasks()) + + +@schedule_admin_bp.route('/schedules//export', methods=['GET']) +@require_admin +def export_schedule(task_id: int): + """导出单条排程任务及配置为 JSON 文件。""" + task = db.session.get(ScheduleTask, task_id) + if not task: + raise NotFoundError('Not found') + cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first() + payload = { + 'schema_version': 1, + 'exported_at': datetime.utcnow().isoformat(), + 'schedules': [serialize_task_for_export(task, cfg_model)], + } + body = json.dumps(payload, ensure_ascii=False, indent=2) + filename = f"{task.schedule_no or f'schedule_{task.id}'}_export_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json" + return Response( + body, + mimetype='application/json; charset=utf-8', + headers={'Content-Disposition': f'attachment; filename="{filename}"'}, + ) + + +@schedule_admin_bp.route('/schedules/import', methods=['POST']) +@require_admin +def import_schedules(): + """批量导入排程 JSON(按 schedule_no upsert)。""" + data = request.get_json(silent=True) or {} + user = get_current_user() + result = import_schedules_from_payload( + data.get('schedules'), + actor_id=getattr(user, 'id', None), + ) + return jsonify(result) + + +@schedule_admin_bp.route('/schedules', methods=['POST']) +@require_admin +def post_schedule(): + """创建排程任务。""" + data = request.get_json(silent=True) or {} + user = get_current_user() + data_source_type = str(data.get('data_source_type') or 'database') + task = create_task( + name=str(data.get('name') or '').strip(), + schedule_type='platform_app', + owner_user_id=int(data.get('owner_user_id')), + cron_expr=str(data.get('cron_expr') or '').strip(), + schedule_timezone=data.get('schedule_timezone'), + wait_seconds=int(data.get('wait_seconds') or 0), + dify_agent_id=int(data.get('dify_agent_id')) if data.get('dify_agent_id') is not None else None, + platform_api_path=str(data.get('platform_api_path') or '').strip() or None, + notify_user_ids_json=data.get('notify_user_ids_json') + if isinstance(data.get('notify_user_ids_json'), list) + else [], + notify_enabled=bool(data.get('notify_enabled', True)), + enabled=bool(data.get('enabled', True)), + actor_id=getattr(user, 'id', None), + ) + task.data_source_type = data_source_type + task.kb_sync_enabled = bool(data.get('kb_sync_enabled', False)) + raw_kb_group_id = data.get('kb_group_id') + task.kb_group_id = int(raw_kb_group_id) if raw_kb_group_id not in (None, '', 0, '0') else None + if data_source_type == 'faq_hot_aggregate': + task.platform_api_path = 'faq-aggregate-hot' + else: + task.platform_api_path = f'/{task.id}' + db.session.commit() + db.session.refresh(task) + config_data = data.get('config') + if config_data and data_source_type != 'faq_hot_aggregate': + upsert_schedule_task_config(task.id, config_data) + if not task.dify_agent_id: + cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task.id).first() + if cfg_model and cfg_model.dify_system_prompt: + cfg_model.dify_system_prompt = None + db.session.commit() + return jsonify(serialize_task(task)), 201 + + +@schedule_admin_bp.route('/schedules/', methods=['GET']) +@require_admin +def get_schedule(task_id: int): + """返回单条排程任务详情。""" + task = db.session.get(ScheduleTask, task_id) + if not task: + raise NotFoundError('Not found') + return jsonify(serialize_task(task)) + + +@schedule_admin_bp.route('/schedules/', methods=['PATCH']) +@require_admin +def patch_schedule(task_id: int): + """更新排程任务字段与关联配置。""" + task = db.session.get(ScheduleTask, task_id) + if not task: + raise NotFoundError('Not found') + data = request.get_json(silent=True) or {} + user = get_current_user() + if 'data_source_type' in data: + task.data_source_type = str(data['data_source_type']) + db.session.commit() + config_data = data.get('config') + if config_data: + upsert_schedule_task_config(task_id, config_data) + task = update_task(task, payload=data, actor_id=getattr(user, 'id', None)) + if not task.dify_agent_id: + cfg_model = ScheduleTaskConfig.query.filter_by(schedule_task_id=task_id).first() + if cfg_model and cfg_model.dify_system_prompt: + cfg_model.dify_system_prompt = None + db.session.commit() + return jsonify(serialize_task(task)) + + +@schedule_admin_bp.route('/schedules/', methods=['DELETE']) +@require_admin +def delete_schedule(task_id: int): + """删除排程任务及其运行记录;中断进行中的 run。""" + task = db.session.get(ScheduleTask, task_id) + if not task: + raise NotFoundError('Not found') + from app.services.schedule.scheduler_service import request_cancel_run + + running_runs = ( + db.session.query(ScheduleRun) + .filter(ScheduleRun.schedule_task_id == task_id, ScheduleRun.status == 'running') + .all() + ) + for rr in running_runs: + request_cancel_run(rr.id) + rr.status = 'failed' + rr.error_message = '排程已被删除,执行中断' + rr.finished_at = datetime.utcnow() + if running_runs: + db.session.commit() + db.session.query(ScheduleRun).filter(ScheduleRun.schedule_task_id == task_id).delete(synchronize_session=False) + db.session.delete(task) + db.session.commit() + return jsonify({'ok': True}) + + +@schedule_admin_bp.route('/schedules//enable', methods=['POST']) +@require_admin +def enable_schedule(task_id: int): + """启用排程并重新计算 next_run_at。""" + task = db.session.get(ScheduleTask, task_id) + if not task: + raise NotFoundError('Not found') + from app.services.schedule.cron_util import normalize_cron_expr + from app.services.schedule.timezone_util import compute_next_run_at, normalize_schedule_timezone + + task.enabled = True + if task.cron_expr: + task.cron_expr = normalize_cron_expr(task.cron_expr) + task.schedule_timezone = normalize_schedule_timezone(getattr(task, 'schedule_timezone', None)) + task.next_run_at = compute_next_run_at(task.cron_expr, timezone_name=task.schedule_timezone) + db.session.commit() + return jsonify(serialize_task(task)) + + +@schedule_admin_bp.route('/schedules//disable', methods=['POST']) +@require_admin +def disable_schedule(task_id: int): + """禁用排程并清空 next_run_at。""" + task = db.session.get(ScheduleTask, task_id) + if not task: + raise NotFoundError('Not found') + task.enabled = False + task.next_run_at = None + db.session.commit() + return jsonify({'ok': True}) diff --git a/backend/app/api/schedule_admin.py b/backend/app/api/schedule_admin.py index 919fa999..30cc296f 100644 --- a/backend/app/api/schedule_admin.py +++ b/backend/app/api/schedule_admin.py @@ -1,10 +1,10 @@ """ backend/app/api/schedule_admin.py -用途:排程 admin API 兼容 shim(Wave 3 迁包过渡期)。 -依赖:app.api.schedule._legacy。 -逻辑:旧 import 路径 `from app.api.schedule_admin import schedule_admin_bp` 仍可用;新代码请用 app.api.schedule。 +用途:排程 API 兼容 shim(Wave 3 迁包过渡期)。 +依赖:app.api.schedule。 +逻辑:旧 import 路径仍可用;新代码请用 app.api.schedule。 """ -from app.api.schedule._legacy import schedule_admin_bp +from app.api.schedule import schedule_admin_bp __all__ = ['schedule_admin_bp'] diff --git a/backend/app/api/user.py b/backend/app/api/user.py index b156d39f..4bdc598d 100644 --- a/backend/app/api/user.py +++ b/backend/app/api/user.py @@ -3,11 +3,11 @@ backend/app/api/user.py 用途:当前用户域 API(Casdoor 登录、企微 OAuth、首页、FAQ、反馈等)。 依赖:app.core.auth.jwt、app.core.errors、models、wecom/dify 相关 services。 -逻辑:薄路由层鉴权与参数校验;业务编排仍在本文件(Wave 3 拆至 api/user/* + services/user/*)。 +逻辑:薄路由层鉴权与参数校验;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, Announcement, LoginAudit, WecomCallbackAudit, GeneralFeedback, ChatLog +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.wecom_notify import mark_wecom_message_opened, send_wecom_event_message @@ -36,10 +36,12 @@ from app.core.errors import ( ValidationError, raise_for_status, ) +from app.services.auth import casdoor_service as _casdoor_svc +from app.services.auth import wecom_auth_service as _wecom_svc user_bp = Blueprint('user', __name__) -_WECOM_ACCESS_TOKEN_CACHE = {'token': None, 'expires_at': None} -_WECOM_STATE_CACHE = {} -_WECOM_BIND_SESSION_CACHE = {} +_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'} @@ -129,26 +131,11 @@ def _run_db_with_retry(operation, *, label: str): return operation() def _get_wecom_config_missing_fields() -> list[str]: - """ - 列出企微集成尚未配置的环境项。 - Returns: - 缺失的配置键名列表,如 WECOM_ENABLED、WECOM_CORP_ID 等。 - """ - missing: list[str] = [] - if not current_app.config.get('WECOM_ENABLED'): - missing.append('WECOM_ENABLED') - if not _clean_str(current_app.config.get('WECOM_CORP_ID')): - missing.append('WECOM_CORP_ID') - if not _clean_str(current_app.config.get('WECOM_AGENT_ID')): - missing.append('WECOM_AGENT_ID') - if not _clean_str(current_app.config.get('WECOM_SECRET')): - missing.append('WECOM_SECRET') - return missing + return _wecom_svc.get_config_missing_fields() def _is_wecom_configured() -> bool: - """企微 Corp/Agent/Secret 与总开关均已配置时返回 True。""" - return len(_get_wecom_config_missing_fields()) == 0 + return _wecom_svc.is_configured() def _issue_casdoor_state(redirect_uri: str): exp_ts = int((datetime.utcnow() + timedelta(minutes=10)).timestamp()) @@ -269,330 +256,58 @@ def _is_casdoor_login_mode() -> bool: return (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() == 'casdoor' def _is_casdoor_configured() -> bool: - if not _clean_str(current_app.config.get('CASDOOR_ORGANIZATION')): - return False - base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/') - client_id = current_app.config.get('CASDOOR_CLIENT_ID') or '' - client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or '' - return bool(base and client_id and client_secret) + return _casdoor_svc.is_casdoor_configured() def _casdoor_user_owner() -> str: - owner = _clean_str(current_app.config.get('CASDOOR_ORGANIZATION')) - if not owner: - raise RuntimeError('CASDOOR_ORGANIZATION is not configured') - return owner + 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): - base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/') - client_id = current_app.config.get('CASDOOR_CLIENT_ID') or '' - client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or '' - if not base or not client_id or not client_secret: - raise RuntimeError('Casdoor is not configured') - url = f'{base}/api/set-password' - resp = requests.post(url, files={'userOwner': (None, user_owner), 'userName': (None, user_name), 'oldPassword': (None, old_password), 'newPassword': (None, new_password)}, auth=(client_id, client_secret), timeout=8) - try: - data = resp.json() or {} - except ValueError: - raise RuntimeError(f'Casdoor set-password failed: HTTP {resp.status_code} {resp.text[:200]}') - if data.get('status') != 'ok': - _raise_casdoor_set_password_error(data) + return _casdoor_svc.casdoor_set_password(user_owner, user_name, old_password, new_password) def _is_casdoor_user_exists_error(message: str) -> bool: - lowered = (message or '').lower() - return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered + return _casdoor_svc.is_user_exists_error(message) def _raise_casdoor_add_user_error(source) -> None: - """ - 将 Casdoor add-user 失败映射为稳定业务错误码,供管理端创建用户时展示。 - @param source: Casdoor JSON 响应、RuntimeError 文本或其它异常来源 - Raises: - ConflictError: Casdoor 侧用户名/邮箱已存在 - AppError: 密码策略或 IdP 同步失败 - """ - data = _extract_casdoor_error_payload(source) - msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message')) - lowered = (msg_text or str(source or '')).lower() - if _is_casdoor_user_exists_error(lowered): - raise ConflictError('Username already exists in Casdoor', code='USER.USERNAME_EXISTS', details={'field': 'username', 'technical': msg_text}) - if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')): - raise AppError(code='CASDOOR_PASSWORD_POLICY', message='Password does not meet security requirements', http_status=400) - raise AppError(code='CASDOOR_ADD_USER_FAILED', message='Failed to create user in authentication system. Please try again or contact the administrator.', http_status=502, details={'technical': msg_text or str(source or '')[:300]}) - -def _build_casdoor_user_profile_payload(*, username: str, email: str, real_name=None, phone_number=None, status='active', department=None) -> dict: - """ - 组装 Casdoor 用户资料字段(create/update 共用),不含 password。 - @param username: Casdoor name(与本地 username 一致) - @param email: 邮箱 - @param real_name: 显示名/真实姓名 - @param phone_number: 手机号 - @param status: 本地账号状态;非 active 时 Casdoor 设为禁用 - @param department: 部门,映射至 affiliation - Returns: - Casdoor User JSON 对象(资料部分) - """ - display_name = _clean_str(real_name) or username - payload = { - 'owner': _casdoor_user_owner(), - 'name': username, - 'email': email or '', - 'displayName': display_name, - 'realName': _clean_str(real_name) or '', - 'phone': _clean_str(phone_number) or '', - 'isForbidden': _clean_str(status) not in (None, 'active'), - } - department_value = _clean_str(department) - if department_value: - payload['affiliation'] = department_value - return payload - -def _build_casdoor_user_payload(*, username: str, password: str, email: str, real_name=None, phone_number=None, status='active', department=None) -> dict: - """ - 组装 Casdoor add-user 请求体,字段与本地 User 模型对齐。 - @param username: Casdoor name(与本地 username 一致) - @param password: 初始明文密码 - @param email: 邮箱 - @param real_name: 显示名/真实姓名 - @param phone_number: 手机号 - @param status: 本地账号状态;非 active 时 Casdoor 设为禁用 - @param department: 部门,映射至 affiliation - Returns: - Casdoor User JSON 对象 - """ - payload = _build_casdoor_user_profile_payload( - username=username, - email=email, - real_name=real_name, - phone_number=phone_number, - status=status, - department=department, - ) - payload['password'] = password - return payload + _casdoor_svc.raise_add_user_error(source) def _casdoor_add_user(user_payload: dict): - """ - 调用 Casdoor /api/add-user 创建 IdP 用户。 - 核心逻辑:使用 Client ID/Secret Basic Auth,与 set-password 管理 API 一致。 - @param user_payload: Casdoor User 对象(owner/name/password 等) - Raises: - RuntimeError: HTTP 或配置异常 - AppError: Casdoor 返回业务错误(经 _raise_casdoor_add_user_error 映射) - """ - base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/') - client_id = current_app.config.get('CASDOOR_CLIENT_ID') or '' - client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or '' - if not base or not client_id or not client_secret: - raise RuntimeError('Casdoor is not configured') - url = f'{base}/api/add-user' - resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8) - try: - data = resp.json() or {} - except ValueError: - raise RuntimeError(f'Casdoor add-user failed: HTTP {resp.status_code} {resp.text[:200]}') - if data.get('status') != 'ok': - _raise_casdoor_add_user_error(data) + return _casdoor_svc.casdoor_add_user(user_payload) def _sync_casdoor_create_user(*, username: str, password: str, email: str, real_name=None, phone_number=None, status='active', department=None): - """ - 管理端创建用户时同步至 Casdoor,与改密逻辑一致:Casdoor 已配置则必须成功,否则跳过。 - 核心逻辑:构建 add-user payload → 调 _casdoor_add_user;本地库 commit 由调用方负责。 - @param username: 本地 username,同步为 Casdoor name - @param password: 初始明文密码 - @param email: 邮箱 - @param real_name: 真实姓名 - @param phone_number: 手机号 - @param status: 本地账号状态 - @param department: 部门 - Raises: - AppError / ConflictError: Casdoor 创建失败 - """ - if not _is_casdoor_configured(): - return - payload = _build_casdoor_user_payload( - username=username, - password=password, - email=email, - real_name=real_name, - phone_number=phone_number, - status=status, - department=department, - ) - _casdoor_add_user(payload) + return _casdoor_svc.sync_create_user(username=username, password=password, email=email, real_name=real_name, phone_number=phone_number, status=status, department=department) def _raise_casdoor_update_user_error(source) -> None: - """ - 将 Casdoor update-user 失败映射为稳定业务错误码,供管理端编辑用户时展示。 - @param source: Casdoor JSON 响应、RuntimeError 文本或其它异常来源 - Raises: - ConflictError: Casdoor 侧邮箱等唯一字段冲突 - AppError: IdP 同步失败 - """ - data = _extract_casdoor_error_payload(source) - msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message')) - lowered = (msg_text or str(source or '')).lower() - if _is_casdoor_user_missing_error(lowered): - _raise_casdoor_user_not_in_idp(source) - if _is_casdoor_user_exists_error(lowered) or ('email' in lowered and 'already' in lowered): - raise ConflictError('Email already exists in Casdoor', code='USER.EMAIL_EXISTS', details={'field': 'email', 'technical': msg_text}) - raise AppError(code='CASDOOR_UPDATE_USER_FAILED', message='Failed to update user in authentication system. Please try again or contact the administrator.', http_status=502, details={'technical': msg_text or str(source or '')[:300]}) + _casdoor_svc.raise_update_user_error(source) def _casdoor_update_user(user_payload: dict): - """ - 调用 Casdoor /api/update-user 更新 IdP 用户资料。 - 核心逻辑:使用 Client ID/Secret Basic Auth,与 add-user/set-password 管理 API 一致。 - @param user_payload: Casdoor User 对象(owner/name 及待更新字段) - Raises: - RuntimeError: HTTP 或配置异常 - AppError: Casdoor 返回业务错误(经 _raise_casdoor_update_user_error 映射) - """ - base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/') - client_id = current_app.config.get('CASDOOR_CLIENT_ID') or '' - client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or '' - if not base or not client_id or not client_secret: - raise RuntimeError('Casdoor is not configured') - url = f'{base}/api/update-user' - resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8) - try: - data = resp.json() or {} - except ValueError: - raise RuntimeError(f'Casdoor update-user failed: HTTP {resp.status_code} {resp.text[:200]}') - if data.get('status') != 'ok': - _raise_casdoor_update_user_error(data) + return _casdoor_svc.casdoor_update_user(user_payload) def _sync_casdoor_admin_set_password(user: User, new_password: str): - """ - 管理端重设密码时同步 Casdoor(无旧密码,与 token 重置一致)。 - IdP 用户不存在时抛出 CASDOOR_USER_NOT_IN_IDP,由上层决定是否 fallback add-user。 - @param user: 本地用户 - @param new_password: 新密码明文 - Raises: - AppError: Casdoor 策略或 IdP 同步失败 - """ - if not _is_casdoor_configured(): - return - user_owner = _casdoor_user_owner() - try: - _casdoor_set_password(user_owner, user.username, '', new_password) - except RuntimeError as exc: - if _is_casdoor_user_missing_error(str(exc)): - _raise_casdoor_user_not_in_idp(exc) - _raise_casdoor_set_password_error(exc) + return _casdoor_svc.sync_admin_set_password(user, new_password) def _sync_casdoor_update_user(user: User, *, new_password: str | None = None): - """ - 管理端编辑用户时同步 Casdoor:仅改密时 set-password;IdP 无账号则 add-user 补建。 - 核心逻辑:资料字段只写本地库,不调用 update-user;无新密码则跳过 Casdoor。 - @param user: 已应用本地变更但未 commit 的 User 实例 - @param new_password: 管理员设置的新密码;None 表示不改密 - Raises: - AppError / ConflictError: Casdoor 改密或补建失败 - """ - if not _is_casdoor_configured() or not new_password: - return - - def _provision_missing_user_in_casdoor(): - _sync_casdoor_create_user( - username=user.username, - password=new_password, - email=user.email, - real_name=user.real_name, - phone_number=user.phone_number, - status=user.status, - department=user.department, - ) - - try: - _sync_casdoor_admin_set_password(user, new_password) - except AppError as exc: - if exc.code == 'CASDOOR_USER_NOT_IN_IDP': - _provision_missing_user_in_casdoor() - return - raise + return _casdoor_svc.sync_update_user(user, new_password=new_password) def _is_casdoor_password_error(message: str) -> bool: - lowered = (message or '').lower() - return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered + return _casdoor_svc.is_password_error(message) def _is_casdoor_user_missing_error(message: str) -> bool: - lowered = (message or '').lower() - return ( - "doesn't exist" in lowered - or 'does not exist' in lowered - or 'user not found' in lowered - or 'no such user' in lowered - ) + return _casdoor_svc.is_user_missing_error(message) def _raise_casdoor_user_not_in_idp(source=None) -> None: - data = _extract_casdoor_error_payload(source) - msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message')) - raise AppError( - code='CASDOOR_USER_NOT_IN_IDP', - message='Your account has not been registered in the authentication system. Please contact the administrator.', - http_status=409, - details={'technical': msg_text or str(source or '')[:300]}, - ) + _casdoor_svc.raise_user_not_in_idp(source) def _extract_casdoor_error_payload(source) -> dict: - if isinstance(source, dict): - return source - text = str(source or '') - match = re.search(r'\{.*\}', text, re.DOTALL) - if match: - try: - parsed = ast.literal_eval(match.group(0)) - if isinstance(parsed, dict): - return parsed - except (SyntaxError, ValueError): - pass - try: - parsed = json.loads(text) - if isinstance(parsed, dict): - return parsed - except (json.JSONDecodeError, TypeError): - pass - return {} + return _casdoor_svc.extract_error_payload(source) def _raise_casdoor_auth_error(source, *, context: str, status_code: int = 401) -> None: - """ - Map Casdoor OAuth/API failures to stable business error codes for frontend i18n. - context: password | verify | code | refresh - """ - data = _extract_casdoor_error_payload(source) - raw = str(source or '') - oauth_error = _clean_str(data.get('error')).lower() - if not oauth_error and 'invalid_grant' in raw.lower(): - oauth_error = 'invalid_grant' - if not oauth_error and 'invalid_client' in raw.lower(): - oauth_error = 'invalid_client' - if oauth_error == 'invalid_grant' or _is_casdoor_password_error(raw): - if context in ('password', 'verify'): - raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401) - raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401) - if oauth_error in ('invalid_client', 'unauthorized_client'): - raise AppError(code='CASDOOR_CONFIG_ERROR', message='Authentication service is misconfigured. Please contact the administrator.', http_status=503, details={'casdoor_error': oauth_error}) - if oauth_error == 'access_denied': - raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403) - if 'token endpoint missing' in raw.lower() or 'casdoor_base_url is not configured' in raw.lower() or 'casdoor is not configured' in raw.lower(): - raise AppError(code='CASDOOR_CONFIG_ERROR', message='Authentication service is not configured. Please contact the administrator.', http_status=503) - if 'invalid or expired casdoor state' in raw.lower(): - raise ValidationError('Invalid or expired Casdoor state') - current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s raw=%s', context, data, raw[:500]) - raise AppError(code='CASDOOR_AUTH_FAILED', message='Authentication failed, please try again', http_status=status_code, details={'casdoor_error': oauth_error or None, 'technical': raw[:300]}) + _casdoor_svc.raise_auth_error(source, context=context, status_code=status_code) def _raise_casdoor_set_password_error(source) -> None: - data = _extract_casdoor_error_payload(source) - msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message')) - lowered = (msg_text or str(source or '')).lower() - if _is_casdoor_password_error(lowered) or 'old password' in lowered or 'current password' in lowered: - _raise_incorrect_current_password() - if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')): - raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400) - if _is_casdoor_user_missing_error(lowered): - _raise_casdoor_user_not_in_idp(source) - raise AppError(code='CASDOOR_SET_PASSWORD_FAILED', message='Failed to change password. Please try again or contact the administrator.', http_status=502, details={'technical': msg_text or str(source)[:300]}) + _casdoor_svc.raise_set_password_error(source) def _raise_incorrect_current_password(): raise AppError( @@ -690,17 +405,7 @@ def _consume_wecom_bind_session(token: str): return identity def _parse_wecom_field_list(raw_value, default_fields: list[str]): - if isinstance(raw_value, str): - pieces = [item.strip().lower() for item in raw_value.split(',')] - elif isinstance(raw_value, (list, tuple)): - pieces = [str(item).strip().lower() for item in raw_value] - else: - pieces = [] - result = [] - for piece in pieces: - if piece in _ALLOWED_WECOM_MATCH_FIELDS and piece not in result: - result.append(piece) - return result or list(default_fields) + 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): @@ -728,21 +433,7 @@ def _persist_wecom_callback_audit(*, msg_signature, timestamp, nonce, encrypt_ra db.session.rollback() def _get_wecom_access_token(): - now = datetime.utcnow() - token = _WECOM_ACCESS_TOKEN_CACHE.get('token') - expires_at = _WECOM_ACCESS_TOKEN_CACHE.get('expires_at') - if token and expires_at and (now < expires_at): - return token - corp_id = current_app.config.get('WECOM_CORP_ID') - secret = current_app.config.get('WECOM_SECRET') - token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken' - resp = requests.get(token_url, params={'corpid': corp_id, 'corpsecret': secret}, timeout=8) - data = resp.json() - if data.get('errcode') != 0 or not data.get('access_token'): - raise RuntimeError(f'Failed to fetch WeCom token: {data}') - _WECOM_ACCESS_TOKEN_CACHE['token'] = data['access_token'] - _WECOM_ACCESS_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60)) - return data['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, 'source': source, 'access_token': issue_local_access_token(user), 'token_type': 'Bearer'} @@ -796,39 +487,16 @@ def _extract_wecom_extattr_value(wecom_user: dict, key: str): return None def _get_wecom_match_config(): - raw_rules = current_app.config.get('WECOM_MATCH_RULES', 'employee_id,mobile') - rules = _parse_wecom_field_list(raw_rules, ['employee_id', 'mobile']) - operator = str(current_app.config.get('WECOM_MATCH_OPERATOR', 'AND')).upper() - if operator not in {'AND', 'OR'}: - operator = 'AND' - return (rules, operator) + return _wecom_svc.get_match_config() def _get_wecom_first_login_bind_mode(): - mode = _clean_str(current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE')) or 'match_rules' - mode = mode.lower() - if mode not in {'match_rules', 'input_verify'}: - mode = 'match_rules' - return mode + return _wecom_svc.get_first_login_bind_mode() def _get_wecom_first_login_input_fields(): - raw_fields = current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS', 'employee_id,mobile,email') - return _parse_wecom_field_list(raw_fields, ['employee_id', 'mobile', 'email']) + return _wecom_svc.get_first_login_input_fields() def _extract_wecom_identity(wecom_user: dict): - userid = _clean_str(wecom_user.get('userid')) - unionid = _clean_str(wecom_user.get('unionid')) - email = _clean_str(wecom_user.get('email')) - mobile_raw = _clean_str(wecom_user.get('mobile')) - normalize_mobile = bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True)) - mobile = _normalize_mobile(mobile_raw) if normalize_mobile else mobile_raw - employee_id_source = _clean_str(current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE')) or 'userid' - if employee_id_source == 'userid': - employee_id = userid - elif employee_id_source.startswith('extattr:'): - employee_id = _extract_wecom_extattr_value(wecom_user, employee_id_source.split(':', 1)[1]) - else: - employee_id = _clean_str(wecom_user.get(employee_id_source)) - return {'wecom_userid': userid, 'wecom_unionid': unionid, 'name': _clean_str(wecom_user.get('name')) or userid or 'wecom_user', 'email': email, 'mobile': mobile, 'mobile_raw': mobile_raw, 'employee_id': employee_id} + return _wecom_svc.extract_identity(wecom_user) def _mobile_candidates(identity: dict): values = [] @@ -866,34 +534,7 @@ def _find_users_by_input_field(field: str, value): return ([], 'invalid_field') def _find_users_by_match_rules(identity: dict, rules: list, operator: str): - filters = [] - missing = [] - for rule in rules: - if rule == 'employee_id': - employee_id = _clean_str(identity.get('employee_id')) - if not employee_id: - missing.append('employee_id') - else: - filters.append(User.employee_id == employee_id) - elif rule == 'mobile': - candidates = _mobile_candidates(identity) - if not candidates: - missing.append('mobile') - else: - filters.append(User.phone_number.in_(candidates)) - elif rule == 'email': - email = _clean_str(identity.get('email')) - if not email: - missing.append('email') - else: - filters.append(User.email == email) - if missing: - return ([], missing) - if not filters: - return ([], ['match_rules']) - clause = and_(*filters) if operator == 'AND' else or_(*filters) - users = db.session.query(User).filter(clause).all() - return (users, []) + 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') @@ -2168,66 +1809,3 @@ def get_db(): 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}) - -@user_bp.route('/announcements', methods=['GET']) -def get_announcements(): - """ - Get active announcements (Public) - """ - - def _load_announcements(): - anns = db.session.query(Announcement.id, Announcement.title, Announcement.content, Announcement.created_at).filter(Announcement.is_active.is_(True)).order_by(Announcement.created_at.desc()).all() - return jsonify([{'id': a.id, 'title': a.title, 'content': a.content, 'created_at': a.created_at.isoformat()} for a in anns]) - try: - return _run_db_with_retry(_load_announcements, label='user.announcements') - except (OperationalError, DatabaseError) as exc: - current_app.logger.warning('user.announcements retry failed: %s', exc) - raise ServiceUnavailableError('Database connection failed') - -@user_bp.route('/announcements', methods=['POST']) -def create_announcement(): - """ - Create announcement (Admin only) - """ - user = _get_current_user() - if not user or user.role != 'admin': - raise ForbiddenError('Unauthorized') - data = request.get_json() or {} - if not data.get('title') or not data.get('content'): - raise ValidationError('Missing fields') - ann = Announcement(title=data['title'], content=data['content'], is_active=True) - db.session.add(ann) - db.session.commit() - return (jsonify({'message': 'Created', 'id': ann.id}), 201) - -@user_bp.route('/announcements/', methods=['PUT']) -def update_announcement(id): - """ - 更新公告(仅管理员)。 - - 核心逻辑:校验 title/content 非空后更新 Announcement 记录。 - """ - user = _get_current_user() - if not user or user.role != 'admin': - raise ForbiddenError('Unauthorized') - data = request.get_json() or {} - if not data.get('title') or not data.get('content'): - raise ValidationError('Missing fields') - ann = db.session.get(Announcement, id) - if not ann: - raise NotFoundError('Not found') - ann.title = data['title'] - ann.content = data['content'] - db.session.commit() - return jsonify({'message': 'Updated'}) - -@user_bp.route('/announcements/', methods=['DELETE']) -def delete_announcement(id): - user = _get_current_user() - if not user or user.role != 'admin': - raise ForbiddenError('Unauthorized') - ann = db.session.get(Announcement, id) - if ann: - db.session.delete(ann) - db.session.commit() - return jsonify({'message': 'Deleted'}) diff --git a/backend/app/api/workspace/__init__.py b/backend/app/api/workspace/__init__.py index bd9e707d..1b6a4307 100644 --- a/backend/app/api/workspace/__init__.py +++ b/backend/app/api/workspace/__init__.py @@ -1,15 +1,18 @@ """ backend/app/api/workspace/__init__.py -用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check)。 -逻辑:Wave 1 前 re-export 旧 workspace_* 模块。 +用途:工作台域 Blueprint 聚合(schedule、shipping_notice、file_check、announcements)。 +依赖:workspace 各子模块 blueprint。 +逻辑:import 子模块注册路由;register_blueprints 从本包导入各 bp。 """ -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 +from app.api.workspace.announcements import workspace_announcements_bp +from app.api.workspace.file_check import workspace_file_check_bp +from app.api.workspace.schedule import workspace_schedule_bp +from app.api.workspace.shipping_notice import workspace_shipping_notice_bp __all__ = [ + 'workspace_announcements_bp', + 'workspace_file_check_bp', 'workspace_schedule_bp', 'workspace_shipping_notice_bp', - 'workspace_file_check_bp', ] diff --git a/backend/app/api/workspace/announcements.py b/backend/app/api/workspace/announcements.py new file mode 100644 index 00000000..bd77505c --- /dev/null +++ b/backend/app/api/workspace/announcements.py @@ -0,0 +1,27 @@ +""" +backend/app/api/workspace/announcements.py + +用途:工作台/登录页只读公告列表 API。 +依赖:services/admin/announcement_service(读活跃公告)。 +逻辑:GET /announcements 无需登录;管理 CRUD 见 api/admin/announcements.py。 +""" +from flask import Blueprint, jsonify + +from sqlalchemy.exc import DatabaseError, OperationalError + +from app.core.errors import ServiceUnavailableError +from app.services.admin import announcement_service + +workspace_announcements_bp = Blueprint('workspace_announcements', __name__) + + +@workspace_announcements_bp.route('/announcements', methods=['GET']) +def list_active_announcements(): + """返回已发布的公司公告(公开,供登录页与工作台展示)。""" + try: + return jsonify(announcement_service.list_active_announcements()) + except (OperationalError, DatabaseError) as exc: + from flask import current_app + + current_app.logger.warning('workspace.announcements query failed: %s', exc) + raise ServiceUnavailableError('Database connection failed') diff --git a/backend/app/api/workspace/file_check.py b/backend/app/api/workspace/file_check.py index b9bf6b05..6a692313 100644 --- a/backend/app/api/workspace/file_check.py +++ b/backend/app/api/workspace/file_check.py @@ -1,5 +1,111 @@ """ backend/app/api/workspace/file_check.py -用途:工作台文件检核路由(Wave 1 自 workspace_file_check.py 迁入)。 +用途:工作台文件检核进度轮询 API(对话页 tool_run_progress)。 +依赖:app.core.auth.jwt、app.core.errors、file_check_tools、schedule.query_service。 +逻辑:鉴权后查询 ScheduleRun 进度;register_blueprints 经 workspace 包注册。 """ +from __future__ import annotations + +from io import BytesIO + +from flask import Blueprint, jsonify, request, send_file + +from app.core.auth.jwt import get_current_user +from app.core.errors import NotFoundError, UnauthorizedError, ValidationError +from app.models import ScheduleRun, ScheduleTask +from app.services.file_check_tools.chat_log_run_resolver import find_run_for_chat_log +from app.services.schedule.query_service import get_run, serialize_run + +workspace_file_check_bp = Blueprint("workspace_file_check", __name__) + + +def _require_user(): + """ + 校验当前登录用户。 + Raises: + UnauthorizedError: 未认证。 + """ + user = get_current_user() + if not user: + raise UnauthorizedError() + return user + +def serialize_file_judgement(payload: dict) -> dict: + """序列化检核判定统计(读取 response_summary_json.file_judgement)。""" + response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {} + judgement = response_summary.get('file_judgement') + if not isinstance(judgement, dict): + judgement = {} + return {'qualified_count': int(judgement.get('qualified_count') or 0), 'unqualified_count': int(judgement.get('unqualified_count') or 0), 'manual_count': int(judgement.get('manual_count') or 0), 'dify_error_count': int(judgement.get('dify_error_count') or 0), 'invalid_result_count': int(judgement.get('invalid_result_count') or 0)} + +def serialize_current_step(payload: dict) -> dict | None: + response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {} + current_step = response_summary.get('current_step') if isinstance(response_summary.get('current_step'), dict) else None + if not current_step: + return None + return {'step': str(current_step.get('step') or ''), 'label': str(current_step.get('label') or current_step.get('step') or ''), 'row_id': current_step.get('row_id'), 'started_at': current_step.get('started_at'), 'processed_count': int(current_step.get('processed_count') or 0), 'success_count': int(current_step.get('success_count') or 0), 'failed_count': int(current_step.get('failed_count') or 0), 'skipped_count': int(current_step.get('skipped_count') or 0)} + +def _serialize_progress_run(run: ScheduleRun) -> dict: + payload = serialize_run(run) + total = int(payload.get('total_count') or 0) + success = int(payload.get('success_count') or 0) + failed = int(payload.get('failed_count') or 0) + skipped = int(payload.get('skipped_count') or 0) + processed = success + failed + skipped + percent = int(round(processed / total * 100)) if total > 0 else 0 + percent = max(0, min(percent, 100)) + return {'run_id': payload['id'], 'run_no': payload['run_no'], 'task_id': payload['schedule_task_id'], 'title': payload.get('schedule_name') or '', 'status': payload['status'], 'total_count': total, 'processed_count': processed, 'success_count': success, 'failed_count': failed, 'skipped_count': skipped, 'judgement': serialize_file_judgement(payload), 'current_step': serialize_current_step(payload), 'progress_percent': percent, 'started_at': payload.get('started_at'), 'finished_at': payload.get('finished_at'), 'duration_ms': payload.get('duration_ms'), 'error_message': payload.get('error_message'), 'excel': {'file_name': payload.get('excel_file_name'), 'file_size': payload.get('excel_file_size'), 'download_url': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None}, 'knowledge_base': {'sync_status': payload.get('kb_sync_status'), 'group_id': payload.get('kb_group_id'), 'document_id': payload.get('kb_document_id'), 'document_version_id': payload.get('kb_document_version_id'), 'sync_job_id': payload.get('kb_sync_job_id'), 'error_message': payload.get('kb_sync_error')}} + +@workspace_file_check_bp.route('/file-check/runs/for-log', methods=['GET']) +def workspace_file_check_run_for_log(): + """按 chat_log_id + schedule_task_id 返回该轮问答绑定的检核批次。""" + _require_user() + task_id = request.args.get('task_id', type=int) + chat_log_id = request.args.get('chat_log_id', type=int) + if not task_id or task_id <= 0: + raise ValidationError("task_id_required") + if not chat_log_id or chat_log_id <= 0: + raise ValidationError("chat_log_id_required") + run = find_run_for_chat_log(task_id=task_id, chat_log_id=chat_log_id) + return jsonify({'ok': True, 'run': _serialize_progress_run(run) if run else None, 'match_source': 'chat_log' if run else None}) + +@workspace_file_check_bp.route('/file-check/runs/for-session', methods=['GET']) +def workspace_file_check_run_for_session(): + """已废弃:请改用 for-log?chat_log_id=。保留接口避免旧客户端 404。""" + _require_user() + return jsonify({'ok': True, 'run': None, 'match_source': None, 'session_updated_at': None}) + +@workspace_file_check_bp.route('/file-check/runs/active', methods=['GET']) +def workspace_file_check_active_run(): + """查询当前进行中的检核批次;优先按 schedule_task_id(query: task_id)过滤。""" + _require_user() + task_id = request.args.get('task_id', type=int) + conversation_id = str(request.args.get('conversation_id') or '').strip() + query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id).filter(ScheduleRun.status == 'running') + if task_id is not None: + query = query.filter(ScheduleRun.schedule_task_id == task_id) + rows = query.order_by(ScheduleRun.id.desc()).all() + if task_id is not None: + run = rows[0] if rows else None + else: + run = next((row for row in rows if not conversation_id or str((row.api_request_json or {}).get('conversation_id') or '').strip() == conversation_id), None) + return jsonify({'ok': True, 'run': _serialize_progress_run(run) if run else None}) + +@workspace_file_check_bp.route('/file-check/runs/', methods=['GET']) +def workspace_file_check_run_detail(run_id: int): + _require_user() + run = get_run(run_id) + if not run: + raise NotFoundError('run_not_found') + return jsonify({'ok': True, 'run': _serialize_progress_run(run)}) + +@workspace_file_check_bp.route('/file-check/runs//excel', methods=['GET']) +def workspace_file_check_run_excel(run_id: int): + _require_user() + run = get_run(run_id) + if not run: + raise NotFoundError('run_not_found') + if not run.excel_file_data: + raise NotFoundError('excel_not_found') + return send_file(BytesIO(run.excel_file_data), as_attachment=True, download_name=run.excel_file_name or f'{run.run_no}.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') \ No newline at end of file diff --git a/backend/app/api/workspace/schedule.py b/backend/app/api/workspace/schedule.py index dcb6978e..6c23c928 100644 --- a/backend/app/api/workspace/schedule.py +++ b/backend/app/api/workspace/schedule.py @@ -1,5 +1,80 @@ """ backend/app/api/workspace/schedule.py -用途:工作台排程路由(Wave 1 自 workspace_schedule.py 迁入)。 +用途:工作台排程运行记录查询 API。 +依赖:app.core.auth.jwt、app.core.errors、schedule.query_service。 +逻辑:鉴权后只读查询 ScheduleRun;register_blueprints 经 workspace 包注册。 """ +from __future__ import annotations + +from datetime import datetime + +from flask import Blueprint, jsonify, request, send_file + +from app.core.auth.jwt import get_current_user +from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError +from app.services.schedule.query_service import can_view_run, get_run, list_runs, serialize_run + +workspace_schedule_bp = Blueprint("workspace_schedule", __name__) + + +def _require_user(): + """校验当前用户;未登录时抛出 UnauthorizedError。""" + user = get_current_user() + if not user: + raise UnauthorizedError() + return user + + +@workspace_schedule_bp.route("/schedule-runs", methods=["GET"]) +def workspace_schedule_runs(): + user = _require_user() + status = str(request.args.get("status") or "").strip() or None + schedule_name = str(request.args.get("schedule_name") or "").strip() or None + started_after_str = request.args.get("started_after") + started_before_str = request.args.get("started_before") + started_after = datetime.fromisoformat(started_after_str.replace("Z", "+00:00")) if started_after_str else None + started_before = datetime.fromisoformat(started_before_str.replace("Z", "+00:00")) if started_before_str else None + limit = int(request.args.get("limit") or 100) + return jsonify( + list_runs( + notify_user_id=user.id, + schedule_name=schedule_name, + status=status, + started_after=started_after, + started_before=started_before, + limit=limit, + ) + ) + + +@workspace_schedule_bp.route("/schedule-runs/", methods=["GET"]) +def workspace_schedule_run_detail(run_id: int): + user = _require_user() + run = get_run(run_id) + if not run: + raise NotFoundError("Not found") + if not can_view_run(run, user.id): + raise ForbiddenError("Forbidden") + return jsonify(serialize_run(run)) + + +@workspace_schedule_bp.route("/schedule-runs//excel", methods=["GET"]) +def workspace_schedule_run_excel(run_id: int): + from io import BytesIO + + user = _require_user() + run = get_run(run_id) + if not run: + raise NotFoundError("Not found") + if not can_view_run(run, user.id): + raise ForbiddenError("Forbidden") + if not run.excel_file_data: + raise NotFoundError("Excel not found") + buf = BytesIO(run.excel_file_data) + return send_file( + buf, + as_attachment=True, + download_name=run.excel_file_name or "result.xlsx", + mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + ) diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 651c18fc..f5f8e096 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -1,5 +1,559 @@ """ backend/app/api/workspace/shipping_notice.py -用途:工作台出货通知路由(Wave 1 自 workspace_shipping_notice.py 迁入)。 +用途:HXOPS 工作台与聊天前端使用的发货通知用户态 API。 +依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload。 +逻辑:薄路由层鉴权与参数校验;register_blueprints 经 workspace 包注册。 """ +from __future__ import annotations + +from flask import Blueprint, jsonify, request, send_file + +from app import db +from app.core.auth.jwt import get_current_user +from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError +from app.models import ShippingBatch, ShippingTask +from app.services.shipping_notice.chat_actions import build_chat_actions_payload +from app.services.shipping_notice.constants import ( + AUTO_CHAIN_FALLBACK, + CP_EXPORT_GENERATED, + CP_NOTICE_TEXT_EXTRACTION_FAILED, + MAP_JSON, +) +from app.services.shipping_notice.query_service import ( + EXPORT_MIME_TYPE, + get_batch_for_user, + get_conversation_batch_workspace, + get_focus_task_for_batch, + get_task_for_user, + list_batches_for_user, + list_tasks_for_batch, + list_tasks_for_user, + resolve_task_export_download, + serialize_batch_summary, + serialize_task_detail, + serialize_task_summary, + task_export_error_message, +) + +workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__) + + +def _require_user(): + """ + 校验当前登录用户;未认证时抛出 UnauthorizedError,由全局 handler 输出标准错误 JSON。 + Returns: + User 模型实例。 + Raises: + UnauthorizedError: 无有效 JWT 或 legacy header。 + """ + user = get_current_user() + if not user: + raise UnauthorizedError() + return user + + +@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET']) +def workspace_shipping_tasks(): + """列出当前用户可见的发货任务,可按批次与处理状态过滤。""" + user = _require_user() + batch_no = str(request.args.get('batch_no') or '').strip() or None + process_status = str(request.args.get('process_status') or '').strip() or None + limit = int(request.args.get('limit') or 100) + return jsonify(list_tasks_for_user(user.id, batch_no=batch_no, process_status=process_status, limit=limit)) + +@workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET']) +def workspace_shipping_batches(): + """列出当前用户的发货批次摘要。""" + user = _require_user() + limit = int(request.args.get('limit') or 100) + return jsonify(list_batches_for_user(user.id, limit=limit)) + +@workspace_shipping_notice_bp.route('/shipping-conversations//batch-workspace', methods=['GET']) +def workspace_shipping_conversation_batch_workspace(conversation_id: str): + """返回一个 Agent 会话下的多批次执行工作台快照。""" + user = _require_user() + batches = ShippingBatch.query.filter(ShippingBatch.conversation_id == str(conversation_id or "").strip()).filter( + (ShippingBatch.user_id == user.id) | (ShippingBatch.user_id.is_(None)) + ).all() + return jsonify(get_conversation_batch_workspace(conversation_id, user.id)) + +@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST']) +def workspace_create_shipping_batch_from_notices(): + """接收多份发货通知附件,创建批次并交给后台编排器逐票推进。""" + user = _require_user() + uploads = request.files.getlist('files') + if not uploads: + single = request.files.get('file') + if single: + uploads = [single] + if not uploads: + raise ValidationError('files is required') + from app.services.shipping_notice import tools as shipping_tools + from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload + conversation_id = str(request.form.get('conversation_id') or '').strip() + notice_items: list[dict] = [] + for upload in uploads: + raw = upload.read() or b'' + filename = upload.filename or 'notice' + source_type = guess_source_type(filename) + text = '' + warnings: list[str] = [] + try: + temp_task_no = f'TMP-{len(notice_items) + 1}' + saved_path = save_task_notice_upload(temp_task_no, filename, raw) + text, meta = extract_notice_text(saved_path) + warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else [] + except Exception as exc: + warnings = [f'notice_extract_failed:{exc}'] + if text: + limit = max_notice_chars() + if len(text) > limit: + text = text[:limit] + warnings.append(f'notice_text_truncated:{limit}') + notice_items.append({'source_type': source_type, 'source_file_name': filename, 'source_file_type': str(getattr(upload, 'mimetype', '') or '').strip() or None, 'raw_text': text, 'warnings': warnings}) + payload = {'user_id': user.id, 'conversation_id': conversation_id or None, 'file_count': len(notice_items), 'notice_items': notice_items, 'defer_parse': True} + created = shipping_tools.create_batch_tasks(payload) + data = created.get('data') if isinstance(created, dict) else None + batch_data = data.get('batch') if isinstance(data, dict) else None + tasks_data = data.get('tasks') if isinstance(data, dict) else None + batch_no = str(created.get('batch_no') or (batch_data or {}).get('batch_no') or '').strip() + orchestrator_started = False + if batch_no: + from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator + orchestrator_started = start_batch_orchestrator(batch_no) + if isinstance(data, dict) and batch_no: + focus_task = get_focus_task_for_batch(batch_no, user.id) + if focus_task: + data['focus_task'] = serialize_task_summary(focus_task) + if isinstance(tasks_data, list): + data['tasks'] = tasks_data + data['orchestrator_started'] = orchestrator_started + if isinstance(created, dict): + base_message = str(created.get('message') or '').strip() + if orchestrator_started: + created['message'] = f'{base_message},后台已开始逐票处理。' if base_message else '后台已开始逐票处理。' + return jsonify(created) + +@workspace_shipping_notice_bp.route('/shipping-batches/', methods=['GET']) +def workspace_shipping_batch_detail(batch_no: str): + """返回批次详情、批次内任务列表和当前焦点任务。""" + user = _require_user() + batch = get_batch_for_user(batch_no, user.id) + if not batch: + raise NotFoundError('Not found') + focus_task = get_focus_task_for_batch(batch_no, user.id) + return jsonify({**serialize_batch_summary(batch), 'tasks': list_tasks_for_batch(batch_no, user.id), 'focus_task': serialize_task_summary(focus_task) if focus_task else None}) + +@workspace_shipping_notice_bp.route('/shipping-batches//tasks', methods=['GET']) +def workspace_shipping_batch_tasks(batch_no: str): + """返回指定批次下的任务列表。""" + user = _require_user() + batch = get_batch_for_user(batch_no, user.id) + if not batch: + raise NotFoundError('Not found') + return jsonify(list_tasks_for_batch(batch_no, user.id)) + +@workspace_shipping_notice_bp.route('/shipping-batches//focus-task', methods=['GET']) +def workspace_shipping_batch_focus_task(batch_no: str): + """返回指定批次当前焦点任务的摘要。""" + user = _require_user() + batch = get_batch_for_user(batch_no, user.id) + if not batch: + raise NotFoundError('Not found') + focus_task = get_focus_task_for_batch(batch_no, user.id) + if not focus_task: + raise NotFoundError('Focus task not found') + return jsonify(serialize_task_summary(focus_task)) + +@workspace_shipping_notice_bp.route('/shipping-batches//focus-task', methods=['POST']) +def workspace_switch_shipping_batch_focus_task(batch_no: str): + """切换批次当前焦点任务,供工作台在同批次任务间跳转。""" + user = _require_user() + batch = get_batch_for_user(batch_no, user.id) + if not batch: + raise NotFoundError('Not found') + data = request.get_json(silent=True) or {} + task_no = str(data.get('task_no') or data.get('target_task_no') or '').strip() + if not task_no: + raise ValidationError('task_no is required') + task = get_task_for_user(task_no, user.id) + if not task or task.batch_id != batch.id: + raise NotFoundError('Task not found in batch') + batch.current_focus_task_no = task.task_no + db.session.commit() + return jsonify({'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}) + +@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['POST']) +def workspace_create_shipping_task(): + """创建单个发货任务,适用于手工录入或聊天入口先建单。""" + user = _require_user() + data = request.get_json(silent=True) or {} + payload = {'user_id': user.id} + source_type = str(data.get('source_type') or '').strip() + if source_type: + payload['source_type'] = source_type + conversation_id = str(data.get('conversation_id') or '').strip() + if conversation_id: + payload['conversation_id'] = conversation_id + raw_content = str(data.get('raw_content') or '').strip() + if raw_content: + payload['raw_content'] = raw_content + from app.services.shipping_notice import tools as shipping_tools + return jsonify(shipping_tools.create_task(payload)) + +@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST']) +def workspace_create_shipping_task_from_notice(): + """接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。""" + user = _require_user() + upload = request.files.get('file') + if not upload: + raise ValidationError('file is required') + from app.services.shipping_notice import tools as shipping_tools + from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload + source_type = guess_source_type(upload.filename or '') + conversation_id = str(request.form.get('conversation_id') or '').strip() + payload = {'user_id': user.id, 'source_type': source_type} + if conversation_id: + payload['conversation_id'] = conversation_id + created = shipping_tools.create_task(payload) + task_id = str(created.get('task_id') or '').strip() + if not task_id: + raise AppError(code='SYSTEM.INTERNAL_ERROR', message='failed to create task', http_status=500) + raw = upload.read() or b'' + saved_path = save_task_notice_upload(task_id, upload.filename or 'notice', raw) + text, meta = extract_notice_text(saved_path) + if not text: + from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint + return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': {'filename': upload.filename or '', **meta}}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)}) + if text: + limit = max_notice_chars() + if len(text) > limit: + text = text[:limit] + meta.setdefault('warnings', []).append(f'notice_text_truncated:{limit}') + task = ShippingTask.query.filter_by(task_no=task_id).first() + if task: + task.raw_content = text + db.session.commit() + task = ShippingTask.query.filter_by(task_no=task_id).first() + if task: + task.source_file_name = str(upload.filename or '').strip() or task.source_file_name + task.source_file_type = str(getattr(upload, 'mimetype', '') or '').strip() or task.source_file_type + db.session.commit() + from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator + orchestrator_started = start_task_orchestrator(task_id) + return jsonify({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': {'filename': upload.filename or '', **meta}, 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}}) + +@workspace_shipping_notice_bp.route('/shipping-tasks//replace-notice', methods=['POST']) +def workspace_replace_shipping_task_notice(task_no: str): + """重新上传发货通知并覆盖当前任务,不新建批次/任务。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + upload = request.files.get('file') + if not upload: + raise ValidationError('file is required') + from app.services.shipping_notice import task_workflow + from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload + raw = upload.read() or b'' + filename = upload.filename or 'notice' + saved_path = save_task_notice_upload(task.task_no, filename, raw) + text, meta = extract_notice_text(saved_path) + warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else [] + if text: + limit = max_notice_chars() + if len(text) > limit: + text = text[:limit] + warnings.append(f'notice_text_truncated:{limit}') + task.source_type = guess_source_type(filename) or task.source_type + result = task_workflow.replace_task_notice( + task, + raw_text=text, + source_file_name=filename, + source_file_type=str(getattr(upload, 'mimetype', '') or '').strip(), + warnings=warnings, + ) + data = result.setdefault('data', {}) + if isinstance(data, dict): + data['notice_upload'] = {'filename': filename, **(meta if isinstance(meta, dict) else {})} + return jsonify(result) + +@workspace_shipping_notice_bp.route('/shipping-tasks/', methods=['GET']) +def workspace_shipping_task_detail(task_no: str): + """返回指定任务的详情快照。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + return jsonify(serialize_task_detail(task)) + +@workspace_shipping_notice_bp.route('/shipping-tasks//chat-actions', methods=['GET']) +def workspace_shipping_task_chat_actions(task_no: str): + """返回聊天气泡侧所需的动作按钮与检查点信息。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + return jsonify(build_chat_actions_payload(task)) + +@workspace_shipping_notice_bp.route('/shipping-tasks//retry', methods=['POST']) +def workspace_retry_shipping_task(task_no: str): + """重试当前任务,适用于超时、解析失败或自动推进中断后的恢复。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + from app.services.shipping_notice import tools as shipping_tools + data = request.get_json(silent=True) or {} + payload = {'task_id': task.task_no} + comment = str(data.get('comment') or '').strip() + if comment: + payload['comment'] = comment + return jsonify(shipping_tools.retry_task(payload)) + +@workspace_shipping_notice_bp.route('/shipping-tasks//upload-inventory', methods=['POST']) +def workspace_upload_shipping_inventory(task_no: str): + """用户态上传库存 Excel,并在服务端完成解析。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + upload = request.files.get('file') + from app.services.shipping_notice import tools as shipping_tools + return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload)) + +@workspace_shipping_notice_bp.route('/shipping-tasks//confirm-inventory-source', methods=['POST']) +def workspace_confirm_shipping_inventory_source(task_no: str): + """确认当前任务的库存 RPA 来源,并继续触发库存导出。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + data = request.get_json(silent=True) or {} + source_code = str(data.get('source_code') or '').strip() + if not source_code: + raise ValidationError('source_code is required') + from app.services.shipping_notice import tools as shipping_tools + return jsonify(shipping_tools.confirm_inventory_source({'task_id': task.task_no, 'source_code': source_code})) + +@workspace_shipping_notice_bp.route('/shipping-tasks//apply-inventory-mapping', methods=['POST']) +def workspace_apply_inventory_mapping(task_no: str): + """提交库存字段映射,并允许在工作台侧自动回退到下一步。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + from app.services.shipping_notice import tools as shipping_tools + data = request.get_json(silent=True) or {} + map_json = data.get(MAP_JSON) + if not isinstance(map_json, dict) or not map_json: + raise ValidationError(f'{MAP_JSON} is required') + from app.services.shipping_notice import tools as shipping_tools + payload = {'task_id': task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True} + return jsonify(shipping_tools.apply_inventory_mapping(payload)) + +@workspace_shipping_notice_bp.route('/shipping-tasks//submit-decision', methods=['POST']) +def workspace_submit_shipping_decision(task_no: str): + """以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + data = request.get_json(silent=True) or {} + decision = str(data.get('decision') or '').strip() + if not decision: + raise ValidationError('decision is required') + from app.services.shipping_notice import tools as shipping_tools + payload = {'task_id': task.task_no, 'decision': decision, AUTO_CHAIN_FALLBACK: True} + comment = str(data.get('comment') or '').strip() + if comment: + payload['comment'] = comment + return jsonify(shipping_tools.submit_decision(payload)) + +@workspace_shipping_notice_bp.route('/shipping-tasks//update-notice-fields', methods=['POST']) +def workspace_update_shipping_notice_fields(task_no: str): + """更新发货通知单头字段。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + data = request.get_json(silent=True) or {} + fields = data.get('fields') + if not isinstance(fields, dict) or not fields: + raise ValidationError('fields is required') + from app.services.shipping_notice import tools as shipping_tools + payload = {'task_id': task.task_no, 'fields': fields} + comment = str(data.get('comment') or '').strip() + if comment: + payload['comment'] = comment + return jsonify(shipping_tools.update_notice_fields(payload)) + +@workspace_shipping_notice_bp.route('/shipping-tasks//update-notice-line', methods=['POST']) +def workspace_update_shipping_notice_line(task_no: str): + """更新发货通知中的指定订单行。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + data = request.get_json(silent=True) or {} + try: + line_index = int(data.get('line_index')) + except (TypeError, ValueError): + raise ValidationError('line_index is required') + patch = data.get('patch') + if not isinstance(patch, dict) or not patch: + raise ValidationError('patch is required') + from app.services.shipping_notice import tools as shipping_tools + payload = {'task_id': task.task_no, 'line_index': line_index, 'patch': patch} + comment = str(data.get('comment') or '').strip() + if comment: + payload['comment'] = comment + return jsonify(shipping_tools.update_notice_line(payload)) + +@workspace_shipping_notice_bp.route('/shipping-tasks//add-notice-line', methods=['POST']) +def workspace_add_shipping_notice_line(task_no: str): + """为发货通知新增订单行。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + data = request.get_json(silent=True) or {} + line = data.get('line') + if not isinstance(line, dict) or not line: + raise ValidationError('line is required') + from app.services.shipping_notice import tools as shipping_tools + payload = {'task_id': task.task_no, 'line': line} + comment = str(data.get('comment') or '').strip() + if comment: + payload['comment'] = comment + return jsonify(shipping_tools.add_notice_line(payload)) + +@workspace_shipping_notice_bp.route('/shipping-tasks//remove-notice-line', methods=['POST']) +def workspace_remove_shipping_notice_line(task_no: str): + """删除发货通知中的指定订单行。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + data = request.get_json(silent=True) or {} + try: + line_index = int(data.get('line_index')) + except (TypeError, ValueError): + raise ValidationError('line_index is required') + from app.services.shipping_notice import tools as shipping_tools + payload = {'task_id': task.task_no, 'line_index': line_index} + comment = str(data.get('comment') or '').strip() + if comment: + payload['comment'] = comment + return jsonify(shipping_tools.remove_notice_line(payload)) + +@workspace_shipping_notice_bp.route('/shipping-tasks//auto-progress', methods=['POST']) +def workspace_auto_progress_shipping_task(task_no: str): + """用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + from app.services.shipping_notice import tools as shipping_tools + data = request.get_json(silent=True) or {} + payload: dict = {'task_id': task.task_no} + for key in ('lang', 'locale', 'language'): + if data.get(key): + payload[key] = data[key] + break + result = shipping_tools.auto_progress(payload) + if isinstance(result, dict) and result.get('status') == 'ok': + gen_data = result.get('data') + if isinstance(gen_data, dict) and gen_data.get('export_file_path'): + gen_data = {**gen_data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'} + result = {**result, 'data': gen_data} + return jsonify(result) + +@workspace_shipping_notice_bp.route('/shipping-tasks//match-inventory', methods=['POST']) +def workspace_match_shipping_inventory(task_no: str): + """执行库存匹配,并在生成 Excel 后补充前端可直接下载的链接。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + from app.services.shipping_notice import tools as shipping_tools + from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint, human_options_for_checkpoint + matched = shipping_tools.match_inventory({'task_id': task.task_no, AUTO_CHAIN_FALLBACK: True}) + if not isinstance(matched, dict): + return jsonify(matched) + data = matched.get('data') + if isinstance(data, dict) and data.get('export_file_path'): + matched = {**matched, 'data': {**data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}} + checkpoint = matched.get('checkpoint') or CP_EXPORT_GENERATED + if matched.get('status') == 'ok' and data and data.get('export_file_path'): + matched['checkpoint'] = checkpoint + if 'human_options' not in matched: + options = human_options_for_checkpoint(checkpoint) + if options is not None: + matched['human_options'] = options + if 'action_buttons' not in matched: + buttons = action_buttons_for_checkpoint(checkpoint) + if buttons: + matched['action_buttons'] = buttons + return jsonify(matched) + +@workspace_shipping_notice_bp.route('/shipping-tasks//mark-manual-uploaded', methods=['POST']) +def workspace_mark_manual_uploaded(task_no: str): + """标记货代系统已人工上传完成,无需再等待 RPA 回执。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + from app.services.shipping_notice import tools as shipping_tools + return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'})) + +@workspace_shipping_notice_bp.route('/shipping-tasks//retry-upload', methods=['POST']) +def workspace_retry_shipping_upload(task_no: str): + """用户态重试上传货代系统,直接触发既有 RPA 上传链路。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + from app.services.shipping_notice import tools as shipping_tools + return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'retry_upload'})) + +@workspace_shipping_notice_bp.route('/shipping-tasks//generate-excel', methods=['POST']) +def workspace_generate_shipping_excel(task_no: str): + """为指定任务生成出货 Excel,并补充工作台下载链接。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + from app.services.shipping_notice import tools as shipping_tools + result = shipping_tools.generate_excel({'task_id': task.task_no}) + if isinstance(result, dict) and result.get('status') == 'ok': + data = result.get('data') + if not isinstance(data, dict): + data = {} + result['data'] = data + data['download_url'] = f'/api/workspace/shipping-tasks/{task.task_no}/export' + return jsonify(result) + +@workspace_shipping_notice_bp.route('/shipping-tasks//export', methods=['GET']) +def workspace_shipping_task_export(task_no: str): + """下载当前用户可访问任务的出货 Excel。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + err_msg = task_export_error_message(task) + if err_msg: + raise NotFoundError(err_msg) + resolved = resolve_task_export_download(task) + assert resolved is not None + path, download_name = resolved + return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE) + +@workspace_shipping_notice_bp.route('/shipping-batches//retry-pending', methods=['POST']) +def workspace_retry_shipping_batch_pending(batch_no: str): + """重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。""" + user = _require_user() + batch = get_batch_for_user(batch_no, user.id) + if not batch: + raise NotFoundError('Not found') + from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks + return jsonify(retry_batch_pending_tasks(batch.batch_no)) diff --git a/backend/app/api/workspace_file_check.py b/backend/app/api/workspace_file_check.py index c15d114c..e69bf962 100644 --- a/backend/app/api/workspace_file_check.py +++ b/backend/app/api/workspace_file_check.py @@ -1,111 +1,18 @@ """ backend/app/api/workspace_file_check.py -用途:工作台文件检核进度轮询 API(对话页 tool_run_progress)。 -依赖:app.core.auth.jwt、app.core.errors、file_check_tools、schedule.query_service。 -逻辑:鉴权后查询 ScheduleRun 进度;参数缺失 raise ValidationError,资源缺失 raise NotFoundError。 +用途:工作台文件检核 API 兼容 shim(Wave 1 迁包)。 +依赖:app.api.workspace.file_check。 +逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。 """ -from __future__ import annotations +from app.api.workspace.file_check import ( + serialize_current_step, + serialize_file_judgement, + workspace_file_check_bp, +) -from io import BytesIO - -from flask import Blueprint, jsonify, request, send_file - -from app.core.auth.jwt import get_current_user -from app.core.errors import NotFoundError, UnauthorizedError, ValidationError -from app.models import ScheduleRun, ScheduleTask -from app.services.file_check_tools.chat_log_run_resolver import find_run_for_chat_log -from app.services.schedule.query_service import get_run, serialize_run - -workspace_file_check_bp = Blueprint("workspace_file_check", __name__) - - -def _require_user(): - """ - 校验当前登录用户。 - Raises: - UnauthorizedError: 未认证。 - """ - user = get_current_user() - if not user: - raise UnauthorizedError() - return user - -def serialize_file_judgement(payload: dict) -> dict: - """序列化检核判定统计(读取 response_summary_json.file_judgement)。""" - response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {} - judgement = response_summary.get('file_judgement') - if not isinstance(judgement, dict): - judgement = {} - return {'qualified_count': int(judgement.get('qualified_count') or 0), 'unqualified_count': int(judgement.get('unqualified_count') or 0), 'manual_count': int(judgement.get('manual_count') or 0), 'dify_error_count': int(judgement.get('dify_error_count') or 0), 'invalid_result_count': int(judgement.get('invalid_result_count') or 0)} - -def serialize_current_step(payload: dict) -> dict | None: - response_summary = payload.get('response_summary_json') if isinstance(payload.get('response_summary_json'), dict) else {} - current_step = response_summary.get('current_step') if isinstance(response_summary.get('current_step'), dict) else None - if not current_step: - return None - return {'step': str(current_step.get('step') or ''), 'label': str(current_step.get('label') or current_step.get('step') or ''), 'row_id': current_step.get('row_id'), 'started_at': current_step.get('started_at'), 'processed_count': int(current_step.get('processed_count') or 0), 'success_count': int(current_step.get('success_count') or 0), 'failed_count': int(current_step.get('failed_count') or 0), 'skipped_count': int(current_step.get('skipped_count') or 0)} - -def _serialize_progress_run(run: ScheduleRun) -> dict: - payload = serialize_run(run) - total = int(payload.get('total_count') or 0) - success = int(payload.get('success_count') or 0) - failed = int(payload.get('failed_count') or 0) - skipped = int(payload.get('skipped_count') or 0) - processed = success + failed + skipped - percent = int(round(processed / total * 100)) if total > 0 else 0 - percent = max(0, min(percent, 100)) - return {'run_id': payload['id'], 'run_no': payload['run_no'], 'task_id': payload['schedule_task_id'], 'title': payload.get('schedule_name') or '', 'status': payload['status'], 'total_count': total, 'processed_count': processed, 'success_count': success, 'failed_count': failed, 'skipped_count': skipped, 'judgement': serialize_file_judgement(payload), 'current_step': serialize_current_step(payload), 'progress_percent': percent, 'started_at': payload.get('started_at'), 'finished_at': payload.get('finished_at'), 'duration_ms': payload.get('duration_ms'), 'error_message': payload.get('error_message'), 'excel': {'file_name': payload.get('excel_file_name'), 'file_size': payload.get('excel_file_size'), 'download_url': f'/api/workspace/file-check/runs/{run.id}/excel' if payload.get('excel_file_name') else None}, 'knowledge_base': {'sync_status': payload.get('kb_sync_status'), 'group_id': payload.get('kb_group_id'), 'document_id': payload.get('kb_document_id'), 'document_version_id': payload.get('kb_document_version_id'), 'sync_job_id': payload.get('kb_sync_job_id'), 'error_message': payload.get('kb_sync_error')}} - -@workspace_file_check_bp.route('/file-check/runs/for-log', methods=['GET']) -def workspace_file_check_run_for_log(): - """按 chat_log_id + schedule_task_id 返回该轮问答绑定的检核批次。""" - _require_user() - task_id = request.args.get('task_id', type=int) - chat_log_id = request.args.get('chat_log_id', type=int) - if not task_id or task_id <= 0: - raise ValidationError("task_id_required") - if not chat_log_id or chat_log_id <= 0: - raise ValidationError("chat_log_id_required") - run = find_run_for_chat_log(task_id=task_id, chat_log_id=chat_log_id) - return jsonify({'ok': True, 'run': _serialize_progress_run(run) if run else None, 'match_source': 'chat_log' if run else None}) - -@workspace_file_check_bp.route('/file-check/runs/for-session', methods=['GET']) -def workspace_file_check_run_for_session(): - """已废弃:请改用 for-log?chat_log_id=。保留接口避免旧客户端 404。""" - _require_user() - return jsonify({'ok': True, 'run': None, 'match_source': None, 'session_updated_at': None}) - -@workspace_file_check_bp.route('/file-check/runs/active', methods=['GET']) -def workspace_file_check_active_run(): - """查询当前进行中的检核批次;优先按 schedule_task_id(query: task_id)过滤。""" - _require_user() - task_id = request.args.get('task_id', type=int) - conversation_id = str(request.args.get('conversation_id') or '').strip() - query = ScheduleRun.query.join(ScheduleTask, ScheduleTask.id == ScheduleRun.schedule_task_id).filter(ScheduleRun.status == 'running') - if task_id is not None: - query = query.filter(ScheduleRun.schedule_task_id == task_id) - rows = query.order_by(ScheduleRun.id.desc()).all() - if task_id is not None: - run = rows[0] if rows else None - else: - run = next((row for row in rows if not conversation_id or str((row.api_request_json or {}).get('conversation_id') or '').strip() == conversation_id), None) - return jsonify({'ok': True, 'run': _serialize_progress_run(run) if run else None}) - -@workspace_file_check_bp.route('/file-check/runs/', methods=['GET']) -def workspace_file_check_run_detail(run_id: int): - _require_user() - run = get_run(run_id) - if not run: - raise NotFoundError('run_not_found') - return jsonify({'ok': True, 'run': _serialize_progress_run(run)}) - -@workspace_file_check_bp.route('/file-check/runs//excel', methods=['GET']) -def workspace_file_check_run_excel(run_id: int): - _require_user() - run = get_run(run_id) - if not run: - raise NotFoundError('run_not_found') - if not run.excel_file_data: - raise NotFoundError('excel_not_found') - return send_file(BytesIO(run.excel_file_data), as_attachment=True, download_name=run.excel_file_name or f'{run.run_no}.xlsx', mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') \ No newline at end of file +__all__ = [ + 'serialize_current_step', + 'serialize_file_judgement', + 'workspace_file_check_bp', +] diff --git a/backend/app/api/workspace_schedule.py b/backend/app/api/workspace_schedule.py index dd78ae7f..9f2fde83 100644 --- a/backend/app/api/workspace_schedule.py +++ b/backend/app/api/workspace_schedule.py @@ -1,80 +1,10 @@ """ backend/app/api/workspace_schedule.py -用途:工作台排程运行记录查询 API。 -依赖:app.core.auth.jwt、app.core.errors、schedule.query_service。 -逻辑:鉴权后只读查询 ScheduleRun;未登录 raise UnauthorizedError。 +用途:工作台排程 API 兼容 shim(Wave 1 迁包)。 +依赖:app.api.workspace.schedule。 +逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。 """ -from __future__ import annotations +from app.api.workspace.schedule import workspace_schedule_bp -from datetime import datetime - -from flask import Blueprint, jsonify, request, send_file - -from app.core.auth.jwt import get_current_user -from app.core.errors import ForbiddenError, NotFoundError, UnauthorizedError -from app.services.schedule.query_service import can_view_run, get_run, list_runs, serialize_run - -workspace_schedule_bp = Blueprint("workspace_schedule", __name__) - - -def _require_user(): - """校验当前用户;未登录时抛出 UnauthorizedError。""" - user = get_current_user() - if not user: - raise UnauthorizedError() - return user - - -@workspace_schedule_bp.route("/schedule-runs", methods=["GET"]) -def workspace_schedule_runs(): - user = _require_user() - status = str(request.args.get("status") or "").strip() or None - schedule_name = str(request.args.get("schedule_name") or "").strip() or None - started_after_str = request.args.get("started_after") - started_before_str = request.args.get("started_before") - started_after = datetime.fromisoformat(started_after_str.replace("Z", "+00:00")) if started_after_str else None - started_before = datetime.fromisoformat(started_before_str.replace("Z", "+00:00")) if started_before_str else None - limit = int(request.args.get("limit") or 100) - return jsonify( - list_runs( - notify_user_id=user.id, - schedule_name=schedule_name, - status=status, - started_after=started_after, - started_before=started_before, - limit=limit, - ) - ) - - -@workspace_schedule_bp.route("/schedule-runs/", methods=["GET"]) -def workspace_schedule_run_detail(run_id: int): - user = _require_user() - run = get_run(run_id) - if not run: - raise NotFoundError("Not found") - if not can_view_run(run, user.id): - raise ForbiddenError("Forbidden") - return jsonify(serialize_run(run)) - - -@workspace_schedule_bp.route("/schedule-runs//excel", methods=["GET"]) -def workspace_schedule_run_excel(run_id: int): - from io import BytesIO - - user = _require_user() - run = get_run(run_id) - if not run: - raise NotFoundError("Not found") - if not can_view_run(run, user.id): - raise ForbiddenError("Forbidden") - if not run.excel_file_data: - raise NotFoundError("Excel not found") - buf = BytesIO(run.excel_file_data) - return send_file( - buf, - as_attachment=True, - download_name=run.excel_file_name or "result.xlsx", - mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - ) +__all__ = ['workspace_schedule_bp'] diff --git a/backend/app/api/workspace_shipping_notice.py b/backend/app/api/workspace_shipping_notice.py index 79226639..4744d483 100644 --- a/backend/app/api/workspace_shipping_notice.py +++ b/backend/app/api/workspace_shipping_notice.py @@ -1,559 +1,10 @@ """ -api/workspace_shipping_notice.py +backend/app/api/workspace_shipping_notice.py -用途:提供 HXOPS 工作台与聊天前端使用的发货通知用户态 API。 -依赖:app.core.auth.jwt、app.core.errors、shipping_notice.query_service / tools / notice_upload。 -逻辑:薄路由层做鉴权与参数校验(统一 raise AppError);业务编排下沉 shipping_notice service。 +用途:工作台发货通知 API 兼容 shim(Wave 1 迁包)。 +依赖:app.api.workspace.shipping_notice。 +逻辑:旧 import 路径仍可用;新代码请用 app.api.workspace。 """ -from __future__ import annotations +from app.api.workspace.shipping_notice import workspace_shipping_notice_bp -from flask import Blueprint, jsonify, request, send_file - -from app import db -from app.core.auth.jwt import get_current_user -from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError -from app.models import ShippingBatch, ShippingTask -from app.services.shipping_notice.chat_actions import build_chat_actions_payload -from app.services.shipping_notice.constants import ( - AUTO_CHAIN_FALLBACK, - CP_EXPORT_GENERATED, - CP_NOTICE_TEXT_EXTRACTION_FAILED, - MAP_JSON, -) -from app.services.shipping_notice.query_service import ( - EXPORT_MIME_TYPE, - get_batch_for_user, - get_conversation_batch_workspace, - get_focus_task_for_batch, - get_task_for_user, - list_batches_for_user, - list_tasks_for_batch, - list_tasks_for_user, - resolve_task_export_download, - serialize_batch_summary, - serialize_task_detail, - serialize_task_summary, - task_export_error_message, -) - -workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__) - - -def _require_user(): - """ - 校验当前登录用户;未认证时抛出 UnauthorizedError,由全局 handler 输出标准错误 JSON。 - Returns: - User 模型实例。 - Raises: - UnauthorizedError: 无有效 JWT 或 legacy header。 - """ - user = get_current_user() - if not user: - raise UnauthorizedError() - return user - - -@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET']) -def workspace_shipping_tasks(): - """列出当前用户可见的发货任务,可按批次与处理状态过滤。""" - user = _require_user() - batch_no = str(request.args.get('batch_no') or '').strip() or None - process_status = str(request.args.get('process_status') or '').strip() or None - limit = int(request.args.get('limit') or 100) - return jsonify(list_tasks_for_user(user.id, batch_no=batch_no, process_status=process_status, limit=limit)) - -@workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET']) -def workspace_shipping_batches(): - """列出当前用户的发货批次摘要。""" - user = _require_user() - limit = int(request.args.get('limit') or 100) - return jsonify(list_batches_for_user(user.id, limit=limit)) - -@workspace_shipping_notice_bp.route('/shipping-conversations//batch-workspace', methods=['GET']) -def workspace_shipping_conversation_batch_workspace(conversation_id: str): - """返回一个 Agent 会话下的多批次执行工作台快照。""" - user = _require_user() - batches = ShippingBatch.query.filter(ShippingBatch.conversation_id == str(conversation_id or "").strip()).filter( - (ShippingBatch.user_id == user.id) | (ShippingBatch.user_id.is_(None)) - ).all() - return jsonify(get_conversation_batch_workspace(conversation_id, user.id)) - -@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST']) -def workspace_create_shipping_batch_from_notices(): - """接收多份发货通知附件,创建批次并交给后台编排器逐票推进。""" - user = _require_user() - uploads = request.files.getlist('files') - if not uploads: - single = request.files.get('file') - if single: - uploads = [single] - if not uploads: - raise ValidationError('files is required') - from app.services.shipping_notice import tools as shipping_tools - from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload - conversation_id = str(request.form.get('conversation_id') or '').strip() - notice_items: list[dict] = [] - for upload in uploads: - raw = upload.read() or b'' - filename = upload.filename or 'notice' - source_type = guess_source_type(filename) - text = '' - warnings: list[str] = [] - try: - temp_task_no = f'TMP-{len(notice_items) + 1}' - saved_path = save_task_notice_upload(temp_task_no, filename, raw) - text, meta = extract_notice_text(saved_path) - warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else [] - except Exception as exc: - warnings = [f'notice_extract_failed:{exc}'] - if text: - limit = max_notice_chars() - if len(text) > limit: - text = text[:limit] - warnings.append(f'notice_text_truncated:{limit}') - notice_items.append({'source_type': source_type, 'source_file_name': filename, 'source_file_type': str(getattr(upload, 'mimetype', '') or '').strip() or None, 'raw_text': text, 'warnings': warnings}) - payload = {'user_id': user.id, 'conversation_id': conversation_id or None, 'file_count': len(notice_items), 'notice_items': notice_items, 'defer_parse': True} - created = shipping_tools.create_batch_tasks(payload) - data = created.get('data') if isinstance(created, dict) else None - batch_data = data.get('batch') if isinstance(data, dict) else None - tasks_data = data.get('tasks') if isinstance(data, dict) else None - batch_no = str(created.get('batch_no') or (batch_data or {}).get('batch_no') or '').strip() - orchestrator_started = False - if batch_no: - from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator - orchestrator_started = start_batch_orchestrator(batch_no) - if isinstance(data, dict) and batch_no: - focus_task = get_focus_task_for_batch(batch_no, user.id) - if focus_task: - data['focus_task'] = serialize_task_summary(focus_task) - if isinstance(tasks_data, list): - data['tasks'] = tasks_data - data['orchestrator_started'] = orchestrator_started - if isinstance(created, dict): - base_message = str(created.get('message') or '').strip() - if orchestrator_started: - created['message'] = f'{base_message},后台已开始逐票处理。' if base_message else '后台已开始逐票处理。' - return jsonify(created) - -@workspace_shipping_notice_bp.route('/shipping-batches/', methods=['GET']) -def workspace_shipping_batch_detail(batch_no: str): - """返回批次详情、批次内任务列表和当前焦点任务。""" - user = _require_user() - batch = get_batch_for_user(batch_no, user.id) - if not batch: - raise NotFoundError('Not found') - focus_task = get_focus_task_for_batch(batch_no, user.id) - return jsonify({**serialize_batch_summary(batch), 'tasks': list_tasks_for_batch(batch_no, user.id), 'focus_task': serialize_task_summary(focus_task) if focus_task else None}) - -@workspace_shipping_notice_bp.route('/shipping-batches//tasks', methods=['GET']) -def workspace_shipping_batch_tasks(batch_no: str): - """返回指定批次下的任务列表。""" - user = _require_user() - batch = get_batch_for_user(batch_no, user.id) - if not batch: - raise NotFoundError('Not found') - return jsonify(list_tasks_for_batch(batch_no, user.id)) - -@workspace_shipping_notice_bp.route('/shipping-batches//focus-task', methods=['GET']) -def workspace_shipping_batch_focus_task(batch_no: str): - """返回指定批次当前焦点任务的摘要。""" - user = _require_user() - batch = get_batch_for_user(batch_no, user.id) - if not batch: - raise NotFoundError('Not found') - focus_task = get_focus_task_for_batch(batch_no, user.id) - if not focus_task: - raise NotFoundError('Focus task not found') - return jsonify(serialize_task_summary(focus_task)) - -@workspace_shipping_notice_bp.route('/shipping-batches//focus-task', methods=['POST']) -def workspace_switch_shipping_batch_focus_task(batch_no: str): - """切换批次当前焦点任务,供工作台在同批次任务间跳转。""" - user = _require_user() - batch = get_batch_for_user(batch_no, user.id) - if not batch: - raise NotFoundError('Not found') - data = request.get_json(silent=True) or {} - task_no = str(data.get('task_no') or data.get('target_task_no') or '').strip() - if not task_no: - raise ValidationError('task_no is required') - task = get_task_for_user(task_no, user.id) - if not task or task.batch_id != batch.id: - raise NotFoundError('Task not found in batch') - batch.current_focus_task_no = task.task_no - db.session.commit() - return jsonify({'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}) - -@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['POST']) -def workspace_create_shipping_task(): - """创建单个发货任务,适用于手工录入或聊天入口先建单。""" - user = _require_user() - data = request.get_json(silent=True) or {} - payload = {'user_id': user.id} - source_type = str(data.get('source_type') or '').strip() - if source_type: - payload['source_type'] = source_type - conversation_id = str(data.get('conversation_id') or '').strip() - if conversation_id: - payload['conversation_id'] = conversation_id - raw_content = str(data.get('raw_content') or '').strip() - if raw_content: - payload['raw_content'] = raw_content - from app.services.shipping_notice import tools as shipping_tools - return jsonify(shipping_tools.create_task(payload)) - -@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST']) -def workspace_create_shipping_task_from_notice(): - """接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。""" - user = _require_user() - upload = request.files.get('file') - if not upload: - raise ValidationError('file is required') - from app.services.shipping_notice import tools as shipping_tools - from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload - source_type = guess_source_type(upload.filename or '') - conversation_id = str(request.form.get('conversation_id') or '').strip() - payload = {'user_id': user.id, 'source_type': source_type} - if conversation_id: - payload['conversation_id'] = conversation_id - created = shipping_tools.create_task(payload) - task_id = str(created.get('task_id') or '').strip() - if not task_id: - raise AppError(code='SYSTEM.INTERNAL_ERROR', message='failed to create task', http_status=500) - raw = upload.read() or b'' - saved_path = save_task_notice_upload(task_id, upload.filename or 'notice', raw) - text, meta = extract_notice_text(saved_path) - if not text: - from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint - return jsonify({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': {'filename': upload.filename or '', **meta}}, 'human_options': ['reparse', 'reject'], 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED, 'action_buttons': action_buttons_for_checkpoint(CP_NOTICE_TEXT_EXTRACTION_FAILED)}) - if text: - limit = max_notice_chars() - if len(text) > limit: - text = text[:limit] - meta.setdefault('warnings', []).append(f'notice_text_truncated:{limit}') - task = ShippingTask.query.filter_by(task_no=task_id).first() - if task: - task.raw_content = text - db.session.commit() - task = ShippingTask.query.filter_by(task_no=task_id).first() - if task: - task.source_file_name = str(upload.filename or '').strip() or task.source_file_name - task.source_file_type = str(getattr(upload, 'mimetype', '') or '').strip() or task.source_file_type - db.session.commit() - from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator - orchestrator_started = start_task_orchestrator(task_id) - return jsonify({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': {'filename': upload.filename or '', **meta}, 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}}) - -@workspace_shipping_notice_bp.route('/shipping-tasks//replace-notice', methods=['POST']) -def workspace_replace_shipping_task_notice(task_no: str): - """重新上传发货通知并覆盖当前任务,不新建批次/任务。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - upload = request.files.get('file') - if not upload: - raise ValidationError('file is required') - from app.services.shipping_notice import task_workflow - from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload - raw = upload.read() or b'' - filename = upload.filename or 'notice' - saved_path = save_task_notice_upload(task.task_no, filename, raw) - text, meta = extract_notice_text(saved_path) - warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else [] - if text: - limit = max_notice_chars() - if len(text) > limit: - text = text[:limit] - warnings.append(f'notice_text_truncated:{limit}') - task.source_type = guess_source_type(filename) or task.source_type - result = task_workflow.replace_task_notice( - task, - raw_text=text, - source_file_name=filename, - source_file_type=str(getattr(upload, 'mimetype', '') or '').strip(), - warnings=warnings, - ) - data = result.setdefault('data', {}) - if isinstance(data, dict): - data['notice_upload'] = {'filename': filename, **(meta if isinstance(meta, dict) else {})} - return jsonify(result) - -@workspace_shipping_notice_bp.route('/shipping-tasks/', methods=['GET']) -def workspace_shipping_task_detail(task_no: str): - """返回指定任务的详情快照。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - return jsonify(serialize_task_detail(task)) - -@workspace_shipping_notice_bp.route('/shipping-tasks//chat-actions', methods=['GET']) -def workspace_shipping_task_chat_actions(task_no: str): - """返回聊天气泡侧所需的动作按钮与检查点信息。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - return jsonify(build_chat_actions_payload(task)) - -@workspace_shipping_notice_bp.route('/shipping-tasks//retry', methods=['POST']) -def workspace_retry_shipping_task(task_no: str): - """重试当前任务,适用于超时、解析失败或自动推进中断后的恢复。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - from app.services.shipping_notice import tools as shipping_tools - data = request.get_json(silent=True) or {} - payload = {'task_id': task.task_no} - comment = str(data.get('comment') or '').strip() - if comment: - payload['comment'] = comment - return jsonify(shipping_tools.retry_task(payload)) - -@workspace_shipping_notice_bp.route('/shipping-tasks//upload-inventory', methods=['POST']) -def workspace_upload_shipping_inventory(task_no: str): - """用户态上传库存 Excel,并在服务端完成解析。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - upload = request.files.get('file') - from app.services.shipping_notice import tools as shipping_tools - return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload)) - -@workspace_shipping_notice_bp.route('/shipping-tasks//confirm-inventory-source', methods=['POST']) -def workspace_confirm_shipping_inventory_source(task_no: str): - """确认当前任务的库存 RPA 来源,并继续触发库存导出。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - data = request.get_json(silent=True) or {} - source_code = str(data.get('source_code') or '').strip() - if not source_code: - raise ValidationError('source_code is required') - from app.services.shipping_notice import tools as shipping_tools - return jsonify(shipping_tools.confirm_inventory_source({'task_id': task.task_no, 'source_code': source_code})) - -@workspace_shipping_notice_bp.route('/shipping-tasks//apply-inventory-mapping', methods=['POST']) -def workspace_apply_inventory_mapping(task_no: str): - """提交库存字段映射,并允许在工作台侧自动回退到下一步。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - from app.services.shipping_notice import tools as shipping_tools - data = request.get_json(silent=True) or {} - map_json = data.get(MAP_JSON) - if not isinstance(map_json, dict) or not map_json: - raise ValidationError(f'{MAP_JSON} is required') - from app.services.shipping_notice import tools as shipping_tools - payload = {'task_id': task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True} - return jsonify(shipping_tools.apply_inventory_mapping(payload)) - -@workspace_shipping_notice_bp.route('/shipping-tasks//submit-decision', methods=['POST']) -def workspace_submit_shipping_decision(task_no: str): - """以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - data = request.get_json(silent=True) or {} - decision = str(data.get('decision') or '').strip() - if not decision: - raise ValidationError('decision is required') - from app.services.shipping_notice import tools as shipping_tools - payload = {'task_id': task.task_no, 'decision': decision, AUTO_CHAIN_FALLBACK: True} - comment = str(data.get('comment') or '').strip() - if comment: - payload['comment'] = comment - return jsonify(shipping_tools.submit_decision(payload)) - -@workspace_shipping_notice_bp.route('/shipping-tasks//update-notice-fields', methods=['POST']) -def workspace_update_shipping_notice_fields(task_no: str): - """更新发货通知单头字段。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - data = request.get_json(silent=True) or {} - fields = data.get('fields') - if not isinstance(fields, dict) or not fields: - raise ValidationError('fields is required') - from app.services.shipping_notice import tools as shipping_tools - payload = {'task_id': task.task_no, 'fields': fields} - comment = str(data.get('comment') or '').strip() - if comment: - payload['comment'] = comment - return jsonify(shipping_tools.update_notice_fields(payload)) - -@workspace_shipping_notice_bp.route('/shipping-tasks//update-notice-line', methods=['POST']) -def workspace_update_shipping_notice_line(task_no: str): - """更新发货通知中的指定订单行。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - data = request.get_json(silent=True) or {} - try: - line_index = int(data.get('line_index')) - except (TypeError, ValueError): - raise ValidationError('line_index is required') - patch = data.get('patch') - if not isinstance(patch, dict) or not patch: - raise ValidationError('patch is required') - from app.services.shipping_notice import tools as shipping_tools - payload = {'task_id': task.task_no, 'line_index': line_index, 'patch': patch} - comment = str(data.get('comment') or '').strip() - if comment: - payload['comment'] = comment - return jsonify(shipping_tools.update_notice_line(payload)) - -@workspace_shipping_notice_bp.route('/shipping-tasks//add-notice-line', methods=['POST']) -def workspace_add_shipping_notice_line(task_no: str): - """为发货通知新增订单行。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - data = request.get_json(silent=True) or {} - line = data.get('line') - if not isinstance(line, dict) or not line: - raise ValidationError('line is required') - from app.services.shipping_notice import tools as shipping_tools - payload = {'task_id': task.task_no, 'line': line} - comment = str(data.get('comment') or '').strip() - if comment: - payload['comment'] = comment - return jsonify(shipping_tools.add_notice_line(payload)) - -@workspace_shipping_notice_bp.route('/shipping-tasks//remove-notice-line', methods=['POST']) -def workspace_remove_shipping_notice_line(task_no: str): - """删除发货通知中的指定订单行。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - data = request.get_json(silent=True) or {} - try: - line_index = int(data.get('line_index')) - except (TypeError, ValueError): - raise ValidationError('line_index is required') - from app.services.shipping_notice import tools as shipping_tools - payload = {'task_id': task.task_no, 'line_index': line_index} - comment = str(data.get('comment') or '').strip() - if comment: - payload['comment'] = comment - return jsonify(shipping_tools.remove_notice_line(payload)) - -@workspace_shipping_notice_bp.route('/shipping-tasks//auto-progress', methods=['POST']) -def workspace_auto_progress_shipping_task(task_no: str): - """用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - from app.services.shipping_notice import tools as shipping_tools - data = request.get_json(silent=True) or {} - payload: dict = {'task_id': task.task_no} - for key in ('lang', 'locale', 'language'): - if data.get(key): - payload[key] = data[key] - break - result = shipping_tools.auto_progress(payload) - if isinstance(result, dict) and result.get('status') == 'ok': - gen_data = result.get('data') - if isinstance(gen_data, dict) and gen_data.get('export_file_path'): - gen_data = {**gen_data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'} - result = {**result, 'data': gen_data} - return jsonify(result) - -@workspace_shipping_notice_bp.route('/shipping-tasks//match-inventory', methods=['POST']) -def workspace_match_shipping_inventory(task_no: str): - """执行库存匹配,并在生成 Excel 后补充前端可直接下载的链接。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - from app.services.shipping_notice import tools as shipping_tools - from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint, human_options_for_checkpoint - matched = shipping_tools.match_inventory({'task_id': task.task_no, AUTO_CHAIN_FALLBACK: True}) - if not isinstance(matched, dict): - return jsonify(matched) - data = matched.get('data') - if isinstance(data, dict) and data.get('export_file_path'): - matched = {**matched, 'data': {**data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}} - checkpoint = matched.get('checkpoint') or CP_EXPORT_GENERATED - if matched.get('status') == 'ok' and data and data.get('export_file_path'): - matched['checkpoint'] = checkpoint - if 'human_options' not in matched: - options = human_options_for_checkpoint(checkpoint) - if options is not None: - matched['human_options'] = options - if 'action_buttons' not in matched: - buttons = action_buttons_for_checkpoint(checkpoint) - if buttons: - matched['action_buttons'] = buttons - return jsonify(matched) - -@workspace_shipping_notice_bp.route('/shipping-tasks//mark-manual-uploaded', methods=['POST']) -def workspace_mark_manual_uploaded(task_no: str): - """标记货代系统已人工上传完成,无需再等待 RPA 回执。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - from app.services.shipping_notice import tools as shipping_tools - return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'})) - -@workspace_shipping_notice_bp.route('/shipping-tasks//retry-upload', methods=['POST']) -def workspace_retry_shipping_upload(task_no: str): - """用户态重试上传货代系统,直接触发既有 RPA 上传链路。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - from app.services.shipping_notice import tools as shipping_tools - return jsonify(shipping_tools.upload_to_freight({'task_id': task.task_no, 'mode': 'retry_upload'})) - -@workspace_shipping_notice_bp.route('/shipping-tasks//generate-excel', methods=['POST']) -def workspace_generate_shipping_excel(task_no: str): - """为指定任务生成出货 Excel,并补充工作台下载链接。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - if not task: - raise NotFoundError('Not found') - from app.services.shipping_notice import tools as shipping_tools - result = shipping_tools.generate_excel({'task_id': task.task_no}) - if isinstance(result, dict) and result.get('status') == 'ok': - data = result.get('data') - if not isinstance(data, dict): - data = {} - result['data'] = data - data['download_url'] = f'/api/workspace/shipping-tasks/{task.task_no}/export' - return jsonify(result) - -@workspace_shipping_notice_bp.route('/shipping-tasks//export', methods=['GET']) -def workspace_shipping_task_export(task_no: str): - """下载当前用户可访问任务的出货 Excel。""" - user = _require_user() - task = get_task_for_user(task_no, user.id) - err_msg = task_export_error_message(task) - if err_msg: - raise NotFoundError(err_msg) - resolved = resolve_task_export_download(task) - assert resolved is not None - path, download_name = resolved - return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE) - -@workspace_shipping_notice_bp.route('/shipping-batches//retry-pending', methods=['POST']) -def workspace_retry_shipping_batch_pending(batch_no: str): - """重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。""" - user = _require_user() - batch = get_batch_for_user(batch_no, user.id) - if not batch: - raise NotFoundError('Not found') - from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks - return jsonify(retry_batch_pending_tasks(batch.batch_no)) +__all__ = ['workspace_shipping_notice_bp'] diff --git a/backend/app/services/admin/__init__.py b/backend/app/services/admin/__init__.py index 4895b4b3..8d07c3d7 100644 --- a/backend/app/services/admin/__init__.py +++ b/backend/app/services/admin/__init__.py @@ -2,5 +2,32 @@ backend/app/services/admin/__init__.py 用途:管理后台业务服务包。 -逻辑:Wave 3 从 api/admin/_legacy 抽取 users/agents/departments/settings 等。 +逻辑:Wave 3 从 api/admin 抽取;子模块按需 import。 """ +from . import ( + agent_service, + announcement_service, + dashboard_service, + database_admin_service, + department_service, + faq_service, + guide_service, + permission_service, + report_service, + user_service, + wecom_admin_service, +) + +__all__ = [ + 'agent_service', + 'announcement_service', + 'dashboard_service', + 'database_admin_service', + 'department_service', + 'faq_service', + 'guide_service', + 'permission_service', + 'report_service', + 'user_service', + 'wecom_admin_service', +] diff --git a/backend/app/services/admin/agent_service.py b/backend/app/services/admin/agent_service.py index 59f4de90..9789ee49 100644 --- a/backend/app/services/admin/agent_service.py +++ b/backend/app/services/admin/agent_service.py @@ -1,5 +1,290 @@ """ backend/app/services/admin/agent_service.py -用途:Agent CRUD、权限、guide 配置。 +用途:管理端 Agent CRUD、连通性测试、用户权限绑定。 +依赖:models、DifyService、Config、requests。 +逻辑:由 api/admin/agents.py 调用。 """ +from __future__ import annotations + +from datetime import datetime +from typing import Any + +import requests + +from app import db +from app.core.config.settings import Config +from app.core.errors import NotFoundError, ValidationError +from app.models import Agent, User +from app.services.dify import DifyService + + +def serialize_agent(agent: Agent) -> dict: + """Agent ORM → 管理端列表 JSON。""" + return { + 'id': agent.id, + 'name': agent.name, + 'dify_app_id': agent.dify_app_id, + 'dify_api_key': agent.dify_api_key, + 'is_active': agent.is_active, + 'description': agent.description, + 'type': agent.type, + 'api_base_url': agent.api_base_url, + 'extra_config': agent.extra_config, + } + + +def list_agents() -> list[dict]: + """返回全部 Agent(按 id 升序)。""" + agents = db.session.query(Agent).order_by(Agent.id.asc()).all() + return [serialize_agent(a) for a in agents] + + +def create_agent(data: dict[str, Any]) -> dict: + """ + 创建 Agent。 + Returns: + { id }。 + Raises: + ValidationError: name 缺失或 API 类型缺少 dify_app_id。 + """ + if not data.get('name'): + raise ValidationError('Name is required') + agent_type = data.get('type', 'api') + if agent_type == 'api' and (not data.get('dify_app_id')): + raise ValidationError('App ID is required for API agents') + agent = Agent( + name=data['name'], + dify_app_id=data.get('dify_app_id') or None, + dify_api_key=data.get('dify_api_key') or None, + description=data.get('description'), + type=agent_type, + api_base_url=data.get('api_base_url'), + extra_config=data.get('extra_config'), + is_active=data.get('is_active', True), + ) + db.session.add(agent) + db.session.commit() + return {'id': agent.id} + + +def update_agent(agent_id: int, data: dict[str, Any]) -> None: + """更新 Agent 字段;dify_api_key 仅在非空时覆盖。""" + agent = db.session.get(Agent, agent_id) + if not agent: + raise NotFoundError('Not found') + for key in ['name', 'dify_app_id', 'description', 'type', 'api_base_url', 'extra_config', 'is_active']: + if key in data: + setattr(agent, key, data[key]) + if data.get('dify_api_key'): + agent.dify_api_key = data['dify_api_key'] + db.session.commit() + + +def delete_agent(agent_id: int) -> None: + """删除 Agent(不存在时静默成功)。""" + agent = db.session.get(Agent, agent_id) + if agent: + db.session.delete(agent) + db.session.commit() + + +def test_agent_connectivity(agent_id: int) -> dict[str, Any]: + """ + 测试 Agent 连通性(iframe GET 或 Dify chatflow/workflow POST)。 + 核心逻辑:通过则可选自动 is_active=True。 + Returns: + passed、request_url、output_info、analysis、http_status、tested_at 等。 + Raises: + NotFoundError: Agent 不存在。 + """ + agent = db.session.get(Agent, agent_id) + if not agent: + raise NotFoundError('Not found') + tested_at = datetime.utcnow().isoformat() + if agent.type == 'iframe': + return _test_iframe_agent(agent, tested_at) + return _test_dify_agent(agent, tested_at) + + +def _test_iframe_agent(agent: Agent, tested_at: str) -> dict[str, Any]: + iframe_url = (agent.extra_config or {}).get('iframe_url') + if not iframe_url: + return { + 'passed': False, + 'request_url': '', + 'output_info': 'Missing iframe_url in extra_config.', + 'analysis': '测试失败:未配置 iframe URL。', + 'http_status': 0, + 'tested_at': tested_at, + } + try: + resp = requests.get(iframe_url, timeout=(5, 15), allow_redirects=True) + passed = 200 <= resp.status_code < 400 + if passed and (not agent.is_active): + agent.is_active = True + db.session.commit() + return { + 'passed': passed, + 'request_url': iframe_url, + 'output_info': f'HTTP {resp.status_code}; response length={len(resp.text)}', + 'analysis': '测试通过:iframe 地址可访问。' if passed else '测试失败:iframe 地址不可访问或返回异常状态。', + 'http_status': resp.status_code, + 'tested_at': tested_at, + } + except requests.RequestException as exc: + return { + 'passed': False, + 'request_url': iframe_url, + 'output_info': str(exc), + 'analysis': '测试失败:请求 iframe 地址异常。', + 'http_status': 0, + 'tested_at': tested_at, + } + + +def _test_dify_agent(agent: Agent, tested_at: str) -> dict[str, Any]: + if not agent.dify_api_key: + return { + 'passed': False, + 'request_url': '', + 'output_info': 'Missing dify_api_key.', + 'analysis': '测试失败:未配置 API Key。', + 'http_status': 0, + 'tested_at': tested_at, + } + base_url = (agent.api_base_url or Config.DIFY_API_BASE or '').rstrip('/') + if not base_url: + return { + 'passed': False, + 'request_url': '', + 'output_info': 'Missing api_base_url.', + 'analysis': '测试失败:未配置 API Base URL。', + 'http_status': 0, + 'tested_at': tested_at, + } + extra_config = agent.extra_config or {} + dify_app_type = str(extra_config.get('dify_app_type') or 'chatflow').strip().lower() + if dify_app_type not in ('chatflow', 'workflow'): + dify_app_type = 'chatflow' + if dify_app_type == 'workflow': + request_url = DifyService._build_workflow_url(base_url) + payload = { + 'inputs': {'query': '系统连通性测试,请简短回复OK。'}, + 'response_mode': 'blocking', + 'user': 'admin_test', + } + else: + request_url = DifyService._build_chat_messages_url(base_url) + payload = { + 'inputs': {}, + 'query': '系统连通性测试,请简短回复OK。', + 'response_mode': 'blocking', + 'user': 'admin_test', + } + headers = {'Authorization': f'Bearer {agent.dify_api_key}', 'Content-Type': 'application/json'} + try: + resp = requests.post(request_url, headers=headers, json=payload, timeout=(5, 25)) + raw_text = (resp.text or '')[:4000] + output_info = raw_text + passed = False + analysis = f'测试失败:HTTP {resp.status_code}。' + if dify_app_type == 'workflow' and 200 <= resp.status_code < 300: + passed = True + analysis = '测试通过:Workflow 接口可访问且认证通过。' + try: + data = resp.json() + if dify_app_type == 'workflow': + passed, output_info, analysis = _parse_workflow_test_response(resp, data, output_info, analysis) + else: + passed, output_info, analysis = _parse_chatflow_test_response(resp, data, output_info, analysis, passed) + except ValueError: + if resp.ok and raw_text.strip(): + passed = True + analysis = ( + '测试通过:Workflow 接口可访问并返回了文本内容。' + if dify_app_type == 'workflow' + else '测试通过:Chatflow 接口可访问并返回了文本内容。' + ) + if passed and (not agent.is_active): + agent.is_active = True + db.session.commit() + return { + 'passed': passed, + 'dify_app_type': dify_app_type, + 'request_url': request_url, + 'output_info': output_info, + 'analysis': analysis, + 'http_status': resp.status_code, + 'tested_at': tested_at, + } + except requests.RequestException as exc: + return { + 'passed': False, + 'dify_app_type': dify_app_type, + 'request_url': request_url, + 'output_info': str(exc), + 'analysis': '测试失败:请求异常(网络、超时或认证问题)。', + 'http_status': 0, + 'tested_at': tested_at, + } + + +def _parse_workflow_test_response(resp, data, output_info: str, analysis: str) -> tuple[bool, str, str]: + passed = 200 <= resp.status_code < 300 + workflow_data = data.get('data') if isinstance(data, dict) else None + outputs = workflow_data.get('outputs') if isinstance(workflow_data, dict) else None + status = workflow_data.get('status') if isinstance(workflow_data, dict) else None + message = data.get('message') if isinstance(data, dict) else None + if isinstance(outputs, dict) and outputs: + output_info = str(outputs)[:4000] + elif isinstance(message, str) and message.strip(): + output_info = message[:4000] + elif isinstance(data, dict): + output_info = str(data)[:4000] + if resp.ok and status in ('succeeded', 'success'): + analysis = '测试通过:Workflow 接口可访问且业务返回成功。' + elif resp.ok: + analysis = '测试通过:Workflow 接口可访问且认证通过(本次未返回业务成功状态)。' + return passed, output_info, analysis + + +def _parse_chatflow_test_response(resp, data, output_info: str, analysis: str, passed: bool) -> tuple[bool, str, str]: + answer = data.get('answer') if isinstance(data, dict) else None + if answer: + output_info = str(answer)[:4000] + if resp.ok and isinstance(answer, str) and answer.strip(): + passed = True + analysis = '测试通过:Chatflow 接口可访问且已返回回答。' + elif resp.ok: + analysis = '测试未通过:Chatflow 接口可访问,但未返回有效回答。' + else: + message = data.get('message') if isinstance(data, dict) else None + if message: + output_info = str(message)[:4000] + return passed, output_info, analysis + + +def update_agent_permissions(agent_id: int, user_ids: list[int]) -> None: + """ + 将 Agent 的授权用户集合设为 user_ids(增量 add/remove)。 + Raises: + NotFoundError: Agent 不存在。 + """ + agent = db.session.get(Agent, agent_id) + if not agent: + raise NotFoundError('Not found') + current_users = db.session.query(User).filter(User.agents.contains(agent)).all() + current_user_ids = {u.id for u in current_users} + new_user_ids = set(user_ids) + to_add = new_user_ids - current_user_ids + if to_add: + users_to_add = db.session.query(User).filter(User.id.in_(to_add)).all() + for user in users_to_add: + user.agents.append(agent) + to_remove = current_user_ids - new_user_ids + if to_remove: + users_to_remove = db.session.query(User).filter(User.id.in_(to_remove)).all() + for user in users_to_remove: + user.agents.remove(agent) + db.session.commit() diff --git a/backend/app/services/admin/announcement_service.py b/backend/app/services/admin/announcement_service.py new file mode 100644 index 00000000..437caa7a --- /dev/null +++ b/backend/app/services/admin/announcement_service.py @@ -0,0 +1,93 @@ +""" +backend/app/services/admin/announcement_service.py + +用途:系统公告 CRUD 与活跃公告列表(管理端 + 工作台/登录页只读)。 +依赖:models.Announcement、app.core.errors。 +逻辑:api/admin/announcements.py 管理 CRUD;api/workspace/announcements.py 只读活跃列表。 +""" +from __future__ import annotations + +from typing import Any + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import Announcement + + +def serialize_announcement(ann: Announcement, *, include_active: bool = False) -> dict: + """Announcement ORM → API dict。""" + row = { + 'id': ann.id, + 'title': ann.title, + 'content': ann.content, + 'created_at': ann.created_at.isoformat() if ann.created_at else None, + } + if include_active: + row['is_active'] = bool(ann.is_active) + return row + + +def list_active_announcements() -> list[dict]: + """返回已发布(is_active)公告,供工作台/登录页展示。""" + rows = ( + db.session.query(Announcement) + .filter(Announcement.is_active.is_(True)) + .order_by(Announcement.created_at.desc()) + .all() + ) + return [serialize_announcement(a) for a in rows] + + +def list_announcements() -> list[dict]: + """管理端列表:含全部公告及 is_active 字段。""" + rows = db.session.query(Announcement).order_by(Announcement.created_at.desc()).all() + return [serialize_announcement(a, include_active=True) for a in rows] + + +def create_announcement(data: dict[str, Any]) -> dict: + """ + 创建公告。 + Returns: + { id, message }。 + Raises: + ValidationError: title/content 缺失。 + """ + if not data.get('title') or not data.get('content'): + raise ValidationError('Missing fields') + ann = Announcement( + title=data['title'], + content=data['content'], + is_active=bool(data.get('is_active', True)), + ) + db.session.add(ann) + db.session.commit() + return {'message': 'Created', 'id': ann.id} + + +def update_announcement(announcement_id: int, data: dict[str, Any]) -> dict: + """ + 更新公告 title/content(及可选 is_active)。 + Raises: + NotFoundError: 公告不存在。 + ValidationError: title/content 缺失。 + """ + if not data.get('title') or not data.get('content'): + raise ValidationError('Missing fields') + ann = db.session.get(Announcement, announcement_id) + if not ann: + raise NotFoundError('Not found') + ann.title = data['title'] + ann.content = data['content'] + if 'is_active' in data: + ann.is_active = bool(data['is_active']) + db.session.commit() + return {'message': 'Updated'} + + +def delete_announcement(announcement_id: int) -> dict: + """删除公告(不存在时静默成功)。""" + ann = db.session.get(Announcement, announcement_id) + if ann: + db.session.delete(ann) + db.session.commit() + return {'message': 'Deleted'} diff --git a/backend/app/services/admin/dashboard_service.py b/backend/app/services/admin/dashboard_service.py index 9790f589..1066c310 100644 --- a/backend/app/services/admin/dashboard_service.py +++ b/backend/app/services/admin/dashboard_service.py @@ -1,5 +1,60 @@ """ backend/app/services/admin/dashboard_service.py -用途:管理后台仪表盘统计聚合。 +用途:管理后台仪表盘统计与侧栏角标聚合。 +依赖:models、SQLAlchemy func。 +逻辑:由 api/admin/dashboard.py 调用。 """ +from __future__ import annotations + +from sqlalchemy import func + +from app import db +from app.models import Agent, ChatLog, Feedback, PermissionRequest, User + + +def compute_dashboard_summary() -> dict: + """ + 聚合仪表盘四张卡片所需的统计值(仅 COUNT/AVG,不返回列表)。 + Returns: + agent_count、user_count、total_conversations、avg_score。 + """ + total_users = db.session.query(func.count(User.id)).scalar() or 0 + active_agents = db.session.query(func.count(Agent.id)).filter_by(is_active=True).scalar() or 0 + total_conversations = db.session.query(func.count(ChatLog.id)).scalar() or 0 + avg_score = db.session.query(func.avg(Feedback.score)).scalar() + avg_score = round(float(avg_score), 1) if avg_score else 0.0 + return { + 'agent_count': active_agents, + 'user_count': total_users, + 'total_conversations': total_conversations, + 'avg_score': avg_score, + } + + +def compute_dashboard_badges() -> dict: + """ + 聚合侧栏角标所需的待办数量。 + Returns: + pending_approvals、pending_requests。 + """ + pending_approvals = db.session.query(func.count(User.id)).filter_by(status='pending').scalar() or 0 + pending_requests = db.session.query(func.count(PermissionRequest.id)).filter_by(status='pending').scalar() or 0 + return { + 'pending_approvals': pending_approvals, + 'pending_requests': pending_requests, + } + + +def compute_legacy_dashboard_stats() -> dict: + """遗留 /dashboard 接口响应(summary + badges 字段名兼容早期前端)。""" + summary = compute_dashboard_summary() + badges = compute_dashboard_badges() + return { + 'total_users': summary['user_count'], + 'active_agents': summary['agent_count'], + 'total_conversations': summary['total_conversations'], + 'avg_score': summary['avg_score'], + 'pending_approvals': badges['pending_approvals'], + 'pending_requests': badges['pending_requests'], + } diff --git a/backend/app/services/admin/database_admin_service.py b/backend/app/services/admin/database_admin_service.py new file mode 100644 index 00000000..5c037e42 --- /dev/null +++ b/backend/app/services/admin/database_admin_service.py @@ -0,0 +1,99 @@ +""" +backend/app/services/admin/database_admin_service.py + +用途:管理后台通用数据表浏览与 chat_logs 批量删除。 +依赖:models、report_service(chat_logs 报表复用)。 +逻辑:由 api/admin/database.py 调用。 +""" +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from sqlalchemy import func + +from app import db +from app.core.errors import ValidationError +from app.models import ( + Agent, + ChatLog, + Department, + Feedback, + PermissionRequest, + QuickQuestion, + User, + UserDefaultAgent, + UserFavoriteAgent, + UserHomepageConfig, +) +from app.services.admin import report_service + +ADMIN_TABLE_MODEL_MAP = { + 'users': User, + 'agents': Agent, + 'chat_logs': ChatLog, + 'feedbacks': Feedback, + 'permission_requests': PermissionRequest, + 'departments': Department, + 'quick_questions': QuickQuestion, + 'user_homepage_configs': UserHomepageConfig, + 'user_favorite_agents': UserFavoriteAgent, + 'user_default_agents': UserDefaultAgent, +} + + +def _serialize_model_row(item) -> dict: + row = {} + for col in item.__table__.columns: + val = getattr(item, col.name) + if isinstance(val, datetime): + val = val.isoformat() + row[col.name] = val + return row + + +def get_table_data(table: str, query_params: dict[str, str]) -> list[dict]: + """ + 返回管理报表表数据(最多 100 行)。 + chat_logs 走专用报表 JOIN 逻辑。 + """ + if table == 'chat_logs': + return report_service.list_chat_logs_report(query_params) + model = ADMIN_TABLE_MODEL_MAP.get(table) + if not model: + raise ValidationError('Invalid table') + query = db.session.query(model) + for key, value in query_params.items(): + if hasattr(model, key) and value: + col = getattr(model, key) + query = query.filter(col.cast(db.String).ilike(f'%{value}%')) + items = query.limit(100).all() + return [_serialize_model_row(item) for item in items] + + +def get_table_count(table: str, query_params: dict[str, str]) -> dict: + """返回表行数;chat_logs 使用报表筛选。""" + if table == 'chat_logs': + return report_service.count_chat_logs_report(query_params) + model = ADMIN_TABLE_MODEL_MAP.get(table) + if not model: + raise ValidationError('Invalid table') + total = db.session.query(func.count(model.id)).scalar() + return {'table': table, 'total': int(total or 0)} + + +def batch_delete_chat_logs(raw_ids: list[Any]) -> dict: + """按 id 批量删除 ChatLog。""" + if not isinstance(raw_ids, list) or not raw_ids: + raise ValidationError('ids is required') + ids = [] + for value in raw_ids: + try: + ids.append(int(value)) + except (TypeError, ValueError): + continue + if not ids: + raise ValidationError('No valid ids') + cnt = db.session.query(ChatLog).filter(ChatLog.id.in_(ids)).delete(synchronize_session=False) + db.session.commit() + return {'deleted_count': cnt} diff --git a/backend/app/services/admin/department_service.py b/backend/app/services/admin/department_service.py index 8bf71d71..7d45ffab 100644 --- a/backend/app/services/admin/department_service.py +++ b/backend/app/services/admin/department_service.py @@ -1,5 +1,91 @@ """ backend/app/services/admin/department_service.py -用途:部门 CRUD。 +用途:管理端部门 CRUD 业务编排。 +依赖:models.Department、app.core.errors。 +逻辑:由 api/admin/departments.py 调用。 """ +from __future__ import annotations + +from typing import Any + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import Department + + +def serialize_department(dept: Department) -> dict: + """部门 ORM → API dict。""" + return { + 'id': dept.id, + 'name': dept.name, + 'code': dept.code, + 'company': dept.company, + 'description': dept.description, + } + + +def list_departments() -> list[dict]: + """返回全部部门(按 name 升序)。""" + depts = db.session.query(Department).order_by(Department.name.asc()).all() + return [serialize_department(d) for d in depts] + + +def create_department(data: dict[str, Any]) -> dict: + """ + 创建部门。 + Returns: + { id, name }。 + Raises: + ValidationError: name 缺失或 name/code 重复。 + """ + if not data.get('name'): + raise ValidationError('Name is required') + if db.session.query(Department).filter_by(name=data['name']).first(): + raise ValidationError('Name exists') + if data.get('code') and db.session.query(Department).filter_by(code=data['code']).first(): + raise ValidationError('Code exists') + dept = Department( + name=data['name'], + code=data.get('code'), + company=data.get('company'), + description=data.get('description'), + ) + db.session.add(dept) + db.session.commit() + return {'id': dept.id, 'name': dept.name} + + +def update_department(dept_id: int, data: dict[str, Any]) -> None: + """ + 更新部门字段。 + Raises: + NotFoundError: 部门不存在。 + ValidationError: name/code 与其它记录冲突。 + """ + dept = db.session.get(Department, dept_id) + if not dept: + raise NotFoundError('Not found') + if 'name' in data: + if db.session.query(Department).filter(Department.name == data['name'], Department.id != dept_id).first(): + raise ValidationError('Name exists') + dept.name = data['name'] + if 'code' in data: + if data['code'] and db.session.query(Department).filter( + Department.code == data['code'], Department.id != dept_id + ).first(): + raise ValidationError('Code exists') + dept.code = data['code'] + if 'company' in data: + dept.company = data['company'] + if 'description' in data: + dept.description = data['description'] + db.session.commit() + + +def delete_department(dept_id: int) -> None: + """删除部门(不存在时静默成功)。""" + dept = db.session.get(Department, dept_id) + if dept: + db.session.delete(dept) + db.session.commit() diff --git a/backend/app/services/admin/faq_service.py b/backend/app/services/admin/faq_service.py new file mode 100644 index 00000000..018964e9 --- /dev/null +++ b/backend/app/services/admin/faq_service.py @@ -0,0 +1,237 @@ +""" +backend/app/services/admin/faq_service.py + +用途:全局常用问题(QuickQuestion)与热点 FAQ 候选管理。 +依赖:models、faq_kb_invalidation、hot_faq_* services。 +逻辑:由 api/admin/quick_questions.py、faq_candidates.py 调用。 +""" +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import Agent, KbDocument, QuickQuestion + + +def parse_aliases(raw_aliases) -> list[str]: + """解析别名列表,支持 JSON 数组或换行分隔字符串。""" + if raw_aliases is None: + return [] + if isinstance(raw_aliases, list): + items = [str(item).strip() for item in raw_aliases if str(item).strip()] + elif isinstance(raw_aliases, str): + items = [line.strip() for line in raw_aliases.splitlines() if line.strip()] + else: + return [] + seen: set[str] = set() + result: list[str] = [] + for item in items: + if item not in seen: + seen.add(item) + result.append(item) + return result + + +def parse_expires_at(raw_value) -> datetime | None: + """解析 FAQ 过期时间 ISO 字符串。""" + if not raw_value: + return None + text = str(raw_value).strip() + if not text: + return None + try: + return datetime.fromisoformat(text.replace('Z', '+00:00')).replace(tzinfo=None) + except ValueError as exc: + raise ValidationError('Invalid expires_at format') from exc + + +def serialize_quick_question( + q: QuickQuestion, + agent_name: str, + stale_kb_document: KbDocument | None = None, +) -> dict: + """序列化全局常用问题供管理端展示。""" + return { + 'id': q.id, + 'title': q.title, + 'question': q.question, + 'answer': q.answer, + 'aliases': q.aliases if isinstance(q.aliases, list) else [], + 'cache_enabled': bool(q.cache_enabled), + 'is_enabled': bool(q.is_enabled), + 'hit_count': q.hit_count or 0, + 'agent_id': q.agent_id, + 'agent_name': agent_name, + 'sort_order': q.sort_order, + 'expires_at': q.expires_at.isoformat() if q.expires_at else None, + 'updated_at': q.updated_at.isoformat() if getattr(q, 'updated_at', None) else None, + 'source_kb_document_ids': q.source_kb_document_ids if isinstance(q.source_kb_document_ids, list) else [], + 'stale_at': q.stale_at.isoformat() if getattr(q, 'stale_at', None) else None, + 'stale_reason': q.stale_reason, + 'stale_kb_document_id': q.stale_kb_document_id, + 'stale_kb_document_title': stale_kb_document.title if stale_kb_document else None, + } + + +def apply_quick_question_payload(qq: QuickQuestion, data: dict, *, require_answer: bool = False) -> None: + """将请求体字段写入 QuickQuestion 实例。""" + if 'title' in data: + qq.title = str(data['title']).strip() + if 'question' in data: + qq.question = str(data['question']).strip() + if 'agent_id' in data: + qq.agent_id = data['agent_id'] + if 'sort_order' in data: + qq.sort_order = data.get('sort_order', 0) + if 'answer' in data: + qq.answer = str(data['answer']).strip() or None + if 'aliases' in data: + qq.aliases = parse_aliases(data['aliases']) + if 'cache_enabled' in data: + qq.cache_enabled = bool(data['cache_enabled']) + if 'is_enabled' in data: + qq.is_enabled = bool(data['is_enabled']) + if 'expires_at' in data: + qq.expires_at = parse_expires_at(data['expires_at']) + if 'retriever_resources' in data and isinstance(data.get('retriever_resources'), list): + from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq + + apply_retriever_resources_to_faq(qq, data['retriever_resources']) + if data.get('clear_stale'): + from app.services.faq_kb_invalidation import clear_faq_stale + + clear_faq_stale(qq) + + if qq.cache_enabled and not str(qq.answer or '').strip(): + raise ValidationError('启用 FAQ 缓存时必须填写标准答案') + if require_answer and (not qq.title or not qq.question or not qq.agent_id): + raise ValidationError('Missing required fields') + + +def list_quick_questions(*, stale_only: bool = False) -> list[dict]: + """列出全局常用问题(user_id IS NULL)。""" + query = ( + db.session.query(QuickQuestion) + .filter(QuickQuestion.user_id.is_(None)) + .order_by(QuickQuestion.sort_order.asc(), QuickQuestion.id.asc()) + ) + if stale_only: + query = query.filter(QuickQuestion.stale_at.isnot(None)) + rows = [] + for q in query.all(): + agent = db.session.get(Agent, q.agent_id) + stale_doc = db.session.get(KbDocument, q.stale_kb_document_id) if q.stale_kb_document_id else None + rows.append(serialize_quick_question(q, agent.name if agent else 'Unknown', stale_doc)) + return rows + + +def create_quick_question(data: dict[str, Any]) -> dict: + """创建全局 QuickQuestion。""" + qq = QuickQuestion(user_id=None) + apply_quick_question_payload(qq, data, require_answer=True) + if isinstance(data.get('retriever_resources'), list): + from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq + + apply_retriever_resources_to_faq(qq, data['retriever_resources']) + qq.updated_at = datetime.utcnow() + db.session.add(qq) + db.session.commit() + return {'id': qq.id} + + +def update_quick_question(question_id: int, data: dict[str, Any]) -> None: + """更新全局 QuickQuestion。""" + qq = db.session.get(QuickQuestion, question_id) + if not qq or qq.user_id is not None: + raise NotFoundError('Not found') + apply_quick_question_payload(qq, data) + qq.updated_at = datetime.utcnow() + db.session.commit() + + +def delete_quick_question(question_id: int) -> None: + """删除 QuickQuestion(不存在时静默成功)。""" + qq = db.session.get(QuickQuestion, question_id) + if qq: + db.session.delete(qq) + db.session.commit() + + +def list_faq_candidates(*, agent_id: int | None = None) -> dict: + """列出热点 FAQ 候选及统计。""" + from app.services.hot_faq_aggregator import HotFaqAggregator + from app.services.hot_faq_candidate_store import HotFaqCandidateStore + + items = HotFaqCandidateStore.list_candidates(agent_id) + return { + 'items': items, + 'stats': HotFaqCandidateStore.summarize(items), + 'rules': HotFaqAggregator.get_rules_document(), + } + + +def refresh_faq_candidates(*, agent_id: int | None, dry_run: bool) -> dict: + """手动触发离线热点聚合。""" + from app.services.hot_faq_aggregator import HotFaqAggregator + + return HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run) + + +def promote_faq_candidate(data: dict[str, Any]) -> dict: + """将热点候选晋升为全局 QuickQuestion。""" + from app.services.faq_kb_invalidation import apply_retriever_resources_to_faq + from app.services.faq_text_utils import normalize_faq_query + from app.services.hot_faq_candidate_store import HotFaqCandidateStore + + agent_id = data.get('agent_id') + q_norm = normalize_faq_query(str(data.get('q_norm') or '')) + if not agent_id or not q_norm: + raise ValidationError('agent_id and q_norm are required') + + candidate = HotFaqCandidateStore.get_candidate(int(agent_id), q_norm) + if not candidate: + raise NotFoundError('FAQ candidate not found') + + title = str(data.get('title') or candidate.get('canonical_query') or q_norm).strip()[:100] + question = str(candidate.get('canonical_query') or q_norm).strip() + answer = str(candidate.get('answer') or '').strip() + if not answer: + raise ValidationError('Candidate has no answer') + + aliases = [q for q in (candidate.get('sample_queries') or []) if normalize_faq_query(q) != q_norm] + retriever_resources = candidate.get('retriever_resources') if isinstance(candidate.get('retriever_resources'), list) else None + qq = QuickQuestion( + user_id=None, + agent_id=int(agent_id), + title=title, + question=question, + answer=answer, + aliases=aliases or None, + cache_enabled=True, + is_enabled=True, + retriever_resources=retriever_resources, + sort_order=int(data.get('sort_order') or 0), + updated_at=datetime.utcnow(), + ) + apply_retriever_resources_to_faq(qq, retriever_resources) + db.session.add(qq) + db.session.flush() + if not HotFaqCandidateStore.mark_promoted(int(agent_id), q_norm, qq.id): + db.session.rollback() + raise NotFoundError('FAQ candidate not found') + db.session.commit() + return {'id': qq.id, 'status': 'ok'} + + +def dismiss_faq_candidate(*, agent_id: int, q_norm: str) -> dict: + """忽略热点 FAQ 候选。""" + from app.services.faq_text_utils import normalize_faq_query + from app.services.hot_faq_candidate_store import HotFaqCandidateStore + + normalized = normalize_faq_query(q_norm) + if not agent_id or not normalized: + raise ValidationError('agent_id and q_norm are required') + HotFaqCandidateStore.dismiss(int(agent_id), normalized) + return {'status': 'ok'} diff --git a/backend/app/services/admin/guide_service.py b/backend/app/services/admin/guide_service.py new file mode 100644 index 00000000..45867c1e --- /dev/null +++ b/backend/app/services/admin/guide_service.py @@ -0,0 +1,122 @@ +""" +backend/app/services/admin/guide_service.py + +用途:Agent 引导资料(视频/PDF/图片)CRUD 与 MinIO 上传。 +依赖:models.AgentGuide、minio_service。 +逻辑:由 api/admin/guides.py 调用。 +""" +from __future__ import annotations + +from typing import Any + +from werkzeug.datastructures import FileStorage + +from app import db +from app.core.errors import AppError, NotFoundError, ValidationError +from app.models import AgentGuide +from app.services.minio_service import minio_service + + +def _infer_file_type(content_type: str | None) -> str: + ct = str(content_type or '') + if ct.startswith('video'): + return 'video' + if 'pdf' in ct: + return 'pdf' + return 'image' + + +def serialize_guide(guide: AgentGuide) -> dict: + """AgentGuide ORM → API dict(含公开 URL)。""" + return { + 'id': guide.id, + 'agent_id': guide.agent_id, + 'file_name': guide.file_name, + 'file_type': guide.file_type, + 'file_path': guide.file_path, + 'file_url': minio_service.get_public_url(guide.file_path), + 'file_size': guide.file_size, + 'remark': guide.remark, + 'sort_order': guide.sort_order, + 'status': guide.status, + 'created_at': guide.created_at.isoformat() if guide.created_at else None, + } + + +def upload_guide_file(file_storage: FileStorage | None) -> dict: + """ + 上传引导文件至 MinIO。 + Returns: + file_path、file_name、file_size、file_type。 + Raises: + ValidationError: 无文件。 + AppError: 上传失败。 + """ + if not file_storage or file_storage.filename == '': + raise ValidationError('No selected file' if file_storage else 'No file part') + content_type = file_storage.content_type + file_size = len(file_storage.read()) + file_storage.seek(0) + try: + object_name = minio_service.upload_file(file_storage, file_storage.filename, content_type, file_size) + return { + 'file_path': object_name, + 'file_name': file_storage.filename, + 'file_size': file_size, + 'file_type': _infer_file_type(content_type), + } + except Exception as exc: + raise AppError(f'Upload failed: {str(exc)}') + + +def list_guides(*, agent_id: int | None = None) -> list[dict]: + """按 agent_id 可选过滤返回引导列表。""" + query = db.session.query(AgentGuide) + if agent_id is not None: + query = query.filter_by(agent_id=agent_id) + guides = query.order_by(AgentGuide.sort_order).all() + return [serialize_guide(g) for g in guides] + + +def create_guide(data: dict[str, Any], *, created_by_id: int | None) -> dict: + """创建 AgentGuide 记录。""" + guide = AgentGuide( + agent_id=data['agent_id'], + file_name=data['file_name'], + file_type=data['file_type'], + file_path=data['file_path'], + file_size=data.get('file_size'), + remark=data.get('remark'), + sort_order=data.get('sort_order', 0), + status=data.get('status', 1), + created_by=created_by_id, + ) + db.session.add(guide) + db.session.commit() + return {'id': guide.id} + + +def update_guide(guide_id: int, data: dict[str, Any]) -> None: + """更新引导元数据。""" + guide = db.session.get(AgentGuide, guide_id) + if not guide: + raise NotFoundError('Guide not found') + if 'file_name' in data: + guide.file_name = data['file_name'] + if 'remark' in data: + guide.remark = data['remark'] + if 'sort_order' in data: + guide.sort_order = data['sort_order'] + if 'status' in data: + guide.status = data['status'] + db.session.commit() + + +def delete_guide(guide_id: int) -> None: + """删除引导并移除 MinIO 对象。""" + guide = db.session.get(AgentGuide, guide_id) + if not guide: + raise NotFoundError('Guide not found') + minio_service.delete_file(guide.file_path) + db.session.delete(guide) + db.session.commit() diff --git a/backend/app/services/admin/permission_service.py b/backend/app/services/admin/permission_service.py index d470ec7e..a6287447 100644 --- a/backend/app/services/admin/permission_service.py +++ b/backend/app/services/admin/permission_service.py @@ -1,5 +1,174 @@ """ backend/app/services/admin/permission_service.py -用途:权限申请、批量授权业务逻辑。 +用途:用户 Agent 权限批量/单用户更新,以及权限申请审批业务逻辑。 +依赖:models、wecom_notify.send_wecom_event_message。 +逻辑:由 api/admin/permissions.py 调用;users 路由 /users//permissions 亦委托本模块。 """ +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import Agent, PermissionRequest, User +from app.services.wecom_notify import send_wecom_event_message + +_BATCH_ACTION_LABELS = {'add': '新增', 'remove': '移除', 'set': '重置为'} + + +def serialize_permission_request(req: PermissionRequest) -> dict: + """PermissionRequest ORM → 管理端列表 JSON。""" + return { + 'id': req.id, + 'user_id': req.user_id, + 'agent_id': req.agent_id, + 'reason': req.reason, + 'status': req.status, + 'created_at': req.created_at.isoformat(), + } + + +def _load_users_and_agents(user_ids: list[Any], agent_ids: list[Any]) -> tuple[list[User], list[Agent]]: + users = db.session.query(User).filter(User.id.in_(user_ids)).all() + agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all() + return users, agents + + +def _apply_user_agent_action(user: User, agents: list[Agent], action: str) -> None: + """对单个用户执行 add / remove / set 权限变更。""" + if action == 'set': + user.agents = agents + elif action == 'add': + for agent in agents: + if agent not in user.agents: + user.agents.append(agent) + elif action == 'remove': + for agent in agents: + if agent in user.agents: + user.agents.remove(agent) + + +def _notify_batch_permission_update(user: User, agents: list[Agent], action: str) -> None: + """批量权限变更后向已绑定企微的用户推送通知。""" + if not user.wecom_userid: + return + action_label = _BATCH_ACTION_LABELS.get(action, action) + agent_names = '、'.join([a.name for a in agents]) if agents else '无' + send_wecom_event_message( + event_type='permission_batch_updated', + user=user, + title='应用权限已更新', + content=f'管理员已{action_label}你的应用权限:{agent_names}', + jump_path='/workspace', + ) + + +def batch_update_permissions(data: dict[str, Any]) -> dict: + """ + 批量更新多用户的 Agent 权限(add / remove / set)。 + Returns: + { status, updated_count }。 + Raises: + ValidationError: 未选择用户。 + """ + user_ids = data.get('user_ids', []) + agent_ids = data.get('agent_ids', []) + action = data.get('action', 'add') + if not user_ids: + raise ValidationError('No users selected') + + users, agents = _load_users_and_agents(user_ids, agent_ids) + if not agents and action != 'set': + if action == 'remove': + return {'status': 'ok', 'updated_count': 0} + + for user in users: + _apply_user_agent_action(user, agents, action) + _notify_batch_permission_update(user, agents, action) + + db.session.commit() + return {'status': 'ok', 'updated_count': len(users)} + + +def update_user_permissions(user_id: int, data: dict[str, Any]) -> dict: + """ + 将指定用户的 Agent 权限重置为 agent_ids 列表(全量替换)。 + Returns: + { status }。 + Raises: + NotFoundError: 用户不存在。 + """ + user = db.session.get(User, user_id) + if not user: + raise NotFoundError('Not found') + agent_ids = data.get('agent_ids', []) + agents = db.session.query(Agent).filter(Agent.id.in_(agent_ids)).all() + user.agents = agents + db.session.commit() + return {'status': 'ok'} + + +def list_permission_requests() -> list[dict]: + """返回全部权限申请(按 created_at 降序)。""" + reqs = ( + db.session.query(PermissionRequest) + .order_by(PermissionRequest.created_at.desc()) + .all() + ) + return [serialize_permission_request(r) for r in reqs] + + +def approve_permission_request(request_id: int) -> dict: + """ + 批准权限申请:更新状态并将 Agent 加入用户权限。 + Raises: + NotFoundError: 申请不存在。 + """ + req = db.session.get(PermissionRequest, request_id) + if not req: + raise NotFoundError('Not found') + + req.status = 'approved' + req.reviewed_at = datetime.utcnow() + user = db.session.get(User, req.user_id) + agent = db.session.get(Agent, req.agent_id) + if user and agent and (agent not in user.agents): + user.agents.append(agent) + if user and user.wecom_userid: + send_wecom_event_message( + event_type='permission_request_approved', + user=user, + title='权限申请已通过', + content=f'你申请的应用权限已通过:{(agent.name if agent else req.agent_id)}', + jump_path='/workspace', + ) + db.session.commit() + return {'status': 'ok'} + + +def reject_permission_request(request_id: int) -> dict: + """ + 拒绝权限申请并通知用户(若已绑定企微)。 + Raises: + NotFoundError: 申请不存在。 + """ + req = db.session.get(PermissionRequest, request_id) + if not req: + raise NotFoundError('Not found') + + req.status = 'rejected' + req.reviewed_at = datetime.utcnow() + user = db.session.get(User, req.user_id) + agent = db.session.get(Agent, req.agent_id) + if user and user.wecom_userid: + send_wecom_event_message( + event_type='permission_request_rejected', + user=user, + title='权限申请未通过', + content=f'你申请的应用权限未通过:{(agent.name if agent else req.agent_id)}', + jump_path='/workspace', + ) + db.session.commit() + return {'status': 'ok'} diff --git a/backend/app/services/admin/report_service.py b/backend/app/services/admin/report_service.py new file mode 100644 index 00000000..e2fae2de --- /dev/null +++ b/backend/app/services/admin/report_service.py @@ -0,0 +1,194 @@ +""" +backend/app/services/admin/report_service.py + +用途:管理后台报表(使用分析、反馈、聊天日志)数据聚合。 +依赖:models、SQLAlchemy func。 +逻辑:由 api/admin/reports.py、database_admin_service 调用。 +""" +from __future__ import annotations + +import math +from datetime import datetime +from typing import Any + +from sqlalchemy import desc, func + +from app import db +from app.models import Agent, ChatLog, Feedback, GeneralFeedback, User + +USAGE_BY_USER_TOP_LIMIT = 50 + + +def build_usage_report(*, user_page: int, user_page_size: int) -> dict: + """聊天使用分析报表。""" + total = db.session.query(ChatLog).count() + by_agent = ( + db.session.query(Agent.name, func.count(ChatLog.id)) + .join(ChatLog) + .group_by(Agent.name) + .order_by(desc(func.count(ChatLog.id)), Agent.name) + .all() + ) + user_page = max(1, user_page) + user_page_size = max(1, min(user_page_size, USAGE_BY_USER_TOP_LIMIT)) + by_user_top = ( + db.session.query(User.username, func.count(ChatLog.id)) + .join(ChatLog) + .group_by(User.username) + .order_by(desc(func.count(ChatLog.id)), User.username) + .limit(USAGE_BY_USER_TOP_LIMIT) + .all() + ) + user_total = len(by_user_top) + user_pages = max(1, math.ceil(user_total / user_page_size)) if user_total else 1 + user_page = min(user_page, user_pages) + offset = (user_page - 1) * user_page_size + by_user_page = by_user_top[offset:offset + user_page_size] + return { + 'total': total, + 'by_user': [{'username': u, 'count': c} for u, c in by_user_page], + 'by_agent': [{'agent': a, 'count': c} for a, c in by_agent], + 'user_total': user_total, + 'user_page': user_page, + 'user_page_size': user_page_size, + 'user_pages': user_pages, + 'user_top_limit': USAGE_BY_USER_TOP_LIMIT, + } + + +def build_feedback_report() -> dict: + """反馈评分分布报表。""" + total = db.session.query(Feedback).count() + avg = db.session.query(func.avg(Feedback.score)).scalar() or 0 + dist = db.session.query(Feedback.score, func.count(Feedback.id)).group_by(Feedback.score).all() + return { + 'total': total, + 'avg_score': float(avg), + 'distribution': [{'score': s, 'count': c} for s, c in dist], + } + + +def _apply_general_feedback_filters(query, query_params: dict[str, str]): + reserved = {'limit', 'offset', 'page', 'page_size'} + for key, value in query_params.items(): + if key in reserved or not value: + continue + if hasattr(GeneralFeedback, key): + col = getattr(GeneralFeedback, key) + elif key == 'real_name': + col = User.real_name + elif key == 'department': + col = User.department + else: + continue + query = query.filter(col.cast(db.String).ilike(f'%{value}%')) + return query + + +def list_general_feedbacks_report(query_params: dict[str, str]) -> list[dict]: + """通用反馈列表(报表页)。""" + query = ( + db.session.query( + GeneralFeedback, + User.real_name.label('real_name'), + User.department.label('department'), + ) + .outerjoin(User, User.id == GeneralFeedback.user_id) + ) + query = _apply_general_feedback_filters(query, query_params) + query = query.order_by(desc(GeneralFeedback.created_at), desc(GeneralFeedback.id)) + try: + limit = int(query_params.get('limit', 200)) + except (TypeError, ValueError): + limit = 200 + limit = max(1, min(limit, 1000)) + items = query.limit(limit).all() + rows = [] + for item, real_name, department in items: + row = {} + for col in item.__table__.columns: + val = getattr(item, col.name) + if isinstance(val, datetime): + val = val.isoformat() + row[col.name] = val + row['real_name'] = real_name + row['department'] = department + rows.append(row) + return rows + + +def count_general_feedbacks_report(query_params: dict[str, str]) -> dict: + """通用反馈计数。""" + query = db.session.query(GeneralFeedback).outerjoin(User, User.id == GeneralFeedback.user_id) + query = _apply_general_feedback_filters(query, query_params) + total = query.count() + return {'table': 'general_feedbacks', 'total': int(total)} + + +def chat_logs_report_query(): + """ChatLog JOIN User、Agent 基础查询。""" + return ( + db.session.query( + ChatLog, + User.username.label('username'), + User.real_name.label('real_name'), + Agent.name.label('agent_name'), + ) + .join(User, User.id == ChatLog.user_id) + .join(Agent, Agent.id == ChatLog.agent_id) + ) + + +def serialize_chat_log_report_row( + log: ChatLog, + username: str | None, + real_name: str | None, + agent_name: str | None, +) -> dict: + """ChatLog 报表行序列化。""" + return { + 'id': log.id, + 'agent_name': agent_name or '', + 'username': username or '', + 'real_name': real_name or '', + 'created_at': log.created_at.isoformat() if log.created_at else None, + 'query': log.query, + 'answer': log.answer, + 'tokens_used': log.tokens_used, + } + + +def apply_chat_logs_report_filters(query, query_params: dict[str, str]): + """对聊天日志报表查询应用列筛选。""" + reserved = {'limit', 'offset', 'page', 'page_size'} + for key, value in query_params.items(): + if key in reserved or not value: + continue + if key == 'agent_name': + query = query.filter(Agent.name.cast(db.String).ilike(f'%{value}%')) + elif key == 'username': + query = query.filter(User.username.cast(db.String).ilike(f'%{value}%')) + elif key == 'real_name': + query = query.filter(User.real_name.cast(db.String).ilike(f'%{value}%')) + elif hasattr(ChatLog, key): + col = getattr(ChatLog, key) + query = query.filter(col.cast(db.String).ilike(f'%{value}%')) + return query + + +def list_chat_logs_report(query_params: dict[str, str]) -> list[dict]: + """聊天日志报表列表(最多 100 条)。""" + query = apply_chat_logs_report_filters(chat_logs_report_query(), query_params) + query = query.order_by(desc(ChatLog.created_at), desc(ChatLog.id)) + items = query.limit(100).all() + return [ + serialize_chat_log_report_row(log, username, real_name, agent_name) + for log, username, real_name, agent_name in items + ] + + +def count_chat_logs_report(query_params: dict[str, str]) -> dict: + """聊天日志报表计数。""" + query = apply_chat_logs_report_filters(chat_logs_report_query(), query_params) + total = query.count() + return {'table': 'chat_logs', 'total': int(total or 0)} diff --git a/backend/app/services/admin/user_service.py b/backend/app/services/admin/user_service.py index 2c15269c..43060754 100644 --- a/backend/app/services/admin/user_service.py +++ b/backend/app/services/admin/user_service.py @@ -1,5 +1,305 @@ """ backend/app/services/admin/user_service.py -用途:管理端用户 CRUD、权限分配。 +用途:管理端用户 CRUD、审批与批量删除;创建/改密时同步 Casdoor。 +依赖:models、user_admin.delete_admin_users、services/auth/casdoor_service。 +逻辑:由 api/admin/users.py 调用。 """ +from __future__ import annotations + +import re +from typing import Any + +from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import joinedload + +from app import db +from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError +from app.models import Agent, User +from app.services.auth import casdoor_service +from app.services.user_admin import delete_admin_users + + +def empty_to_none(value): + if value is None: + return None + if isinstance(value, str) and value.strip() == '': + return None + return value + + +def is_valid_email(email: str) -> bool: + if not isinstance(email, str): + return False + email = email.strip() + if len(email) > 254: + return False + pattern = r'^[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$' + return re.match(pattern, email) is not None + + +def raise_user_integrity_conflict(exc: IntegrityError) -> None: + message = str(getattr(exc, 'orig', exc)) + if 'users_email_key' in message: + raise ConflictError('Email already exists', code='USER.EMAIL_EXISTS') + if 'users_employee_id_key' in message: + raise ConflictError('Employee ID already exists', code='USER.EMPLOYEE_ID_EXISTS') + if 'users_phone_number_key' in message: + raise ConflictError('Phone number already exists', code='USER.PHONE_EXISTS') + if 'users_username_key' in message or 'ix_users_username' in message: + raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS') + raise ConflictError('Data uniqueness conflict', code='USER.UNIQUENESS_CONFLICT') + + +def assert_user_unique_fields(exclude_user_id: int | None, **fields: str | None) -> None: + checks = ( + ('email', 'USER.EMAIL_EXISTS', 'Email already exists'), + ('employee_id', 'USER.EMPLOYEE_ID_EXISTS', 'Employee ID already exists'), + ('phone_number', 'USER.PHONE_EXISTS', 'Phone number already exists'), + ) + for field, code, message in checks: + value = fields.get(field) + if value is None: + continue + query = db.session.query(User.id).filter(getattr(User, field) == value) + if exclude_user_id is not None: + query = query.filter(User.id != exclude_user_id) + if query.first(): + raise ConflictError(message, code=code, details={'field': field}) + + +def serialize_admin_user(user: User) -> dict: + 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_users_filters(query, query_params: dict[str, str]): + if query_params.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 = (query_params.get(key) or '').strip() + if value: + query = query.filter(column.cast(db.String).ilike(f'%{value}%')) + return query + + +def list_users(query_params: dict[str, str]) -> list[dict] | dict: + query = apply_users_filters(db.session.query(User), query_params) + if 'page' not in query_params: + users = query.options(joinedload(User.agents)).order_by(User.id.asc()).all() + return [serialize_admin_user(u) for u in users] + + try: + page = int(query_params.get('page') or 1) + except (TypeError, ValueError): + page = 1 + try: + page_size = int(query_params.get('page_size') or 20) + except (TypeError, ValueError): + page_size = 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 { + 'items': [serialize_admin_user(u) for u in users], + 'total': int(total), + 'page': page, + 'page_size': page_size, + 'pages': pages, + } + + +def create_user(data: dict[str, Any]) -> dict: + required_field_errors = ( + ('username', 'USER.USERNAME_REQUIRED', 'Username is required'), + ('password', 'USER.PASSWORD_REQUIRED', 'Password is required'), + ('email', 'USER.EMAIL_REQUIRED', 'Email is required'), + ('real_name', 'USER.REAL_NAME_REQUIRED', 'Real name is required'), + ('employee_id', 'USER.EMPLOYEE_ID_REQUIRED', 'Employee ID is required'), + ('phone_number', 'USER.PHONE_REQUIRED', 'Phone number is required'), + ) + for field, code, message in required_field_errors: + if empty_to_none(data.get(field)) is None: + raise AppError(code=code, message=message, http_status=400, details={'field': field}) + if db.session.query(User).filter_by(username=data['username']).first(): + raise ConflictError('Username already exists', code='USER.USERNAME_EXISTS', details={'field': 'username'}) + email = empty_to_none(data.get('email')) + if not is_valid_email(email): + raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'}) + assert_user_unique_fields( + None, + email=email, + employee_id=empty_to_none(data.get('employee_id')), + phone_number=empty_to_none(data.get('phone_number')), + ) + user = User( + username=data['username'], + email=email, + department=empty_to_none(data.get('department')), + role=data.get('role', 'user'), + status=data.get('status', 'active'), + real_name=empty_to_none(data.get('real_name')), + employee_id=empty_to_none(data.get('employee_id')), + phone_number=empty_to_none(data.get('phone_number')), + ) + user.set_password(data['password']) + db.session.add(user) + try: + if data.get('agent_ids'): + agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all() + user.agents = agents + casdoor_service.sync_create_user( + username=user.username, + password=data['password'], + email=email, + real_name=user.real_name, + phone_number=user.phone_number, + status=user.status, + department=user.department, + ) + db.session.commit() + except IntegrityError as exc: + db.session.rollback() + raise_user_integrity_conflict(exc) + except AppError: + db.session.rollback() + raise + except RuntimeError as exc: + db.session.rollback() + casdoor_service.raise_add_user_error(exc) + return {'id': user.id} + + +def update_user(user_id: int, data: dict[str, Any]) -> dict: + user = db.session.get(User, user_id) + if not user: + raise NotFoundError('User not found') + if 'email' in data: + email = empty_to_none(data.get('email')) + if email is not None and (not is_valid_email(email)): + raise AppError(code='USER.EMAIL_INVALID', message='Invalid email format', http_status=400, details={'field': 'email'}) + unique_updates = { + field: empty_to_none(data[field]) + for field in ('email', 'employee_id', 'phone_number') + if field in data + } + assert_user_unique_fields(user_id, **unique_updates) + new_password = empty_to_none(data.get('password')) + try: + for key in ['email', 'department', 'role', 'status', 'real_name', 'employee_id', 'phone_number']: + if key in data: + if key in ['email', 'department', 'real_name', 'employee_id', 'phone_number']: + setattr(user, key, empty_to_none(data[key])) + else: + setattr(user, key, data[key]) + if new_password: + user.set_password(new_password) + if 'agent_ids' in data: + agents = db.session.query(Agent).filter(Agent.id.in_(data['agent_ids'])).all() + user.agents = agents + if new_password: + casdoor_service.sync_update_user(user, new_password=new_password) + db.session.commit() + except IntegrityError as exc: + db.session.rollback() + raise_user_integrity_conflict(exc) + except AppError: + db.session.rollback() + raise + except RuntimeError as exc: + db.session.rollback() + casdoor_service.raise_set_password_error(exc) + return {'status': 'ok'} + + +def cleanup_rejected_users() -> dict: + 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 {'deleted_count': cnt} + + +def batch_delete_users(user_ids: list[Any], *, current_user_id: int | None) -> dict: + target_ids = [uid for uid in user_ids if str(uid) != str(current_user_id)] + if not target_ids: + raise ValidationError('No valid users') + 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 {'deleted_count': cnt} + + +def delete_user(user_id: int, *, current_user_id: int | None) -> dict: + if current_user_id is not None and str(current_user_id) == str(user_id): + raise ValidationError('Cannot delete current user') + user = db.session.get(User, user_id) + if not user: + raise NotFoundError('User not found') + try: + delete_admin_users([user_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 {'status': 'ok'} + + +def approve_user(user_id: int) -> dict: + user = db.session.get(User, user_id) + if user: + user.status = 'active' + db.session.commit() + return {'status': 'ok'} + + +def reject_user(user_id: int) -> dict: + user = db.session.get(User, user_id) + if user: + user.status = 'rejected' + db.session.commit() + return {'status': 'ok'} diff --git a/backend/app/services/admin/wecom_admin_service.py b/backend/app/services/admin/wecom_admin_service.py new file mode 100644 index 00000000..0a0d701b --- /dev/null +++ b/backend/app/services/admin/wecom_admin_service.py @@ -0,0 +1,576 @@ +""" +backend/app/services/admin/wecom_admin_service.py + +用途:管理端企微绑定、配置、诊断与 OA userid 同步。 +依赖:wecom_auth_service、oa_wecom_sync、env_persistence、models。 +逻辑:由 api/admin/wecom.py 调用。 +""" +from __future__ import annotations + +import uuid +from datetime import datetime, timedelta +from typing import Any + +import requests +from flask import current_app +from sqlalchemy import func, or_ +from sqlalchemy.exc import IntegrityError + +from app import db +from app.core.config.env_persistence import persist_env_settings +from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError +from app.models import Agent, LoginAudit, User, WecomNotifyAudit +from app.services.auth import wecom_auth_service +from app.services.oa_wecom_sync import sync_wecom_userids_from_oa + + +def serialize_debug_match_user(user: User) -> dict: + return { + 'id': user.id, + 'username': user.username, + 'real_name': user.real_name, + 'employee_id': user.employee_id, + 'phone_number': user.phone_number, + 'email': user.email, + 'status': user.status, + 'wecom_userid': user.wecom_userid, + 'wecom_unionid': user.wecom_unionid, + } + + +def build_match_preview(identity: dict, rules: list[str], operator: str) -> dict: + bind_mode = wecom_auth_service.get_first_login_bind_mode() + preview = { + 'bind_mode': bind_mode, + 'rules': {'fields': rules, 'operator': operator}, + 'auto_create_user': bool(current_app.config.get('WECOM_AUTO_CREATE_USER', True)), + } + bound_user = None + if identity.get('wecom_userid'): + bound_user = db.session.query(User).filter_by(wecom_userid=identity['wecom_userid']).first() + if not bound_user and identity.get('wecom_unionid'): + bound_user = db.session.query(User).filter_by(wecom_unionid=identity['wecom_unionid']).first() + if bound_user: + preview['decision'] = 'already_bound' + preview['bound_user'] = serialize_debug_match_user(bound_user) + return preview + if bind_mode == 'input_verify': + preview['decision'] = 'input_verification_required' + preview['allowed_fields'] = wecom_auth_service.get_first_login_input_fields() + return preview + matched_users, missing_fields = wecom_auth_service.find_users_by_match_rules(identity, rules, operator) + preview['missing_fields'] = missing_fields + preview['matched_users'] = [serialize_debug_match_user(user) for user in matched_users] + if missing_fields: + preview['decision'] = 'missing_match_fields' + elif len(matched_users) == 1: + preview['decision'] = 'matched_existing_user' + elif len(matched_users) > 1: + preview['decision'] = 'ambiguous_match' + elif preview['auto_create_user']: + preview['decision'] = 'would_auto_create_user' + else: + preview['decision'] = 'bind_required' + return preview + + +def debug_user_by_code(code: str) -> dict: + """通过 OAuth code 拉取企微用户并返回匹配预览(管理端诊断)。""" + if not wecom_auth_service.is_configured(): + raise ValidationError('WeCom login is not configured') + code = str(code or '').strip() + if not code: + raise ValidationError('code is required') + + access_token = wecom_auth_service.get_access_token() + info_resp = requests.get( + 'https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo', + params={'access_token': access_token, 'code': code}, + timeout=8, + ) + auth_info = info_resp.json() + userid = auth_info.get('userid') or auth_info.get('UserId') + openid = auth_info.get('openid') or auth_info.get('OpenId') + payload = {'auth_info': auth_info} + if auth_info.get('errcode') != 0: + raise AppError( + code='WECOM_AUTH_FAILED', + message=f"WeCom auth failed: {auth_info.get('errmsg', 'unknown error')}", + http_status=401, + details={'auth_info': auth_info}, + ) + if not userid: + raise AppError( + code='WECOM_NOT_IN_AGENT_SCOPE', + message='当前 code 对应的账号不在应用可见范围内,或不是本企业成员。', + http_status=401, + details={'auth_info': auth_info, 'openid': openid}, + ) + user_resp = requests.get( + 'https://qyapi.weixin.qq.com/cgi-bin/user/get', + params={'access_token': access_token, 'userid': userid}, + timeout=8, + ) + wecom_user = user_resp.json() + payload['wecom_user'] = wecom_user + if wecom_user.get('errcode') != 0: + raise AppError( + code='WECOM_USER_FETCH_FAILED', + message=f"WeCom user fetch failed: {wecom_user.get('errmsg', 'unknown error')}", + http_status=401, + details={'auth_info': auth_info, 'wecom_user': wecom_user}, + ) + identity = wecom_auth_service.extract_identity(wecom_user) + rules, operator = wecom_auth_service.get_match_config() + payload['normalized_identity'] = identity + payload['match_preview'] = build_match_preview(identity, rules, operator) + return payload + + +def list_bindings(query_params: dict[str, str]) -> dict: + bound_only = query_params.get('bound_only', 'false').lower() == 'true' + keyword = (query_params.get('keyword') or '').strip() + try: + page = int(query_params.get('page') or 1) + except (TypeError, ValueError): + page = 1 + try: + page_size = int(query_params.get('page_size') or 20) + except (TypeError, ValueError): + page_size = 20 + page = max(1, page) + page_size = max(1, min(100, page_size)) + + query = db.session.query(User) + if bound_only: + query = query.filter(User.wecom_userid.isnot(None)) + if keyword: + pattern = f'%{keyword}%' + query = query.filter(or_( + User.username.ilike(pattern), + User.real_name.ilike(pattern), + User.employee_id.ilike(pattern), + User.wecom_userid.ilike(pattern), + )) + + total = query.count() + pages = max(1, (total + page_size - 1) // page_size) if total else 1 + if page > pages: + page = pages + + users = ( + query.order_by(User.id.asc()) + .offset((page - 1) * page_size) + .limit(page_size) + .all() + ) + items = [ + { + 'id': u.id, + 'username': u.username, + 'real_name': u.real_name, + 'employee_id': u.employee_id, + 'email': u.email, + 'role': u.role, + 'status': u.status, + 'wecom_userid': u.wecom_userid, + 'wecom_unionid': u.wecom_unionid, + 'bound': bool(u.wecom_userid), + } + for u in users + ] + return { + 'items': items, + 'total': int(total), + 'page': page, + 'page_size': page_size, + 'pages': pages, + } + + +def bind_user(data: dict[str, Any]) -> dict: + user_id = data.get('user_id') + wecom_userid = data.get('wecom_userid') + wecom_unionid = data.get('wecom_unionid') + if not user_id or not wecom_userid: + raise ValidationError('user_id and wecom_userid are required') + try: + user_id = int(user_id) + except (TypeError, ValueError): + raise ValidationError('user_id must be integer') + user = db.session.get(User, user_id) + if not user: + raise NotFoundError('User not found') + dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first() + if dup: + raise ValidationError(f'wecom_userid already bound to user {dup.username}') + if wecom_unionid: + dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first() + if dup_union: + raise ValidationError(f'wecom_unionid already bound to user {dup_union.username}') + user.wecom_userid = wecom_userid + if wecom_unionid is not None: + user.wecom_unionid = wecom_unionid + db.session.commit() + return {'status': 'ok', 'message': 'WeCom binding updated'} + + +def unbind_user(data: dict[str, Any]) -> dict: + user_id = data.get('user_id') + if not user_id: + raise ValidationError('user_id is required') + try: + user_id = int(user_id) + except (TypeError, ValueError): + raise ValidationError('user_id must be integer') + user = db.session.get(User, user_id) + if not user: + raise NotFoundError('User not found') + user.wecom_userid = None + user.wecom_unionid = None + db.session.commit() + return {'status': 'ok', 'message': 'WeCom account unbound'} + + +def provision_user(data: dict[str, Any]) -> tuple[dict, int]: + create_user_flag = bool(data.get('create_user', True)) + user_data = data.get('user') or {} + bind_data = data.get('bind') or {} + user_id = data.get('user_id') + permission_updated = False + wecom_userid = (bind_data.get('wecom_userid') or '').strip() + wecom_unionid = (bind_data.get('wecom_unionid') or '').strip() + if not wecom_userid: + raise ValidationError('bind.wecom_userid is required') + + if create_user_flag: + username = (user_data.get('username') or '').strip() + if not username: + raise ValidationError('user.username is required when create_user=true') + if db.session.query(User).filter_by(username=username).first(): + raise ValidationError('Username exists') + email = (user_data.get('email') or '').strip() or None + employee_id = (user_data.get('employee_id') or '').strip() or None + phone_number = (user_data.get('phone_number') or '').strip() or None + if email and db.session.query(User).filter_by(email=email).first(): + raise ValidationError('Email already exists') + if employee_id and db.session.query(User).filter_by(employee_id=employee_id).first(): + raise ValidationError('Employee ID already exists') + if phone_number and db.session.query(User).filter_by(phone_number=phone_number).first(): + raise ValidationError('Phone number already exists') + user = User( + username=username, + email=email, + department=user_data.get('department'), + role=user_data.get('role', 'user'), + status=user_data.get('status', 'active'), + real_name=user_data.get('real_name'), + employee_id=employee_id, + phone_number=phone_number, + ) + password = user_data.get('password') + user.set_password(password or uuid.uuid4().hex) + db.session.add(user) + db.session.flush() + binding_status = 'created' + status_code = 201 + else: + if user_id is None: + user_id = user_data.get('id') + if user_id is None: + raise ValidationError('user_id is required when create_user=false') + try: + user_id = int(user_id) + except (TypeError, ValueError): + raise ValidationError('user_id must be integer') + user = db.session.get(User, user_id) + if not user: + raise NotFoundError('User not found') + binding_status = 'updated' + status_code = 200 + + dup = db.session.query(User).filter(User.wecom_userid == wecom_userid, User.id != user.id).first() + if dup: + db.session.rollback() + raise ValidationError(f'wecom_userid already bound to user {dup.username}') + if wecom_unionid: + dup_union = db.session.query(User).filter(User.wecom_unionid == wecom_unionid, User.id != user.id).first() + if dup_union: + db.session.rollback() + raise ValidationError(f'wecom_unionid already bound to user {dup_union.username}') + user.wecom_userid = wecom_userid + if wecom_unionid: + user.wecom_unionid = wecom_unionid + + if 'agent_ids' in data: + agent_ids = data.get('agent_ids', []) + if not isinstance(agent_ids, list): + db.session.rollback() + raise ValidationError('agent_ids must be array') + if agent_ids: + try: + unique_ids = sorted({int(i) for i in agent_ids}) + except (TypeError, ValueError): + db.session.rollback() + raise ValidationError('agent_ids must be integer array') + agents = db.session.query(Agent).filter(Agent.id.in_(unique_ids)).all() + if len(agents) != len(unique_ids): + db.session.rollback() + raise ValidationError('Some agent_ids are invalid') + user.agents = agents + else: + user.agents = [] + permission_updated = True + + try: + db.session.commit() + except IntegrityError: + db.session.rollback() + raise ValidationError('Provision failed due to data uniqueness conflict') + + return ( + { + 'status': 'ok', + 'user_id': user.id, + 'binding': binding_status, + 'permission_updated': permission_updated, + }, + status_code, + ) + + +def list_login_audits(query_params: dict[str, str]) -> list[dict]: + source = query_params.get('source') + status = query_params.get('status') + try: + limit = max(1, min(int(query_params.get('limit', 100)), 500)) + except (TypeError, ValueError): + limit = 100 + query = db.session.query(LoginAudit) + if source: + query = query.filter(LoginAudit.source == source) + if status: + query = query.filter(LoginAudit.status == status) + rows = query.order_by(LoginAudit.created_at.desc()).limit(limit).all() + return [ + { + 'id': r.id, + 'user_id': r.user_id, + 'username': r.username, + 'source': r.source, + 'status': r.status, + 'reason': r.reason, + 'error_code': r.error_code, + 'match_rules': r.match_rules, + 'match_operator': r.match_operator, + 'match_result': r.match_result, + 'wecom_userid': r.wecom_userid, + 'ip': r.ip, + 'user_agent': r.user_agent, + 'created_at': r.created_at.isoformat() if r.created_at else None, + } + for r in rows + ] + + +def serialize_notify_settings() -> dict: + return { + 'enabled': bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)), + 'base_url': current_app.config.get('WECOM_NOTIFY_BASE_URL') or '', + 'events': [x for x in str(current_app.config.get('WECOM_NOTIFY_EVENTS', '')).split(',') if x], + } + + +def update_notify_settings(data: dict[str, Any]) -> dict: + updates = {} + if 'enabled' in data: + updates['WECOM_NOTIFY_ENABLED'] = bool(data.get('enabled')) + if 'base_url' in data: + updates['WECOM_NOTIFY_BASE_URL'] = str(data.get('base_url') or '').strip() + if 'events' in data: + events = data.get('events') or [] + if isinstance(events, list): + updates['WECOM_NOTIFY_EVENTS'] = ','.join([str(x).strip() for x in events if str(x).strip()]) + for key, value in updates.items(): + current_app.config[key] = value + persist_env_settings(updates) + return {'status': 'ok', 'settings': serialize_notify_settings()} + + +def serialize_system_settings() -> dict: + return { + 'enabled': bool(current_app.config.get('WECOM_ENABLED', False)), + 'corp_id': current_app.config.get('WECOM_CORP_ID') or '', + 'agent_id': str(current_app.config.get('WECOM_AGENT_ID') or ''), + 'secret': current_app.config.get('WECOM_SECRET') or '', + 'redirect_uri': current_app.config.get('WECOM_REDIRECT_URI') or '', + 'auto_create_user': bool(current_app.config.get('WECOM_AUTO_CREATE_USER', True)), + 'match_rules': current_app.config.get('WECOM_MATCH_RULES') or 'employee_id,mobile', + 'match_operator': str(current_app.config.get('WECOM_MATCH_OPERATOR') or 'AND').upper(), + 'first_login_bind_mode': str(current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE') or 'match_rules').lower(), + 'first_login_input_fields': current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS') or 'employee_id,mobile,email', + 'employee_id_source': current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE') or 'userid', + 'mobile_normalize': bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True)), + 'callback_token': current_app.config.get('WECOM_CALLBACK_TOKEN') or '', + 'encoding_aes_key': current_app.config.get('WECOM_ENCODING_AES_KEY') or '', + 'callback_url': current_app.config.get('WECOM_CALLBACK_URL') or '', + 'homepage_url': current_app.config.get('WECOM_HOMEPAGE_URL') or '', + 'trusted_domain': current_app.config.get('WECOM_TRUSTED_DOMAIN') or '', + 'public_base_url': current_app.config.get('WECOM_PUBLIC_BASE_URL') or '', + } + + +def update_system_settings(data: dict[str, Any]) -> dict: + bool_keys = { + 'enabled': 'WECOM_ENABLED', + 'auto_create_user': 'WECOM_AUTO_CREATE_USER', + 'mobile_normalize': 'WECOM_MOBILE_NORMALIZE', + } + str_keys = { + 'corp_id': 'WECOM_CORP_ID', + 'agent_id': 'WECOM_AGENT_ID', + 'secret': 'WECOM_SECRET', + 'redirect_uri': 'WECOM_REDIRECT_URI', + 'match_rules': 'WECOM_MATCH_RULES', + 'match_operator': 'WECOM_MATCH_OPERATOR', + 'first_login_bind_mode': 'WECOM_FIRST_LOGIN_BIND_MODE', + 'first_login_input_fields': 'WECOM_FIRST_LOGIN_INPUT_FIELDS', + 'employee_id_source': 'WECOM_EMPLOYEE_ID_SOURCE', + 'callback_token': 'WECOM_CALLBACK_TOKEN', + 'encoding_aes_key': 'WECOM_ENCODING_AES_KEY', + 'callback_url': 'WECOM_CALLBACK_URL', + 'homepage_url': 'WECOM_HOMEPAGE_URL', + 'trusted_domain': 'WECOM_TRUSTED_DOMAIN', + 'public_base_url': 'WECOM_PUBLIC_BASE_URL', + } + updates = {} + for req_key, cfg_key in bool_keys.items(): + if req_key in data: + updates[cfg_key] = bool(data.get(req_key)) + for req_key, cfg_key in str_keys.items(): + if req_key in data: + updates[cfg_key] = str(data.get(req_key) or '').strip() + for key, value in updates.items(): + current_app.config[key] = value + if current_app.config.get('WECOM_MATCH_OPERATOR') not in {'AND', 'OR'}: + current_app.config['WECOM_MATCH_OPERATOR'] = 'AND' + updates['WECOM_MATCH_OPERATOR'] = 'AND' + if current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE') not in {'match_rules', 'input_verify'}: + current_app.config['WECOM_FIRST_LOGIN_BIND_MODE'] = 'match_rules' + updates['WECOM_FIRST_LOGIN_BIND_MODE'] = 'match_rules' + persist_env_settings(updates) + return {'status': 'ok', 'settings': serialize_system_settings()} + + +def integration_manifest(*, host_url: str, host: str) -> dict: + settings = serialize_system_settings() + public_base = (settings.get('public_base_url') or '').rstrip('/') + if not public_base: + for key in ('WECOM_PUBLIC_BASE_URL', 'WECOM_NOTIFY_BASE_URL'): + configured = current_app.config.get(key) or '' + if configured: + public_base = configured.rstrip('/') + break + if not public_base: + public_base = host_url.rstrip('/') + callback_url = settings.get('callback_url') or f'{public_base}/api/user/wecom/callback' + homepage_url = settings.get('homepage_url') or f'{public_base}/workspace' + trusted_domain = settings.get('trusted_domain') or host.split(':')[0] + return { + 'public_base_url': public_base, + 'callback_url': callback_url, + 'callback_token': settings.get('callback_token') or '', + 'encoding_aes_key': settings.get('encoding_aes_key') or '', + 'oauth_redirect_uri': settings.get('redirect_uri') or homepage_url, + 'homepage_url': homepage_url, + 'trusted_domain': trusted_domain, + 'authorize_api': f'{public_base}/api/user/wecom/authorize-url', + 'login_api': f'{public_base}/api/user/wecom/login', + } + + +def notify_metrics() -> dict: + now = datetime.utcnow() + from_time = now - timedelta(days=30) + total = db.session.query(func.count(WecomNotifyAudit.id)).filter(WecomNotifyAudit.created_at >= from_time).scalar() or 0 + sent = db.session.query(func.count(WecomNotifyAudit.id)).filter( + WecomNotifyAudit.created_at >= from_time, + WecomNotifyAudit.status == 'sent', + ).scalar() or 0 + opened_24h = db.session.query(func.count(WecomNotifyAudit.id)).filter( + WecomNotifyAudit.created_at >= from_time, + WecomNotifyAudit.opened_at.isnot(None), + ).scalar() or 0 + by_event_rows = ( + db.session.query(WecomNotifyAudit.event_type, WecomNotifyAudit.status, func.count(WecomNotifyAudit.id)) + .filter(WecomNotifyAudit.created_at >= from_time) + .group_by(WecomNotifyAudit.event_type, WecomNotifyAudit.status) + .all() + ) + by_event = {} + for event_type, status, cnt in by_event_rows: + if event_type not in by_event: + by_event[event_type] = {'sent': 0, 'failed': 0} + by_event[event_type][status] = int(cnt) + return { + 'window_days': 30, + 'total': int(total), + 'sent': int(sent), + 'failed': int(total - sent), + 'send_success_rate': round(sent / total * 100, 2) if total else 0, + 'opened_24h': int(opened_24h), + 'opened_24h_rate': round(opened_24h / sent * 100, 2) if sent else 0, + 'by_event': by_event, + } + + +def binding_stats() -> dict: + total_active = db.session.query(func.count(User.id)).filter(User.status == 'active').scalar() or 0 + bound = ( + db.session.query(func.count(User.id)) + .filter(User.status == 'active', User.wecom_userid.isnot(None), User.wecom_userid != '') + .scalar() + or 0 + ) + total_active = int(total_active) + bound = int(bound) + return { + 'total_active': total_active, + 'bound': bound, + 'unbound': max(total_active - bound, 0), + 'bound_rate': round(bound / total_active * 100, 2) if total_active else 0, + } + + +def sync_userids(*, apply: bool) -> dict: + try: + summary = sync_wecom_userids_from_oa(apply=apply) + current_app.logger.info( + '[wecom_sync] oa apply=%s updated=%s would_update=%s conflicts=%s local_matched=%s', + apply, + summary.get('updated'), + summary.get('would_update'), + len(summary.get('conflicts') or []), + summary.get('local_matched'), + ) + return summary + except RuntimeError as exc: + message = str(exc) + if 'conflicts detected' in message.lower(): + raise ConflictError(message, details={'error_code': 'WECOM_SYNC_CONFLICTS'}) + if '未找到可用的 SQL Server ODBC 驱动' in message or 'pyodbc' in message.lower(): + raise AppError( + code='SYSTEM.SERVICE_UNAVAILABLE', + message='OA SQL Server driver is not available on this server', + http_status=503, + details={'error_code': 'OA_SQLSERVER_DRIVER_MISSING', 'technical': message[:300]}, + ) + raise AppError( + code='SYSTEM.HTTP_ERROR', + message='OA SQL Server sync failed. Check OA_SQLSERVER_* env and network access.', + http_status=502, + details={'error_code': 'OA_SQLSERVER_SYNC_FAILED', 'technical': message[:300]}, + ) + except Exception as exc: + current_app.logger.exception('[wecom_sync] oa unexpected failure: %s', exc) + raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(exc), http_status=500) diff --git a/backend/app/services/auth/__init__.py b/backend/app/services/auth/__init__.py index 5bd3e722..4f686ff3 100644 --- a/backend/app/services/auth/__init__.py +++ b/backend/app/services/auth/__init__.py @@ -2,5 +2,8 @@ backend/app/services/auth/__init__.py 用途:认证域业务(Casdoor OIDC、企微 OAuth)。 -逻辑:Wave 3 从 api/user/_legacy auth 相关路由抽取。 +逻辑:Wave 3 从 api/user 抽取;api/user 保留薄 re-export 兼容旧测试。 """ +from . import casdoor_service, wecom_auth_service + +__all__ = ['casdoor_service', 'wecom_auth_service'] diff --git a/backend/app/services/auth/casdoor_service.py b/backend/app/services/auth/casdoor_service.py index b3fdb6e2..57ce24f8 100644 --- a/backend/app/services/auth/casdoor_service.py +++ b/backend/app/services/auth/casdoor_service.py @@ -1,5 +1,373 @@ """ backend/app/services/auth/casdoor_service.py -用途:Casdoor OIDC 登录、token 交换、用户同步业务逻辑。 +用途:Casdoor IdP 用户同步与 OAuth 错误映射(管理端创建/改密、用户域登录共用)。 +依赖:flask.current_app、requests、app.core.errors。 +逻辑:由 services/admin/user_service、api/user 登录路由调用。 """ +from __future__ import annotations + +import ast +import json +import re +from typing import Any + +import requests +from flask import current_app + +from app.core.errors import AppError, ConflictError, ValidationError +from app.models import User + + +def clean_str(value) -> str | None: + """Trim 字符串;空串返回 None。""" + if value is None: + return None + if isinstance(value, str): + value = value.strip() + return value or None + return str(value).strip() or None + + +def is_casdoor_configured() -> bool: + """Casdoor 基础配置是否齐全。""" + if not clean_str(current_app.config.get('CASDOOR_ORGANIZATION')): + return False + base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/') + client_id = current_app.config.get('CASDOOR_CLIENT_ID') or '' + client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or '' + return bool(base and client_id and client_secret) + + +def casdoor_user_owner() -> str: + """返回 Casdoor organization owner。""" + owner = clean_str(current_app.config.get('CASDOOR_ORGANIZATION')) + if not owner: + raise RuntimeError('CASDOOR_ORGANIZATION is not configured') + return owner + + +def extract_error_payload(source) -> dict: + """从 Casdoor 响应或异常文本解析 JSON 错误体。""" + if isinstance(source, dict): + return source + text = str(source or '') + match = re.search(r'\{.*\}', text, re.DOTALL) + if match: + try: + parsed = ast.literal_eval(match.group(0)) + if isinstance(parsed, dict): + return parsed + except (SyntaxError, ValueError): + pass + try: + parsed = json.loads(text) + if isinstance(parsed, dict): + return parsed + except (json.JSONDecodeError, TypeError): + pass + return {} + + +def is_user_exists_error(message: str) -> bool: + lowered = (message or '').lower() + return 'already exist' in lowered or 'duplicate' in lowered or 'has existed' in lowered + + +def is_password_error(message: str) -> bool: + lowered = (message or '').lower() + return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered + + +def is_user_missing_error(message: str) -> bool: + lowered = (message or '').lower() + return ( + "doesn't exist" in lowered + or 'does not exist' in lowered + or 'user not found' in lowered + or 'no such user' in lowered + ) + + +def raise_user_not_in_idp(source=None) -> None: + data = extract_error_payload(source) + msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message')) + raise AppError( + code='CASDOOR_USER_NOT_IN_IDP', + message='Your account has not been registered in the authentication system. Please contact the administrator.', + http_status=409, + details={'technical': msg_text or str(source or '')[:300]}, + ) + + +def raise_add_user_error(source) -> None: + """将 Casdoor add-user 失败映射为稳定业务错误码。""" + data = extract_error_payload(source) + msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message')) + lowered = (msg_text or str(source or '')).lower() + if is_user_exists_error(lowered): + raise ConflictError( + 'Username already exists in Casdoor', + code='USER.USERNAME_EXISTS', + details={'field': 'username', 'technical': msg_text}, + ) + if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')): + raise AppError(code='CASDOOR_PASSWORD_POLICY', message='Password does not meet security requirements', http_status=400) + raise AppError( + code='CASDOOR_ADD_USER_FAILED', + message='Failed to create user in authentication system. Please try again or contact the administrator.', + http_status=502, + details={'technical': msg_text or str(source or '')[:300]}, + ) + + +def raise_update_user_error(source) -> None: + """将 Casdoor update-user 失败映射为稳定业务错误码。""" + data = extract_error_payload(source) + msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message')) + lowered = (msg_text or str(source or '')).lower() + if is_user_missing_error(lowered): + raise_user_not_in_idp(source) + if is_user_exists_error(lowered) or ('email' in lowered and 'already' in lowered): + raise ConflictError( + 'Email already exists in Casdoor', + code='USER.EMAIL_EXISTS', + details={'field': 'email', 'technical': msg_text}, + ) + raise AppError( + code='CASDOOR_UPDATE_USER_FAILED', + message='Failed to update user in authentication system. Please try again or contact the administrator.', + http_status=502, + details={'technical': msg_text or str(source or '')[:300]}, + ) + + +def raise_set_password_error(source) -> None: + """将 Casdoor set-password 失败映射为稳定业务错误码。""" + data = extract_error_payload(source) + msg_text = clean_str(data.get('msg') or data.get('error_description') or data.get('message')) + lowered = (msg_text or str(source or '')).lower() + if is_password_error(lowered) or 'old password' in lowered or 'current password' in lowered: + raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect current password', http_status=401) + if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')): + raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400) + if is_user_missing_error(lowered): + raise_user_not_in_idp(source) + raise AppError( + code='CASDOOR_SET_PASSWORD_FAILED', + message='Failed to change password. Please try again or contact the administrator.', + http_status=502, + details={'technical': msg_text or str(source)[:300]}, + ) + + +def raise_auth_error(source, *, context: str, status_code: int = 401) -> None: + """Map Casdoor OAuth/API failures to stable business error codes.""" + data = extract_error_payload(source) + raw = str(source or '') + oauth_error = clean_str(data.get('error')).lower() + if not oauth_error and 'invalid_grant' in raw.lower(): + oauth_error = 'invalid_grant' + if not oauth_error and 'invalid_client' in raw.lower(): + oauth_error = 'invalid_client' + if oauth_error == 'invalid_grant' or is_password_error(raw): + if context in ('password', 'verify'): + raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401) + raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401) + if oauth_error in ('invalid_client', 'unauthorized_client'): + raise AppError( + code='CASDOOR_CONFIG_ERROR', + message='Authentication service is misconfigured. Please contact the administrator.', + http_status=503, + details={'casdoor_error': oauth_error}, + ) + if oauth_error == 'access_denied': + raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403) + if 'token endpoint missing' in raw.lower() or 'casdoor_base_url is not configured' in raw.lower() or 'casdoor is not configured' in raw.lower(): + raise AppError( + code='CASDOOR_CONFIG_ERROR', + message='Authentication service is not configured. Please contact the administrator.', + http_status=503, + ) + if 'invalid or expired casdoor state' in raw.lower(): + raise ValidationError('Invalid or expired Casdoor state') + current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s raw=%s', context, data, raw[:500]) + raise AppError( + code='CASDOOR_AUTH_FAILED', + message='Authentication failed, please try again', + http_status=status_code, + details={'casdoor_error': oauth_error or None, 'technical': raw[:300]}, + ) + + +def build_user_profile_payload( + *, + username: str, + email: str, + real_name=None, + phone_number=None, + status='active', + department=None, +) -> dict: + """组装 Casdoor 用户资料字段(不含 password)。""" + display_name = clean_str(real_name) or username + payload = { + 'owner': casdoor_user_owner(), + 'name': username, + 'email': email or '', + 'displayName': display_name, + 'realName': clean_str(real_name) or '', + 'phone': clean_str(phone_number) or '', + 'isForbidden': clean_str(status) not in (None, 'active'), + } + department_value = clean_str(department) + if department_value: + payload['affiliation'] = department_value + return payload + + +def build_user_payload( + *, + username: str, + password: str, + email: str, + real_name=None, + phone_number=None, + status='active', + department=None, +) -> dict: + """组装 Casdoor add-user 请求体。""" + payload = build_user_profile_payload( + username=username, + email=email, + real_name=real_name, + phone_number=phone_number, + status=status, + department=department, + ) + payload['password'] = password + return payload + + +def casdoor_add_user(user_payload: dict) -> None: + """调用 Casdoor /api/add-user 创建 IdP 用户。""" + base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/') + client_id = current_app.config.get('CASDOOR_CLIENT_ID') or '' + client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or '' + if not base or not client_id or not client_secret: + raise RuntimeError('Casdoor is not configured') + url = f'{base}/api/add-user' + resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8) + try: + data = resp.json() or {} + except ValueError: + raise RuntimeError(f'Casdoor add-user failed: HTTP {resp.status_code} {resp.text[:200]}') + if data.get('status') != 'ok': + raise_add_user_error(data) + + +def casdoor_update_user(user_payload: dict) -> None: + """调用 Casdoor /api/update-user 更新 IdP 用户资料。""" + base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/') + client_id = current_app.config.get('CASDOOR_CLIENT_ID') or '' + client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or '' + if not base or not client_id or not client_secret: + raise RuntimeError('Casdoor is not configured') + url = f'{base}/api/update-user' + resp = requests.post(url, json=user_payload, auth=(client_id, client_secret), timeout=8) + try: + data = resp.json() or {} + except ValueError: + raise RuntimeError(f'Casdoor update-user failed: HTTP {resp.status_code} {resp.text[:200]}') + if data.get('status') != 'ok': + raise_update_user_error(data) + + +def casdoor_set_password(user_owner: str, user_name: str, old_password: str, new_password: str) -> None: + """调用 Casdoor /api/set-password。""" + base = (current_app.config.get('CASDOOR_BASE_URL') or '').rstrip('/') + client_id = current_app.config.get('CASDOOR_CLIENT_ID') or '' + client_secret = current_app.config.get('CASDOOR_CLIENT_SECRET') or '' + if not base or not client_id or not client_secret: + raise RuntimeError('Casdoor is not configured') + url = f'{base}/api/set-password' + resp = requests.post( + url, + files={ + 'userOwner': (None, user_owner), + 'userName': (None, user_name), + 'oldPassword': (None, old_password), + 'newPassword': (None, new_password), + }, + auth=(client_id, client_secret), + timeout=8, + ) + try: + data = resp.json() or {} + except ValueError: + raise RuntimeError(f'Casdoor set-password failed: HTTP {resp.status_code} {resp.text[:200]}') + if data.get('status') != 'ok': + raise_set_password_error(data) + + +def sync_create_user( + *, + username: str, + password: str, + email: str, + real_name=None, + phone_number=None, + status='active', + department=None, +) -> None: + """管理端创建用户时同步至 Casdoor。""" + if not is_casdoor_configured(): + return + payload = build_user_payload( + username=username, + password=password, + email=email, + real_name=real_name, + phone_number=phone_number, + status=status, + department=department, + ) + casdoor_add_user(payload) + + +def sync_admin_set_password(user: User, new_password: str) -> None: + """管理端重设密码时同步 Casdoor(无旧密码)。""" + if not is_casdoor_configured(): + return + user_owner = casdoor_user_owner() + try: + casdoor_set_password(user_owner, user.username, '', new_password) + except RuntimeError as exc: + if is_user_missing_error(str(exc)): + raise_user_not_in_idp(exc) + raise_set_password_error(exc) + + +def sync_update_user(user: User, *, new_password: str | None = None) -> None: + """管理端编辑用户时同步 Casdoor:仅改密;IdP 无账号则 add-user 补建。""" + if not is_casdoor_configured() or not new_password: + return + + def _provision_missing_user_in_casdoor(): + sync_create_user( + username=user.username, + password=new_password, + email=user.email, + real_name=user.real_name, + phone_number=user.phone_number, + status=user.status, + department=user.department, + ) + + try: + sync_admin_set_password(user, new_password) + except AppError as exc: + if exc.code == 'CASDOOR_USER_NOT_IN_IDP': + _provision_missing_user_in_casdoor() + return + raise diff --git a/backend/app/services/auth/wecom_auth_service.py b/backend/app/services/auth/wecom_auth_service.py index dfde5359..7feea9ac 100644 --- a/backend/app/services/auth/wecom_auth_service.py +++ b/backend/app/services/auth/wecom_auth_service.py @@ -1,5 +1,235 @@ """ backend/app/services/auth/wecom_auth_service.py -用途:企业微信 OAuth、绑定、解绑业务逻辑。 +用途:企业微信 OAuth 身份解析、匹配规则与 access_token 缓存。 +依赖:flask.current_app、requests、models.User。 +逻辑:由 api/user 企微登录路由、services/admin/wecom_admin_service 调用。 """ +from __future__ import annotations + +import re +from datetime import datetime, timedelta + +import requests +from flask import current_app +from sqlalchemy import and_, or_ + +from app import db +from app.models import User + +ACCESS_TOKEN_CACHE: dict = {'token': None, 'expires_at': None} +STATE_CACHE: dict = {} +BIND_SESSION_CACHE: dict = {} + +ALLOWED_MATCH_FIELDS = {'employee_id', 'mobile', 'email'} + + +def clean_str(value) -> str | None: + 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_field_list(raw_value, default_fields: list[str]) -> list[str]: + """解析逗号分隔的企微匹配/输入字段列表。""" + if isinstance(raw_value, str): + pieces = [item.strip().lower() for item in raw_value.split(',')] + elif isinstance(raw_value, (list, tuple)): + pieces = [str(item).strip().lower() for item in raw_value] + else: + pieces = [] + result = [] + for piece in pieces: + if piece in ALLOWED_MATCH_FIELDS and piece not in result: + result.append(piece) + return result or list(default_fields) + + +def get_config_missing_fields() -> list[str]: + """返回缺失的企微登录配置键名。""" + missing = [] + if not current_app.config.get('WECOM_ENABLED'): + missing.append('WECOM_ENABLED') + if not clean_str(current_app.config.get('WECOM_CORP_ID')): + missing.append('WECOM_CORP_ID') + if not clean_str(current_app.config.get('WECOM_AGENT_ID')): + missing.append('WECOM_AGENT_ID') + if not clean_str(current_app.config.get('WECOM_SECRET')): + missing.append('WECOM_SECRET') + return missing + + +def is_configured() -> bool: + return len(get_config_missing_fields()) == 0 + + +def get_access_token() -> str: + """获取企微 access_token(带进程内缓存)。""" + now = datetime.utcnow() + token = ACCESS_TOKEN_CACHE.get('token') + expires_at = ACCESS_TOKEN_CACHE.get('expires_at') + if token and expires_at and (now < expires_at): + return token + corp_id = current_app.config.get('WECOM_CORP_ID') + secret = current_app.config.get('WECOM_SECRET') + resp = requests.get( + 'https://qyapi.weixin.qq.com/cgi-bin/gettoken', + params={'corpid': corp_id, 'corpsecret': secret}, + timeout=8, + ) + data = resp.json() + if data.get('errcode') != 0 or not data.get('access_token'): + raise RuntimeError(f'Failed to fetch WeCom token: {data}') + ACCESS_TOKEN_CACHE['token'] = data['access_token'] + ACCESS_TOKEN_CACHE['expires_at'] = now + timedelta(seconds=max(int(data.get('expires_in', 7200)) - 120, 60)) + return data['access_token'] + + +def normalize_mobile(mobile: str) -> str | None: + mobile = clean_str(mobile) + if not mobile: + return None + digits = re.sub(r'\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_extattr_value(wecom_user: dict, key: str) -> str | None: + 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_match_config() -> tuple[list[str], str]: + raw_rules = current_app.config.get('WECOM_MATCH_RULES', 'employee_id,mobile') + rules = parse_field_list(raw_rules, ['employee_id', 'mobile']) + operator = str(current_app.config.get('WECOM_MATCH_OPERATOR', 'AND')).upper() + if operator not in {'AND', 'OR'}: + operator = 'AND' + return rules, operator + + +def get_first_login_bind_mode() -> str: + mode = clean_str(current_app.config.get('WECOM_FIRST_LOGIN_BIND_MODE')) or 'match_rules' + mode = mode.lower() + if mode not in {'match_rules', 'input_verify'}: + mode = 'match_rules' + return mode + + +def get_first_login_input_fields() -> list[str]: + raw_fields = current_app.config.get('WECOM_FIRST_LOGIN_INPUT_FIELDS', 'employee_id,mobile,email') + return parse_field_list(raw_fields, ['employee_id', 'mobile', 'email']) + + +def extract_identity(wecom_user: dict) -> dict: + """从企微 user/get 响应提取标准化身份字段。""" + userid = clean_str(wecom_user.get('userid')) + unionid = clean_str(wecom_user.get('unionid')) + email = clean_str(wecom_user.get('email')) + mobile_raw = clean_str(wecom_user.get('mobile')) + normalize_flag = bool(current_app.config.get('WECOM_MOBILE_NORMALIZE', True)) + mobile = normalize_mobile(mobile_raw) if normalize_flag else mobile_raw + employee_id_source = clean_str(current_app.config.get('WECOM_EMPLOYEE_ID_SOURCE')) or 'userid' + if employee_id_source == 'userid': + employee_id = userid + elif employee_id_source.startswith('extattr:'): + employee_id = extract_extattr_value(wecom_user, employee_id_source.split(':', 1)[1]) + else: + employee_id = clean_str(wecom_user.get(employee_id_source)) + return { + 'wecom_userid': userid, + 'wecom_unionid': unionid, + 'name': clean_str(wecom_user.get('name')) or userid or 'wecom_user', + 'email': email, + 'mobile': mobile, + 'mobile_raw': mobile_raw, + 'employee_id': employee_id, + } + + +def _mobile_candidates(identity: dict) -> list[str]: + 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_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) -> tuple[list[User], list[str]]: + filters = [] + missing = [] + for rule in rules: + if rule == 'employee_id': + employee_id = clean_str(identity.get('employee_id')) + if not employee_id: + missing.append('employee_id') + else: + filters.append(User.employee_id == employee_id) + elif rule == 'mobile': + candidates = _mobile_candidates(identity) + if not candidates: + missing.append('mobile') + else: + filters.append(User.phone_number.in_(candidates)) + elif rule == 'email': + email = clean_str(identity.get('email')) + if not email: + missing.append('email') + else: + filters.append(User.email == email) + if missing: + return [], missing + if not filters: + return [], ['match_rules'] + clause = and_(*filters) if operator == 'AND' else or_(*filters) + users = db.session.query(User).filter(clause).all() + return users, [] diff --git a/backend/app/services/schedule/import_service.py b/backend/app/services/schedule/import_service.py new file mode 100644 index 00000000..195e7b41 --- /dev/null +++ b/backend/app/services/schedule/import_service.py @@ -0,0 +1,104 @@ +""" +backend/app/services/schedule/import_service.py + +用途:排程任务 JSON 批量导入(upsert by schedule_no)。 +依赖:models、scheduler_service、sql_config。 +逻辑:由 api/schedule/tasks.py import 路由调用。 +""" +from __future__ import annotations + +from typing import Any + +from app import db +from app.core.errors import ValidationError +from app.models import ScheduleTask +from app.services.schedule.scheduler_service import create_task, update_task +from app.services.schedule.sql_config import upsert_schedule_task_config + + +def import_schedules_from_payload(schedules: list[Any], *, actor_id: int | None) -> dict[str, Any]: + """ + 批量导入排程 JSON。 + Args: + schedules: 导出文件中的 schedules 数组。 + actor_id: 当前管理员 user id。 + Returns: + ok、imported、skipped、errors(最多 20 条)。 + Raises: + ValidationError: schedules 非 list。 + """ + if not isinstance(schedules, list): + raise ValidationError('Invalid import file: schedules missing') + + imported = 0 + skipped = 0 + errors: list[str] = [] + for item in schedules: + if not isinstance(item, dict): + skipped += 1 + continue + try: + name = str(item.get('name') or '').strip() + cron_expr = str(item.get('cron_expr') or '').strip() + owner_user_id = int(item.get('owner_user_id')) + if not name or not cron_expr: + raise ValueError('name or cron_expr missing') + existing = None + schedule_no = str(item.get('schedule_no') or '').strip() + if schedule_no: + existing = db.session.query(ScheduleTask).filter_by(schedule_no=schedule_no).first() + task_payload = { + 'name': name, + 'schedule_type': str(item.get('schedule_type') or 'platform_app'), + 'owner_user_id': owner_user_id, + 'cron_expr': cron_expr, + 'schedule_timezone': item.get('schedule_timezone'), + 'wait_seconds': int(item.get('wait_seconds') or 0), + 'dify_agent_id': item.get('dify_agent_id'), + 'platform_api_path': item.get('platform_api_path'), + 'notify_user_ids_json': item.get('notify_user_ids_json') + if isinstance(item.get('notify_user_ids_json'), list) + else [], + 'notify_enabled': bool(item.get('notify_enabled', True)), + 'enabled': bool(item.get('enabled', True)), + 'data_source_type': str(item.get('data_source_type') or 'database'), + 'kb_sync_enabled': bool(item.get('kb_sync_enabled', False)), + 'kb_group_id': item.get('kb_group_id'), + } + cfg = item.get('config') if isinstance(item.get('config'), dict) else None + if existing: + update_task(existing, payload=task_payload, actor_id=actor_id) + existing.data_source_type = task_payload['data_source_type'] + if cfg: + upsert_schedule_task_config(existing.id, cfg) + else: + task = create_task( + name=name, + schedule_type=task_payload['schedule_type'], + owner_user_id=owner_user_id, + cron_expr=cron_expr, + schedule_timezone=task_payload['schedule_timezone'], + wait_seconds=task_payload['wait_seconds'], + dify_agent_id=task_payload['dify_agent_id'], + platform_api_path=task_payload['platform_api_path'], + notify_user_ids_json=task_payload['notify_user_ids_json'], + notify_enabled=task_payload['notify_enabled'], + enabled=task_payload['enabled'], + actor_id=actor_id, + ) + task.data_source_type = task_payload['data_source_type'] + task.kb_sync_enabled = task_payload['kb_sync_enabled'] + task.kb_group_id = ( + int(task_payload['kb_group_id']) + if task_payload.get('kb_group_id') not in (None, '', 0, '0') + else None + ) + db.session.commit() + if cfg: + upsert_schedule_task_config(task.id, cfg) + imported += 1 + except Exception as exc: + errors.append(str(exc)) + skipped += 1 + db.session.commit() + return {'ok': True, 'imported': imported, 'skipped': skipped, 'errors': errors[:20]} diff --git a/backend/app/services/schedule/serialization.py b/backend/app/services/schedule/serialization.py new file mode 100644 index 00000000..107cbf52 --- /dev/null +++ b/backend/app/services/schedule/serialization.py @@ -0,0 +1,22 @@ +""" +backend/app/services/schedule/serialization.py + +用途:排程域 JSON 序列化辅助(SQL 预览、测试跑结果)。 +依赖:标准库 decimal/datetime。 +逻辑:api/schedule/common 与 test_run_service 共用;不依赖 api 层。 +""" +from __future__ import annotations + +import decimal +from datetime import date, datetime, timedelta + + +def safe_json_value(value): + """将 SQL 查询结果中的 Decimal/datetime 转为 JSON 可序列化类型。""" + if isinstance(value, decimal.Decimal): + return float(value) + if isinstance(value, (date, datetime)): + return value.isoformat() + if isinstance(value, timedelta): + return str(value) + return value diff --git a/backend/app/services/schedule/sql_preview_service.py b/backend/app/services/schedule/sql_preview_service.py new file mode 100644 index 00000000..827735d1 --- /dev/null +++ b/backend/app/services/schedule/sql_preview_service.py @@ -0,0 +1,55 @@ +""" +backend/app/services/schedule/sql_preview_service.py + +用途:排程抓取 SQL 预览(test-sql 业务编排)。 +依赖:services/schedule、sql_config、srm_service。 +逻辑:由 api/schedule/config.py 调用。 +""" +from __future__ import annotations + +from typing import Any + +from app.core.errors import AppError, NotFoundError +from app.services.schedule import _build_srm_conn_str +from app.services.schedule.serialization import safe_json_value +from app.services.schedule.srm_service import _fetch_records +from app.services.schedule.sql_config import _build_fetch_sql, get_schedule_sql_config_by_task_id + + +def preview_fetch_sql(task_id: int, data: dict[str, Any]) -> dict[str, Any]: + """ + 执行抓取 SQL 预览查询。 + Args: + task_id: ScheduleTask 主键。 + data: 可选 fetch_where_conditions、fetch_order_by、limit。 + Returns: + total、showing、limit、sql、columns、rows。 + Raises: + NotFoundError: 任务配置不存在。 + AppError: SQL 执行失败。 + """ + cfg = get_schedule_sql_config_by_task_id(task_id) + if not cfg: + raise NotFoundError(f'Config for task {task_id} not found') + custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip() + custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip() + limit = min(int(data.get('limit') or 10), 100) + base = cfg.base_fetch_sql or cfg.fetch_sql + sql = _build_fetch_sql(base, custom_where, custom_order_by) if cfg.base_fetch_sql else base + try: + if cfg.data_source and (not cfg.data_source.is_empty()): + conn_str = cfg.data_source.build_connection_string() + else: + conn_str = _build_srm_conn_str() + rows = _fetch_records(conn_str, sql) + result_rows = [{k: safe_json_value(v) for k, v in r.items()} for r in rows[:limit]] + return { + 'total': len(rows), + 'showing': len(result_rows), + 'limit': limit, + 'sql': sql, + 'columns': list(result_rows[0].keys()) if result_rows else [], + 'rows': result_rows, + } + except Exception as exc: + raise AppError(code='SYSTEM.HTTP_ERROR', message=str(exc), http_status=400, details={'sql': sql}) diff --git a/backend/app/services/schedule/test_run_service.py b/backend/app/services/schedule/test_run_service.py new file mode 100644 index 00000000..7f7b595e --- /dev/null +++ b/backend/app/services/schedule/test_run_service.py @@ -0,0 +1,293 @@ +""" +backend/app/services/schedule/test_run_service.py + +用途:排程 test-run 同步小规模试跑编排。 +依赖:models、scheduler_service、excel_service、srm_service、kb_sync。 +逻辑:由 api/schedule/config.py test-run 路由调用。 +""" +from __future__ import annotations + +import time as _time +import traceback +from datetime import datetime +from typing import Any + +from flask import current_app + +from app import db +from app.core.errors import AppError, NotFoundError +from app.models import ScheduleRun, ScheduleTask +from app.services.schedule import _build_srm_conn_str, _resolve_dify_agent, _resolve_schedule_user +from app.services.schedule.excel_service import export_schedule_result_excel +from app.services.schedule.scheduler_service import _generate_test_run_no, _notify_schedule_run_wecom +from app.services.schedule.serialization import safe_json_value +from app.services.schedule.srm_service import ( + _build_record_text, + _execute_writeback, + _fetch_records, + _run_check_job_loop, +) +from app.services.schedule.sql_config import _build_fetch_sql, get_schedule_sql_config_by_task_id + + +def _parse_kb_sync_flag(raw_value: Any) -> bool: + if isinstance(raw_value, str): + return raw_value.strip().lower() in ('1', 'true', 'yes', 'on') + return bool(raw_value) + + +def _build_test_run_callbacks(cfg, test_sql: str): + """构建 test-run 用的 fetch/writeback/pre_dify/build_record 回调。""" + def _test_fetch_fn(conn_str_arg): + return _fetch_records(conn_str_arg, test_sql) + + def _test_writeback_fn(conn_str_arg, *, row_id, run_no, dify_result, dify_message): + _execute_writeback(conn_str_arg, cfg.writeback_sql, (run_no, dify_result, dify_message, str(row_id))) + + test_pre_dify = None + test_build_record = None + if cfg.detail_sql: + + def _test_pre_dify(conn_str_arg, item, row_id_value): + try: + detail_rows = _fetch_records(conn_str_arg, cfg.detail_sql, params=(str(row_id_value),)) + except Exception as detail_exc: + return { + 'dify_result': '人工判定', + 'dify_message': f'查询成分明细失败:{detail_exc}', + 'writeback_srm': False, + 'writeback_err': str(detail_exc), + } + detail_lines = [] + for dr in detail_rows: + parts = [f"{cfg.header_labels.get(dk, dk)}: {dr.get(dk, '')}" for dk in cfg.detail_alias_order] + detail_lines.append(', '.join(parts)) + item['detail_text'] = '; '.join(detail_lines) if detail_lines else '' + item['_detail_rows'] = detail_rows + return None + + test_pre_dify = _test_pre_dify + + def _test_build_with_detail(conn_str_arg, item, row_id_value): + detail_rows = item.get('_detail_rows', []) + text = _build_record_text(item, cfg.alias_order, cfg.header_labels, detail_rows, cfg.detail_alias_order) + return (text, item.get('attachment')) + + test_build_record = _test_build_with_detail + else: + + def _test_build_simple(conn_str_arg, item, row_id_value): + text = _build_record_text(item, cfg.alias_order, cfg.header_labels) + return (text, item.get('attachment')) + + test_build_record = _test_build_simple + + return _test_fetch_fn, _test_writeback_fn, test_pre_dify, test_build_record + + +def _finalize_run_status(total_count: int, success_count: int, failed_count: int, errors: list) -> str: + if total_count == 0 and (not errors): + return 'success' + if failed_count == 0: + return 'success' + if success_count == 0: + return 'failed' + return 'partial_failed' + + +def execute_test_run( + task_id: int, + data: dict[str, Any], + *, + triggered_by_user_id: int | None, +) -> dict[str, Any]: + """ + 同步执行排程 test-run。 + Args: + task_id: ScheduleTask 主键。 + data: fetch_where/order、limit、kb_sync_enabled 等。 + triggered_by_user_id: 触发用户 id。 + Returns: + test-run API 响应 dict。 + Raises: + NotFoundError: 任务或配置不存在。 + AppError: 执行过程异常。 + """ + task = db.session.get(ScheduleTask, task_id) + if not task: + raise NotFoundError('Not found') + cfg = get_schedule_sql_config_by_task_id(task_id) + if not cfg: + raise NotFoundError(f'Config for task {task_id} not found') + + custom_where = str(data.get('fetch_where_conditions') or cfg.fetch_where_conditions).strip() + custom_order_by = str(data.get('fetch_order_by') or cfg.fetch_order_by).strip() + limit = min(int(data.get('limit') or 3), 10) + test_kb_sync_enabled = _parse_kb_sync_flag(data.get('kb_sync_enabled', False)) + base = cfg.base_fetch_sql or cfg.fetch_sql + test_sql = _build_fetch_sql(base, custom_where, custom_order_by) if cfg.base_fetch_sql else base + if cfg.data_source and (not cfg.data_source.is_empty()): + conn_str = cfg.data_source.build_connection_string() + else: + conn_str = _build_srm_conn_str() + agent = _resolve_dify_agent(task) if task else None + user = _resolve_schedule_user(task) if task else 'test_user' + wait_seconds = task.wait_seconds if task else 120 + dify_agent_id = task.dify_agent_id if task else None + + run = ScheduleRun( + run_no=_generate_test_run_no(), + schedule_task_id=task_id, + trigger_type='test', + triggered_by_user_id=triggered_by_user_id, + started_at=datetime.utcnow(), + status='running', + ) + db.session.add(run) + db.session.commit() + + from app.services.schedule.dify_snapshot import capture_dify_execution_snapshot + + capture_dify_execution_snapshot(run, task) + db.session.commit() + + if not cfg.fetch_sql: + run.status = 'success' + run.finished_at = datetime.utcnow() + run.error_message = '无抓取SQL,跳过外部系统数据抓取' + try: + if task.notify_enabled: + _notify_schedule_run_wecom(task, run) + except Exception as wecom_exc: + current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc) + db.session.commit() + return { + 'run_no': run.run_no, + 'run_id': run.id, + 'sql': '', + 'limit': 0, + 'total_count': 0, + 'success_count': 0, + 'failed_count': 0, + 'skipped_count': 0, + 'details': [], + 'errors': [], + 'step_logs': [{'step': 'no_fetch_sql', 'status': 'skipped', 'detail': '无抓取SQL,跳过外部系统数据抓取'}], + 'dify_agent_id': dify_agent_id, + } + + fetch_fn, writeback_fn, pre_dify_fn, build_record_fn = _build_test_run_callbacks(cfg, test_sql) + start_ts = _time.time() + try: + total_count, success_count, failed_count, skipped_count, details, errors, step_logs = _run_check_job_loop( + conn_str=conn_str, + run_no=run.run_no, + agent=agent, + user=user, + wait_seconds=wait_seconds, + run_id=run.id, + fetch_fn=fetch_fn, + build_record_fn=build_record_fn, + writeback_fn=writeback_fn, + writeback_sql=cfg.writeback_sql, + row_id_key=cfg.row_id_key, + log_prefix=cfg.log_prefix, + fetch_sql=test_sql, + max_rows=limit, + pre_dify_fn=pre_dify_fn, + dify_system_prompt=cfg.dify_system_prompt, + ) + duration_ms = int((_time.time() - start_ts) * 1000) + status = _finalize_run_status(total_count, success_count, failed_count, errors) + header_order = cfg.alias_order if cfg.alias_order else None + header_labels = cfg.header_labels if cfg.header_labels else None + detail_alias_order = cfg.detail_alias_order or [] + try: + file_data, file_name, file_size = export_schedule_result_excel( + run_no=run.run_no, + summary={ + 'status': status, + 'total_count': total_count, + 'success_count': success_count, + 'failed_count': failed_count, + 'duration_ms': duration_ms, + }, + details=details, + header_order=header_order, + header_labels=header_labels, + detail_alias_order=detail_alias_order, + ) + except Exception as excel_exc: + current_app.logger.error('[schedule-test-run] excel export failed: %s', excel_exc, exc_info=True) + file_data, file_name, file_size = (None, None, 0) + run.finished_at = datetime.utcnow() + run.duration_ms = duration_ms + run.status = status + run.total_count = total_count + run.success_count = success_count + run.failed_count = failed_count + run.skipped_count = skipped_count + run.step_logs = step_logs if step_logs else None + run.error_message = '; '.join(errors[:3]) if errors else None + run.excel_file_data = file_data + run.excel_file_name = file_name + run.excel_file_size = file_size or 0 + db.session.commit() + + if test_kb_sync_enabled: + try: + from app.services.schedule.kb_sync import sync_schedule_run_excel_to_kb + + db.session.refresh(task) + db.session.refresh(run) + sync_schedule_run_excel_to_kb(task, run, enabled=True, process_inline=True) + db.session.refresh(run) + except Exception as kb_exc: + db.session.rollback() + db.session.refresh(run) + current_app.logger.error('[schedule-test-run] kb sync failed: %s', kb_exc, exc_info=True) + run.kb_sync_status = 'failed' + run.kb_group_id = getattr(task, 'kb_group_id', None) + run.kb_sync_error = str(kb_exc) + db.session.commit() + + try: + if task.notify_enabled: + _notify_schedule_run_wecom(task, run) + except Exception as wecom_exc: + current_app.logger.error('[schedule-test-run] wecom notify failed: %s', wecom_exc) + + safe_details = [{k: safe_json_value(v) for k, v in item.items()} for item in details] + return { + 'run_no': run.run_no, + 'run_id': run.id, + 'sql': test_sql, + 'limit': limit, + 'total_count': total_count, + 'success_count': success_count, + 'failed_count': failed_count, + 'skipped_count': skipped_count, + 'details': safe_details, + 'errors': errors, + 'step_logs': step_logs, + 'dify_agent_id': dify_agent_id, + 'dify_execution_snapshot': run.dify_execution_snapshot, + 'kb_sync_status': run.kb_sync_status, + 'kb_sync_error': run.kb_sync_error, + 'kb_document_id': run.kb_document_id, + } + except Exception as exc: + db.session.rollback() + run = db.session.get(ScheduleRun, run.id) + duration_ms = int((_time.time() - start_ts) * 1000) + run.finished_at = datetime.utcnow() + run.duration_ms = duration_ms + run.status = 'failed' + run.error_message = str(exc) + db.session.commit() + raise AppError( + code='SYSTEM.HTTP_ERROR', + message=str(exc), + http_status=400, + details={'sql': test_sql, 'traceback': traceback.format_exc()}, + ) diff --git a/backend/tests/services/admin/test_agent_service.py b/backend/tests/services/admin/test_agent_service.py new file mode 100644 index 00000000..8b73bf62 --- /dev/null +++ b/backend/tests/services/admin/test_agent_service.py @@ -0,0 +1,63 @@ +""" +tests/services/admin/test_agent_service.py + +用途:agent_service CRUD 与权限绑定单元测试。 +""" +import pytest + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import Agent, User +from app.services.admin import agent_service + + +def test_agent_crud(app): + with app.app_context(): + created = agent_service.create_agent({ + 'name': 'Test Agent', + 'type': 'iframe', + 'dify_app_id': 'app-1', + 'extra_config': {'iframe_url': 'https://example.com'}, + }) + agent_id = created['id'] + + items = agent_service.list_agents() + assert any(item['id'] == agent_id for item in items) + + agent_service.update_agent(agent_id, {'description': 'updated'}) + refreshed = db.session.get(Agent, agent_id) + assert refreshed.description == 'updated' + + agent_service.delete_agent(agent_id) + assert db.session.get(Agent, agent_id) is None + + +def test_create_agent_requires_dify_app_id_for_api_type(app): + with app.app_context(): + with pytest.raises(ValidationError, match='App ID'): + agent_service.create_agent({'name': 'API Agent', 'type': 'api'}) + + +def test_update_agent_permissions(app): + with app.app_context(): + agent = Agent(name='perm-agent', type='iframe', is_active=True) + user_a = User(username='u-a', email='a@test.com', status='active', role='user') + user_b = User(username='u-b', email='b@test.com', status='active', role='user') + db.session.add_all([agent, user_a, user_b]) + db.session.commit() + + agent_service.update_agent_permissions(agent.id, [user_a.id]) + db.session.refresh(user_a) + assert any(a.id == agent.id for a in user_a.agents) + + agent_service.update_agent_permissions(agent.id, [user_b.id]) + db.session.refresh(user_a) + db.session.refresh(user_b) + assert user_a.agents == [] + assert any(a.id == agent.id for a in user_b.agents) + + +def test_test_agent_connectivity_not_found(app): + with app.app_context(): + with pytest.raises(NotFoundError): + agent_service.test_agent_connectivity(99999) diff --git a/backend/tests/services/admin/test_announcement_service.py b/backend/tests/services/admin/test_announcement_service.py new file mode 100644 index 00000000..4dad58a2 --- /dev/null +++ b/backend/tests/services/admin/test_announcement_service.py @@ -0,0 +1,43 @@ +""" +tests/services/admin/test_announcement_service.py + +用途:announcement_service CRUD 与活跃列表单元测试。 +""" +import pytest + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import Announcement +from app.services.admin import announcement_service + + +def test_announcement_crud(app): + with app.app_context(): + created = announcement_service.create_announcement( + {'title': 'Hello', 'content': 'World'} + ) + ann_id = created['id'] + + active = announcement_service.list_active_announcements() + assert len(active) == 1 + assert active[0]['title'] == 'Hello' + + admin_list = announcement_service.list_announcements() + assert len(admin_list) == 1 + assert admin_list[0]['is_active'] is True + + announcement_service.update_announcement(ann_id, {'title': 'Hi', 'content': 'There'}) + announcement_service.delete_announcement(ann_id) + assert db.session.get(Announcement, ann_id) is None + + +def test_create_announcement_validation(app): + with app.app_context(): + with pytest.raises(ValidationError): + announcement_service.create_announcement({'title': 'only title'}) + + +def test_update_announcement_not_found(app): + with app.app_context(): + with pytest.raises(NotFoundError): + announcement_service.update_announcement(99999, {'title': 'x', 'content': 'y'}) diff --git a/backend/tests/services/admin/test_dashboard_service.py b/backend/tests/services/admin/test_dashboard_service.py new file mode 100644 index 00000000..a6229c6e --- /dev/null +++ b/backend/tests/services/admin/test_dashboard_service.py @@ -0,0 +1,44 @@ +""" +tests/services/admin/test_dashboard_service.py + +用途:dashboard_service 统计聚合单元测试。 +""" +from app import db +from app.models import Agent, ChatLog, Feedback, PermissionRequest, User +from app.services.admin.dashboard_service import ( + compute_dashboard_badges, + compute_dashboard_summary, + compute_legacy_dashboard_stats, +) + + +def test_compute_dashboard_summary_empty(app): + with app.app_context(): + summary = compute_dashboard_summary() + assert summary['agent_count'] == 0 + assert summary['user_count'] == 0 + assert summary['total_conversations'] == 0 + assert summary['avg_score'] == 0.0 + + +def test_compute_dashboard_badges_counts_pending(app): + with app.app_context(): + user = User(username='pending-u', email='p@example.com', status='pending', role='user') + agent = Agent(name='a1', is_active=True) + db.session.add_all([user, agent]) + db.session.flush() + req = PermissionRequest(user_id=user.id, agent_id=agent.id, status='pending', reason='test') + db.session.add(req) + db.session.commit() + + badges = compute_dashboard_badges() + assert badges['pending_approvals'] >= 1 + assert badges['pending_requests'] >= 1 + + +def test_compute_legacy_dashboard_stats_keys(app): + with app.app_context(): + stats = compute_legacy_dashboard_stats() + assert 'total_users' in stats + assert 'pending_approvals' in stats + assert 'pending_requests' in stats diff --git a/backend/tests/services/admin/test_database_admin_service.py b/backend/tests/services/admin/test_database_admin_service.py new file mode 100644 index 00000000..5e3cbe13 --- /dev/null +++ b/backend/tests/services/admin/test_database_admin_service.py @@ -0,0 +1,40 @@ +""" +tests/services/admin/test_database_admin_service.py + +用途:database_admin_service 表浏览与 chat_logs 批量删除单元测试。 +""" +import pytest + +from app import db +from app.core.errors import ValidationError +from app.models import Agent, ChatLog, User +from app.services.admin import database_admin_service + + +def test_get_table_count_and_batch_delete_chat_logs(app): + with app.app_context(): + agent = Agent(name='db-agent', type='api', dify_app_id='app-d', dify_api_key='key-d') + user = User(username='db-user', email='db@example.com', real_name='db-user', role='user') + db.session.add_all([agent, user]) + db.session.flush() + log = ChatLog(user_id=user.id, agent_id=agent.id, query='q', answer='a', tokens_used=1) + db.session.add(log) + db.session.commit() + log_id = log.id + + count = database_admin_service.get_table_count('chat_logs', {'real_name': 'db-user'}) + assert count['total'] == 1 + + rows = database_admin_service.get_table_data('chat_logs', {'real_name': 'db-user'}) + assert len(rows) == 1 + assert rows[0]['username'] == 'db-user' + + result = database_admin_service.batch_delete_chat_logs([log_id]) + assert result['deleted_count'] == 1 + assert db.session.get(ChatLog, log_id) is None + + +def test_batch_delete_chat_logs_validation(app): + with app.app_context(): + with pytest.raises(ValidationError): + database_admin_service.batch_delete_chat_logs([]) diff --git a/backend/tests/services/admin/test_department_service.py b/backend/tests/services/admin/test_department_service.py new file mode 100644 index 00000000..91c243c7 --- /dev/null +++ b/backend/tests/services/admin/test_department_service.py @@ -0,0 +1,45 @@ +""" +tests/services/admin/test_department_service.py + +用途:department_service CRUD 单元测试。 +""" +import pytest + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import Department +from app.services.admin.department_service import ( + create_department, + delete_department, + list_departments, + update_department, +) + + +def test_department_crud(app): + with app.app_context(): + created = create_department({'name': 'R&D', 'code': 'RD', 'company': 'HX'}) + assert created['name'] == 'R&D' + + items = list_departments() + assert any(item['code'] == 'RD' for item in items) + + update_department(created['id'], {'description': 'Research'}) + dept = db.session.get(Department, created['id']) + assert dept.description == 'Research' + + delete_department(created['id']) + assert db.session.get(Department, created['id']) is None + + +def test_create_department_rejects_duplicate_name(app): + with app.app_context(): + create_department({'name': 'Sales'}) + with pytest.raises(ValidationError, match='Name exists'): + create_department({'name': 'Sales'}) + + +def test_update_department_not_found(app): + with app.app_context(): + with pytest.raises(NotFoundError): + update_department(99999, {'name': 'X'}) diff --git a/backend/tests/services/admin/test_faq_service.py b/backend/tests/services/admin/test_faq_service.py new file mode 100644 index 00000000..a47eb484 --- /dev/null +++ b/backend/tests/services/admin/test_faq_service.py @@ -0,0 +1,65 @@ +""" +tests/services/admin/test_faq_service.py + +用途:faq_service 全局常用问题 CRUD 单元测试。 +""" +import pytest + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import Agent, QuickQuestion +from app.services.admin import faq_service + + +def test_quick_question_crud(app): + with app.app_context(): + agent = Agent(name='faq-agent', type='api', dify_app_id='app-1', dify_api_key='key-1') + db.session.add(agent) + db.session.commit() + + created = faq_service.create_quick_question( + { + 'title': '请假', + 'question': '如何请假?', + 'agent_id': agent.id, + 'answer': '在 OA 提交申请', + 'cache_enabled': True, + } + ) + qq_id = created['id'] + + items = faq_service.list_quick_questions(stale_only=False) + assert len(items) == 1 + assert items[0]['title'] == '请假' + assert items[0]['agent_name'] == 'faq-agent' + + faq_service.update_quick_question(qq_id, {'title': '请假流程'}) + qq = db.session.get(QuickQuestion, qq_id) + assert qq.title == '请假流程' + + faq_service.delete_quick_question(qq_id) + assert db.session.get(QuickQuestion, qq_id) is None + + +def test_update_quick_question_not_found(app): + with app.app_context(): + with pytest.raises(NotFoundError): + faq_service.update_quick_question(99999, {'title': 'x'}) + + +def test_create_quick_question_requires_cache_answer(app): + with app.app_context(): + agent = Agent(name='faq-agent-2', type='api', dify_app_id='app-2', dify_api_key='key-2') + db.session.add(agent) + db.session.commit() + + with pytest.raises(ValidationError): + faq_service.create_quick_question( + { + 'title': 't', + 'question': 'q', + 'agent_id': agent.id, + 'cache_enabled': True, + 'answer': '', + } + ) diff --git a/backend/tests/services/admin/test_guide_service.py b/backend/tests/services/admin/test_guide_service.py new file mode 100644 index 00000000..75a8778a --- /dev/null +++ b/backend/tests/services/admin/test_guide_service.py @@ -0,0 +1,49 @@ +""" +tests/services/admin/test_guide_service.py + +用途:guide_service CRUD 单元测试(MinIO 上传 mock)。 +""" +import pytest + +from app import db +from app.core.errors import NotFoundError +from app.models import Agent, AgentGuide +from app.services.admin import guide_service + + +def test_guide_crud(app, monkeypatch): + with app.app_context(): + agent = Agent(name='guide-agent', type='iframe', is_active=True) + db.session.add(agent) + db.session.commit() + + monkeypatch.setattr('app.services.admin.guide_service.minio_service.delete_file', lambda _path: None) + + created = guide_service.create_guide( + { + 'agent_id': agent.id, + 'file_name': 'intro.pdf', + 'file_type': 'pdf', + 'file_path': 'guides/intro.pdf', + 'file_size': 100, + }, + created_by_id=1, + ) + guide_id = created['id'] + + items = guide_service.list_guides(agent_id=agent.id) + assert len(items) == 1 + assert items[0]['file_name'] == 'intro.pdf' + + guide_service.update_guide(guide_id, {'remark': 'hello'}) + guide = db.session.get(AgentGuide, guide_id) + assert guide.remark == 'hello' + + guide_service.delete_guide(guide_id) + assert db.session.get(AgentGuide, guide_id) is None + + +def test_delete_guide_not_found(app): + with app.app_context(): + with pytest.raises(NotFoundError): + guide_service.delete_guide(99999) diff --git a/backend/tests/services/admin/test_permission_service.py b/backend/tests/services/admin/test_permission_service.py new file mode 100644 index 00000000..700bc21f --- /dev/null +++ b/backend/tests/services/admin/test_permission_service.py @@ -0,0 +1,79 @@ +""" +tests/services/admin/test_permission_service.py + +用途:permission_service 批量授权与权限申请审批单元测试。 +""" +import pytest + +from app import db +from app.core.errors import NotFoundError, ValidationError +from app.models import Agent, PermissionRequest, User +from app.services.admin import permission_service + + +def test_update_user_permissions(app): + with app.app_context(): + agent = Agent(name='perm-agent', type='api', dify_app_id='app-p', dify_api_key='key-p') + user = User(username='perm-user', email='perm@example.com', role='user') + db.session.add_all([agent, user]) + db.session.commit() + + permission_service.update_user_permissions(user.id, {'agent_ids': [agent.id]}) + db.session.refresh(user) + assert len(user.agents) == 1 + assert user.agents[0].id == agent.id + + +def test_batch_update_permissions_add(app, monkeypatch): + with app.app_context(): + agent = Agent(name='batch-agent', type='api', dify_app_id='app-b', dify_api_key='key-b') + user = User(username='batch-user', email='batch@example.com', role='user') + db.session.add_all([agent, user]) + db.session.commit() + + monkeypatch.setattr( + 'app.services.admin.permission_service.send_wecom_event_message', + lambda **kwargs: None, + ) + + result = permission_service.batch_update_permissions( + {'user_ids': [user.id], 'agent_ids': [agent.id], 'action': 'add'} + ) + assert result['updated_count'] == 1 + db.session.refresh(user) + assert agent in user.agents + + +def test_batch_update_permissions_no_users(app): + with app.app_context(): + with pytest.raises(ValidationError): + permission_service.batch_update_permissions({'user_ids': [], 'agent_ids': [1]}) + + +def test_permission_request_approve(app, monkeypatch): + with app.app_context(): + agent = Agent(name='req-agent', type='api', dify_app_id='app-r', dify_api_key='key-r') + user = User(username='req-user', email='req@example.com', role='user') + db.session.add_all([agent, user]) + db.session.flush() + req = PermissionRequest(user_id=user.id, agent_id=agent.id, reason='need access', status='pending') + db.session.add(req) + db.session.commit() + + monkeypatch.setattr( + 'app.services.admin.permission_service.send_wecom_event_message', + lambda **kwargs: None, + ) + + permission_service.approve_permission_request(req.id) + db.session.refresh(req) + db.session.refresh(user) + assert req.status == 'approved' + assert req.reviewed_at is not None + assert agent in user.agents + + +def test_permission_request_not_found(app): + with app.app_context(): + with pytest.raises(NotFoundError): + permission_service.approve_permission_request(99999) diff --git a/backend/tests/services/admin/test_report_service.py b/backend/tests/services/admin/test_report_service.py new file mode 100644 index 00000000..ae591ab3 --- /dev/null +++ b/backend/tests/services/admin/test_report_service.py @@ -0,0 +1,35 @@ +""" +tests/services/admin/test_report_service.py + +用途:report_service 报表聚合单元测试。 +""" +from app import db +from app.models import Agent, ChatLog, Feedback, User +from app.services.admin import report_service + + +def test_build_usage_report(app): + with app.app_context(): + agent = Agent(name='report-agent', type='api', dify_app_id='app-r', dify_api_key='key-r') + user = User(username='report-user', email='report@example.com', role='user') + db.session.add_all([agent, user]) + db.session.flush() + db.session.add(ChatLog(user_id=user.id, agent_id=agent.id, query='hi', answer='ok', tokens_used=1)) + db.session.commit() + + data = report_service.build_usage_report(user_page=1, user_page_size=10) + assert data['total'] == 1 + assert data['by_user'][0]['username'] == 'report-user' + assert data['by_agent'][0]['agent'] == 'report-agent' + + +def test_build_feedback_report(app): + with app.app_context(): + db.session.add(Feedback(score=5)) + db.session.add(Feedback(score=3)) + db.session.commit() + + data = report_service.build_feedback_report() + assert data['total'] == 2 + assert data['avg_score'] == 4.0 + assert len(data['distribution']) == 2 diff --git a/backend/tests/services/admin/test_user_service.py b/backend/tests/services/admin/test_user_service.py new file mode 100644 index 00000000..f880220e --- /dev/null +++ b/backend/tests/services/admin/test_user_service.py @@ -0,0 +1,23 @@ +""" +tests/services/admin/test_user_service.py + +用途:user_service 管理端用户 CRUD 单元测试。 +""" +from app import db +from app.models import User +from app.services.admin import user_service + + +def test_approve_and_reject_user(app): + with app.app_context(): + user = User(username='svc-user', email='svc@example.com', role='user', status='pending') + db.session.add(user) + db.session.commit() + + user_service.approve_user(user.id) + db.session.refresh(user) + assert user.status == 'active' + + user_service.reject_user(user.id) + db.session.refresh(user) + assert user.status == 'rejected' diff --git a/backend/tests/services/admin/test_wecom_admin_service.py b/backend/tests/services/admin/test_wecom_admin_service.py new file mode 100644 index 00000000..e047f366 --- /dev/null +++ b/backend/tests/services/admin/test_wecom_admin_service.py @@ -0,0 +1,21 @@ +""" +tests/services/admin/test_wecom_admin_service.py + +用途:wecom_admin_service 绑定统计单元测试。 +""" +from app import db +from app.models import User +from app.services.admin import wecom_admin_service + + +def test_binding_stats(app): + with app.app_context(): + active_bound = User(username='bound1', email='b1@example.com', role='user', status='active', wecom_userid='wx1') + active_unbound = User(username='unbound1', email='u1@example.com', role='user', status='active') + db.session.add_all([active_bound, active_unbound]) + db.session.commit() + + stats = wecom_admin_service.binding_stats() + assert stats['total_active'] == 2 + assert stats['bound'] == 1 + assert stats['unbound'] == 1 diff --git a/backend/tests/services/schedule/test_import_service.py b/backend/tests/services/schedule/test_import_service.py new file mode 100644 index 00000000..2d3c0643 --- /dev/null +++ b/backend/tests/services/schedule/test_import_service.py @@ -0,0 +1,15 @@ +""" +tests/services/schedule/test_import_service.py + +用途:import_service 批量导入参数校验单元测试。 +""" +import pytest + +from app.core.errors import ValidationError +from app.services.schedule.import_service import import_schedules_from_payload + + +def test_import_schedules_rejects_non_list(app): + with app.app_context(): + with pytest.raises(ValidationError, match='schedules missing'): + import_schedules_from_payload({'bad': True}, actor_id=1) diff --git a/backend/tests/test_admin_create_user_casdoor.py b/backend/tests/test_admin_create_user_casdoor.py index 8682eede..ec2cb4c3 100644 --- a/backend/tests/test_admin_create_user_casdoor.py +++ b/backend/tests/test_admin_create_user_casdoor.py @@ -2,7 +2,7 @@ tests/test_admin_create_user_casdoor.py 用途:验证管理端创建/编辑用户时 Casdoor 同步行为。 -依赖:admin create_user/update_user、user._sync_casdoor_*。 +依赖:admin create_user/update_user、services/auth/casdoor_service。 """ import pytest @@ -10,6 +10,7 @@ import pytest from app import db from app.models import User from app.api import user as user_api +from app.services.auth import casdoor_service NEW_USER_PAYLOAD = { @@ -39,7 +40,7 @@ def test_admin_create_user_syncs_casdoor(client, admin_headers, monkeypatch): casdoor_calls['add_user'] += 1 casdoor_calls['payload'] = payload - monkeypatch.setattr(user_api, '_casdoor_add_user', fake_add_user) + monkeypatch.setattr(casdoor_service, 'casdoor_add_user', fake_add_user) res = client.post('/api/admin/users', json=NEW_USER_PAYLOAD, headers=admin_headers) assert res.status_code == 201 @@ -70,7 +71,7 @@ def test_admin_create_user_skips_casdoor_when_not_configured(client, admin_heade def fake_add_user(_payload): casdoor_calls['add_user'] += 1 - monkeypatch.setattr(user_api, '_casdoor_add_user', fake_add_user) + monkeypatch.setattr(casdoor_service, 'casdoor_add_user', fake_add_user) payload = dict(NEW_USER_PAYLOAD) payload.update({ @@ -100,7 +101,7 @@ def test_admin_create_user_rolls_back_when_casdoor_fails(client, admin_headers, http_status=502, ) - monkeypatch.setattr(user_api, '_casdoor_add_user', fake_add_user) + monkeypatch.setattr(casdoor_service, 'casdoor_add_user', fake_add_user) payload = dict(NEW_USER_PAYLOAD) payload.update({ @@ -155,8 +156,8 @@ def test_admin_update_user_skips_casdoor_profile_sync(client, admin_headers, mon def fake_set_password(*_args, **_kwargs): casdoor_calls['set_password'] += 1 - monkeypatch.setattr(user_api, '_casdoor_update_user', fake_update_user) - monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password) + monkeypatch.setattr(casdoor_service, 'casdoor_update_user', fake_update_user) + monkeypatch.setattr(casdoor_service, 'casdoor_set_password', fake_set_password) res = client.put( f'/api/admin/users/{user.id}', @@ -186,7 +187,7 @@ def test_admin_update_user_syncs_casdoor_password(client, admin_headers, monkeyp def fake_set_password(user_owner, user_name, old_password, new_password): casdoor_calls.append((user_owner, user_name, old_password, new_password)) - monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password) + monkeypatch.setattr(casdoor_service, 'casdoor_set_password', fake_set_password) res = client.put( f'/api/admin/users/{user.id}', @@ -217,7 +218,7 @@ def test_admin_update_user_rolls_back_when_casdoor_password_fails(client, admin_ http_status=502, ) - monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password) + monkeypatch.setattr(casdoor_service, 'casdoor_set_password', fake_set_password) res = client.put( f'/api/admin/users/{user.id}', @@ -252,8 +253,8 @@ def test_admin_update_user_provisions_missing_casdoor_user_with_password(client, raise RuntimeError("Casdoor set-password failed: {'status': 'error', 'msg': \"The user: organization_HX/legacy_user doesn't exist\"}") monkeypatch.setattr(user_api, '_casdoor_update_user', fake_update_user) - monkeypatch.setattr(user_api, '_casdoor_add_user', fake_add_user) - monkeypatch.setattr(user_api, '_casdoor_set_password', fake_set_password) + monkeypatch.setattr(casdoor_service, 'casdoor_add_user', fake_add_user) + monkeypatch.setattr(casdoor_service, 'casdoor_set_password', fake_set_password) res = client.put( f'/api/admin/users/{user.id}', diff --git a/backend/tests/test_comprehensive.py b/backend/tests/test_comprehensive.py index 5dccb064..708b4c09 100644 --- a/backend/tests/test_comprehensive.py +++ b/backend/tests/test_comprehensive.py @@ -7,7 +7,7 @@ from app.models import User, Agent # Test File: backend/tests/test_comprehensive.py # Purpose: Comprehensive automated tests for backend functionalities including # User Management, Agent Management, and Permissions. -# References: backend/app/api/admin.py, backend/app/api/user.py, backend/app/models.py +# References: backend/app/api/admin/, backend/app/api/user.py, backend/app/models.py # Logic: # 1. Test User Registration (with new fields) # 2. Test Admin User Approval diff --git a/backend/tests/test_wecom_debug_api.py b/backend/tests/test_wecom_debug_api.py index a2514af0..8761e756 100644 --- a/backend/tests/test_wecom_debug_api.py +++ b/backend/tests/test_wecom_debug_api.py @@ -1,7 +1,7 @@ from app import db from app.models import User -from app.api import admin as admin_api -from app.api import user as user_api +from app.services.auth import wecom_auth_service +from app.services.admin import wecom_admin_service class DummyResponse: @@ -37,7 +37,7 @@ def test_wecom_debug_user_by_code_returns_raw_user_and_match_preview(client, app db.session.add(user) db.session.commit() - monkeypatch.setattr(user_api, '_get_wecom_access_token', lambda: 'token-1') + monkeypatch.setattr(wecom_auth_service, 'get_access_token', lambda: 'token-1') def fake_get(url, params=None, timeout=8): if 'cgi-bin/auth/getuserinfo' in url: @@ -52,7 +52,7 @@ def test_wecom_debug_user_by_code_returns_raw_user_and_match_preview(client, app }) raise AssertionError(f'unexpected url: {url}') - monkeypatch.setattr(admin_api.requests, 'get', fake_get) + monkeypatch.setattr(wecom_admin_service.requests, 'get', fake_get) res = client.post( '/api/admin/wecom/debug-user-by-code', @@ -76,14 +76,14 @@ def test_wecom_debug_user_by_code_returns_scope_error_when_only_openid(client, a WECOM_SECRET='secret-test', ) - monkeypatch.setattr(user_api, '_get_wecom_access_token', lambda: 'token-1') + monkeypatch.setattr(wecom_auth_service, 'get_access_token', lambda: 'token-1') def fake_get(url, params=None, timeout=8): if 'cgi-bin/auth/getuserinfo' in url: return DummyResponse({'errcode': 0, 'errmsg': 'ok', 'openid': 'oExternal_xx'}) raise AssertionError(f'unexpected url: {url}') - monkeypatch.setattr(admin_api.requests, 'get', fake_get) + monkeypatch.setattr(wecom_admin_service.requests, 'get', fake_get) res = client.post( '/api/admin/wecom/debug-user-by-code', diff --git a/docs/faq_cache_ops_manual.md b/docs/faq_cache_ops_manual.md index 18f6bf79..5126a4f8 100644 --- a/docs/faq_cache_ops_manual.md +++ b/docs/faq_cache_ops_manual.md @@ -557,7 +557,7 @@ FAQ_HOT_ENABLED=false | PG 候选存储 | `backend/app/services/hot_faq_candidate_store.py` | | KB 失效标记 | `backend/app/services/faq_kb_invalidation.py` | | CLI | `backend/app/cli/faq_commands.py` | -| 管理 API | `backend/app/api/admin.py` | +| 管理 API | `backend/app/api/admin/`(如 `quick_questions.py`、`faq_candidates.py`) | | 对话入口 | `backend/app/api/chat.py`(Dify 前 `try_match`) | | 管理 UI | `frontend/src/features/admin/modules/questions/` | | 环境变量 | `.env.shared` → `FAQ_HOT_*` | diff --git a/docs/project_context.md b/docs/project_context.md index 82a2faba..2354ec61 100644 --- a/docs/project_context.md +++ b/docs/project_context.md @@ -36,7 +36,7 @@ hxops/ ├── backend/ # Flask 后端 │ ├── app/ │ │ ├── api/ # API 路由 (Blueprint) -│ │ │ ├── admin.py # 管理员接口 +│ │ │ ├── admin/ # 管理员接口(Wave 3 分包) │ │ │ ├── chat.py # 对话接口 (SSE流式) │ │ │ └── ... │ │ ├── services/ # 业务逻辑 (DifyService) diff --git a/docs/refactor/backend_architecture_refactor.md b/docs/refactor/backend_architecture_refactor.md index a70d4252..6aeb5875 100644 --- a/docs/refactor/backend_architecture_refactor.md +++ b/docs/refactor/backend_architecture_refactor.md @@ -56,7 +56,7 @@ | 问题 | 典型文件 | 约行数 | | --- | --- | --- | -| API god 文件 | `api/user.py`、`api/chat.py`、`api/admin.py` | 1400–2200 | +| API god 文件 | `api/user.py`、`api/chat.py`(`api/admin.py` 已拆至 `api/admin/*`) | 1400–2200 | | Service monolith | `services/text2sql.py`、`shipping_notice/tools.py` | 1200–2000 | | 单文件模型 | `models.py` | 796(30+ 模型) | | 错误响应不统一 | API 混用 `AppError` 与 `jsonify({'error':...})` | 300+ 处 | @@ -134,7 +134,7 @@ backend/ │ │ │ ├── faq.py │ │ │ └── wecom.py # 企微 OAuth / 绑定 │ │ │ -│ │ ├── admin/ # ← 现有 api/admin.py,Wave 3 +│ │ ├── admin/ # ✅ 已从 api/admin.py 迁包(Wave 3 完成) │ │ │ ├── users.py │ │ │ ├── agents.py │ │ │ ├── departments.py @@ -261,7 +261,7 @@ Python 3 中 **模块文件与同名包不能并存**,否则包覆盖模块、 | --- | --- | | `models.py` 与 `models/` | Wave 1:拆入 `models/*.py` 后**删除** `models.py` | | `api/chat.py` 与 `api/chat/` | 先 rename 为 `chat/_legacy.py`,再建包 | -| 同理 `user.py`、`admin.py`、`knowledge_base.py` | 标准步骤见 §9.2 | +| 同理 `user.py`、`knowledge_base.py` | 标准步骤见 §9.2(`admin.py` 已删除,仅保留 `api/admin/` 包) | **Wave 0 已建、无冲突的分包**:`api/schedule/`、`api/workspace/`、`api/tools/`、`api/internal/`、`core/`、`jobs/`、`schemas/`、`services/{chat,user,admin,...}/`。 @@ -274,7 +274,7 @@ Python 3 中 **模块文件与同名包不能并存**,否则包覆盖模块、 | `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/admin.py` | `api/admin/*` + `services/admin/*` | 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 | | `app/api/workspace_*.py` | `api/workspace/*` | 0→1 | @@ -400,7 +400,7 @@ jobs/handlers/kb_clean.py # worker 执行 → services/kb → edkb_system | --- | --- | --- | --- | --- | | **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 + 企微 | -| **admin** | `/api/admin` | `api/admin/` | `services/admin/*` | `admin.py` ~1455 行;54 路由 | +| **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`;异步清洗 | | **agents** | `/api/agents` | `api/agents/` | 薄,可保留单文件 | ~118 行 | diff --git a/docs/tec.md b/docs/tec.md index 4a12510a..e4194136 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -671,7 +671,7 @@ OA_STATUS_SYNC_BATCH_SIZE=100 - `backend/app/api/chat.py` - `backend/app/models.py` -- `backend/app/api/admin.py` +- `backend/app/api/admin/`(users、agents、permissions、wecom 等子模块) - `backend/app/services/wecom_notify.py` - `backend/app/services/knowledge_cleaning/queue_service.py` diff --git a/frontend/src/features/admin/api/admin.api.ts b/frontend/src/features/admin/api/admin.api.ts index a762180d..ea80710b 100644 --- a/frontend/src/features/admin/api/admin.api.ts +++ b/frontend/src/features/admin/api/admin.api.ts @@ -247,14 +247,14 @@ export const unbindAdminWecomUser = (userId: number) => body: JSON.stringify({ user_id: userId }), }); -// Announcements (admin module uses user endpoints) -export const listAnnouncements = () => requestJson('/api/user/announcements', auth()); +// Announcements +export const listAnnouncements = () => requestJson('/api/admin/announcements', auth()); export const createAnnouncement = (payload: Record) => - requestJson('/api/user/announcements', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) }); + requestJson('/api/admin/announcements', { method: 'POST', ...jsonAuth(), body: JSON.stringify(payload) }); export const updateAnnouncement = (id: number, payload: Record) => - requestJson(`/api/user/announcements/${id}`, { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) }); + requestJson(`/api/admin/announcements/${id}`, { method: 'PUT', ...jsonAuth(), body: JSON.stringify(payload) }); export const deleteAnnouncement = (id: number) => - requestJson(`/api/user/announcements/${id}`, { method: 'DELETE', ...auth() }); + requestJson(`/api/admin/announcements/${id}`, { method: 'DELETE', ...auth() }); // Quick questions export const listAdminQuickQuestions = () => requestJson('/api/admin/quick-questions', auth()); diff --git a/frontend/src/features/auth/composables/useLoginLanding.ts b/frontend/src/features/auth/composables/useLoginLanding.ts index 8f6e228f..3bf76695 100644 --- a/frontend/src/features/auth/composables/useLoginLanding.ts +++ b/frontend/src/features/auth/composables/useLoginLanding.ts @@ -15,7 +15,7 @@ export function useLoginLanding() { const fetchAnnouncements = async () => { try { - announcements.value = await requestJson('/api/user/announcements'); + announcements.value = await requestJson('/api/workspace/announcements'); } catch (e) { console.error('Failed to load announcements', e); } diff --git a/frontend/src/features/workspace/composables/useWorkspaceHome.ts b/frontend/src/features/workspace/composables/useWorkspaceHome.ts index bc0a8519..4bc462b9 100644 --- a/frontend/src/features/workspace/composables/useWorkspaceHome.ts +++ b/frontend/src/features/workspace/composables/useWorkspaceHome.ts @@ -194,7 +194,7 @@ export function useWorkspaceHome(deps: WorkspaceDeps, options: HomeOptions) { const fetchAnnouncements = async () => { try { - announcements.value = await requestJson('/api/user/announcements'); + announcements.value = await requestJson('/api/workspace/announcements'); } catch (e) { console.error('Failed to load announcements', e); }