refactor(backend): 重构后端
This commit is contained in:
1 parent
c8054476c1
commit
bba6e6f221
32 files changed
+252
-296
No files matched your search
@@ -152,7 +152,7 @@ docker compose logs -f hxops-backend
|
||||
- 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。
|
||||
- ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。
|
||||
- 📝 **注释两层标准(强制)**:新建或调整代码须满足 §5 文件层 + 函数层注释;AI 生成/重构代码同样适用,不得省略。
|
||||
- ⚠️ **错误处理统一契约**:JSON API 使用 `{ success, data | error, request_id }` envelope;后端业务失败 **`raise AppError` 子类**(`app/errors.py`),禁止新写 `jsonify({"error": ...})`;前端 HTTP 统一 **`requestJson`**(`@/shared/api/client`),失败为 **`BusinessError`**,在 composable/view 用 **`useMessage()`** 展示;新增 `error.code` 须同步四语言 **`locales/*/errors.json`**。详见 **[docs/convention/error_handling.md](docs/convention/error_handling.md)**。
|
||||
- ⚠️ **错误处理统一契约**:JSON API 使用 `{ success, data | error, request_id }` envelope;后端业务失败 **`raise AppError` 子类**(`app/core/errors.py`),禁止新写 `jsonify({"error": ...})`;前端 HTTP 统一 **`requestJson`**(`@/shared/api/client`),失败为 **`BusinessError`**,在 composable/view 用 **`useMessage()`** 展示;新增 `error.code` 须同步四语言 **`locales/*/errors.json`**。详见 **[docs/convention/error_handling.md](docs/convention/error_handling.md)**。
|
||||
- ⚠️ 改动**数据库结构、部署脚本(`scripts/`、`Jenkinsfile`、`docker-compose.yml`)或敏感配置**前,先说明影响面再动手。
|
||||
|
||||
合并前最低自检(详见 [新人文档 §3.3](docs/新人环境搭建与配置文档.md)):前后端可启动、`frontend/` 改动后 `npm run build` 通过、关键页面与登录可用。
|
||||
|
||||
@@ -60,8 +60,6 @@ def create_app(config_name='default'):
|
||||
start_scheduler(app)
|
||||
from app.services.fixed_assets_snapshot import FixedAssetsSnapshotService
|
||||
FixedAssetsSnapshotService.start_worker(app)
|
||||
from app.cli.faq_commands import init_app as init_faq_cli
|
||||
init_faq_cli(app)
|
||||
|
||||
@app.before_request
|
||||
def _sync_persisted_settings():
|
||||
|
||||
+54
-18
@@ -672,7 +672,11 @@ def login():
|
||||
Can be disabled via AUTH_ALLOW_LOCAL_PASSWORD_LOGIN=false.
|
||||
"""
|
||||
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_PASSWORD_LOGIN', True)):
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='Password login is disabled. Please use Casdoor login.', http_status=403, details={'error_code': 'PASSWORD_LOGIN_DISABLED'})
|
||||
raise AppError(
|
||||
code='AUTH.PASSWORD_LOGIN_DISABLED',
|
||||
message='Password login is disabled. Please use Casdoor login.',
|
||||
http_status=403,
|
||||
)
|
||||
|
||||
def _attempt_login():
|
||||
data = request.get_json() or {}
|
||||
@@ -728,7 +732,11 @@ def casdoor_password_login():
|
||||
Direct login with username/password against Casdoor (no browser redirect).
|
||||
"""
|
||||
if (current_app.config.get('AUTH_LOGIN_MODE') or 'casdoor').lower() != 'casdoor':
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='Casdoor password login is disabled by AUTH_LOGIN_MODE', http_status=403, details={'error_code': 'CASDOOR_PASSWORD_LOGIN_DISABLED'})
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_PASSWORD_LOGIN_DISABLED',
|
||||
message='Casdoor password login is disabled by AUTH_LOGIN_MODE',
|
||||
http_status=403,
|
||||
)
|
||||
data = request.get_json() or {}
|
||||
username = _clean_str(data.get('username'))
|
||||
password = data.get('password') or ''
|
||||
@@ -939,7 +947,11 @@ def casdoor_refresh():
|
||||
except Exception as e:
|
||||
message = str(e)
|
||||
if 'unsupported_grant_type' in message or 'refresh_token is not supported' in message:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='Casdoor refresh token is not supported by current application config', http_status=400, details={'error_code': 'CASDOOR_REFRESH_UNSUPPORTED'})
|
||||
raise AppError(
|
||||
code='AUTH.CASDOOR_REFRESH_UNSUPPORTED',
|
||||
message='Casdoor refresh token is not supported by current application config',
|
||||
http_status=400,
|
||||
)
|
||||
current_app.logger.exception('[casdoor_refresh] failed refresh=%s', _token_brief(refresh_token))
|
||||
raise UnauthorizedError(f'Casdoor refresh failed: {str(e)}')
|
||||
|
||||
@@ -986,7 +998,11 @@ def wecom_login():
|
||||
if not wecom_userid_value:
|
||||
_write_login_audit('wecom', 'failed', reason=f"not_in_agent_scope:openid={wecom_openid_value or ''}", error_code='WECOM_NOT_IN_AGENT_SCOPE')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='当前企业微信账号未授权登录该应用:账号不在自建应用的可见范围内,或不是本企业成员。请管理员到「企业微信后台 → 应用管理 → 该应用 → 可见范围」中加入该成员所在的部门或个人。', http_status=401, details={'error_code': 'WECOM_NOT_IN_AGENT_SCOPE'})
|
||||
raise AppError(
|
||||
code='WECOM_NOT_IN_AGENT_SCOPE',
|
||||
message='当前企业微信账号未授权登录该应用:账号不在自建应用的可见范围内,或不是本企业成员。请管理员到「企业微信后台 → 应用管理 → 该应用 → 可见范围」中加入该成员所在的部门或个人。',
|
||||
http_status=401,
|
||||
)
|
||||
user_resp = requests.get('https://qyapi.weixin.qq.com/cgi-bin/user/get', params={'access_token': access_token, 'userid': wecom_userid_value}, timeout=8)
|
||||
wecom_user = user_resp.json()
|
||||
wecom_userid_for_audit = wecom_user.get('userid') or wecom_userid_for_audit
|
||||
@@ -1012,7 +1028,11 @@ def wecom_login():
|
||||
if _is_users_pk_sequence_error(e):
|
||||
_write_login_audit('wecom', 'failed', reason='db_sequence_misconfig', wecom_userid=wecom_userid_for_audit, error_code='DB_SEQUENCE_MISCONFIG')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='数据库主键自增配置异常,当前环境缺少 users.id 的自动序列。请执行数据库迁移后重试。', http_status=500, details={'error_code': 'DB_SEQUENCE_MISCONFIG'})
|
||||
raise AppError(
|
||||
code='SYSTEM.DB_SEQUENCE_MISCONFIG',
|
||||
message='数据库主键自增配置异常,当前环境缺少 users.id 的自动序列。请执行数据库迁移后重试。',
|
||||
http_status=500,
|
||||
)
|
||||
_write_login_audit('wecom', 'failed', reason=f'exception:{str(e)[:160]}')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=f'WeCom login failed: {str(e)}', http_status=500)
|
||||
@@ -1027,21 +1047,44 @@ def wecom_complete_bind():
|
||||
value = data.get('value')
|
||||
identity = _get_wecom_bind_session(binding_token)
|
||||
if not identity:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='WeCom binding session expired. Please restart WeCom login.', http_status=400, details={'error_code': 'WECOM_BIND_SESSION_EXPIRED'})
|
||||
raise AppError(
|
||||
code='WECOM_BIND_SESSION_EXPIRED',
|
||||
message='WeCom binding session expired. Please restart WeCom login.',
|
||||
http_status=400,
|
||||
)
|
||||
allowed_fields = _get_wecom_first_login_input_fields()
|
||||
if field not in allowed_fields:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='Selected bind field is not allowed', http_status=400, details={'error_code': 'WECOM_BIND_FIELD_NOT_ALLOWED', 'allowed_fields': allowed_fields})
|
||||
raise AppError(
|
||||
code='WECOM_BIND_FIELD_NOT_ALLOWED',
|
||||
message='Selected bind field is not allowed',
|
||||
http_status=400,
|
||||
details={'allowed_fields': allowed_fields},
|
||||
)
|
||||
matched_users, missing_field = _find_users_by_input_field(field, value)
|
||||
if missing_field:
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message=f'{field} is required', http_status=400, details={'error_code': 'WECOM_BIND_INPUT_VALUE_REQUIRED', 'field': field})
|
||||
raise AppError(
|
||||
code='WECOM_BIND_INPUT_VALUE_REQUIRED',
|
||||
message=f'{field} is required',
|
||||
http_status=400,
|
||||
details={'field': field},
|
||||
)
|
||||
if len(matched_users) == 0:
|
||||
_write_login_audit('wecom', 'failed', reason=f'input_bind_not_found:{field}', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_BIND_INPUT_NOT_FOUND', match_rules=[field], match_operator='AND')
|
||||
db.session.commit()
|
||||
raise AppError(code='SYSTEM.HTTP_ERROR', message='No local account matched the verification value.', http_status=404, details={'error_code': 'WECOM_BIND_INPUT_NOT_FOUND', 'field': field})
|
||||
raise AppError(
|
||||
code='WECOM_BIND_INPUT_NOT_FOUND',
|
||||
message='No local account matched the verification value.',
|
||||
http_status=404,
|
||||
details={'field': field},
|
||||
)
|
||||
if len(matched_users) > 1:
|
||||
_write_login_audit('wecom', 'failed', reason=f'input_bind_ambiguous:{field}', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_BIND_INPUT_AMBIGUOUS', match_rules=[field], match_operator='AND')
|
||||
db.session.commit()
|
||||
raise ConflictError('Multiple local accounts matched the verification value.', details={'error_code': 'WECOM_BIND_INPUT_AMBIGUOUS', 'field': field, 'candidate_count': len(matched_users)})
|
||||
raise ConflictError(
|
||||
'Multiple local accounts matched the verification value.',
|
||||
code='WECOM_BIND_INPUT_AMBIGUOUS',
|
||||
details={'field': field, 'candidate_count': len(matched_users)},
|
||||
)
|
||||
user = matched_users[0]
|
||||
if user.status != 'active':
|
||||
_write_login_audit('wecom', 'failed', user=user, reason='account_disabled', wecom_userid=identity.get('wecom_userid'), error_code='WECOM_ACCOUNT_DISABLED', match_rules=[field], match_operator='AND')
|
||||
@@ -1568,24 +1611,19 @@ def reset_password_by_wecom():
|
||||
code='WECOM.RESET_NOT_CONFIGURED',
|
||||
message='WeCom password reset is not configured',
|
||||
http_status=503,
|
||||
details={
|
||||
'error_code': 'WECOM_RESET_NOT_CONFIGURED',
|
||||
'missing': _get_wecom_config_missing_fields(),
|
||||
},
|
||||
details={'missing': _get_wecom_config_missing_fields()},
|
||||
)
|
||||
if not bool(current_app.config.get('WECOM_NOTIFY_ENABLED', True)):
|
||||
raise AppError(
|
||||
code='WECOM.NOTIFY_DISABLED',
|
||||
message='WeCom notification is disabled',
|
||||
http_status=503,
|
||||
details={'error_code': 'WECOM_NOTIFY_DISABLED'},
|
||||
)
|
||||
if not _get_password_reset_public_base_url():
|
||||
raise AppError(
|
||||
code='WECOM.RESET_URL_NOT_CONFIGURED',
|
||||
message='Password reset public base URL is not configured',
|
||||
http_status=503,
|
||||
details={'error_code': 'PASSWORD_RESET_URL_NOT_CONFIGURED'},
|
||||
)
|
||||
|
||||
data = request.get_json() or {}
|
||||
@@ -1610,7 +1648,6 @@ def reset_password_by_wecom():
|
||||
message='Password reset requests are too frequent',
|
||||
http_status=429,
|
||||
details={
|
||||
'error_code': 'PASSWORD_RESET_RATE_LIMITED',
|
||||
'retry_after_seconds': retry_after_seconds,
|
||||
'retry_after_minutes': retry_minutes,
|
||||
},
|
||||
@@ -1737,7 +1774,6 @@ def reset_password_confirm():
|
||||
code='AUTH.RESET_TOKEN_INVALID',
|
||||
message='Invalid or expired token',
|
||||
http_status=400,
|
||||
details={'error_code': 'RESET_TOKEN_INVALID'},
|
||||
)
|
||||
try:
|
||||
_sync_casdoor_password_for_reset(user, new_password)
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
"""
|
||||
backend/app/auth_jwt.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.auth.jwt。
|
||||
依赖:app.core.auth.jwt。
|
||||
逻辑:Casdoor JWKS 校验与 get_current_user;新代码请 from app.core.auth.jwt import ...。
|
||||
"""
|
||||
|
||||
from app.core.auth.jwt import get_current_user, issue_local_access_token # noqa: F401
|
||||
|
||||
__all__ = ['get_current_user', 'issue_local_access_token']
|
||||
@@ -1 +0,0 @@
|
||||
"""FAQ CLI 包。"""
|
||||
@@ -1,44 +0,0 @@
|
||||
"""
|
||||
backend/app/cli/faq_commands.py
|
||||
|
||||
用途:FAQ 相关 Flask CLI 命令注册。
|
||||
依赖:HotFaqAggregator、Flask click。
|
||||
逻辑:create_app 时 init_app 注册 faq-aggregate-hot 命令。
|
||||
"""
|
||||
import click
|
||||
from flask.cli import with_appcontext
|
||||
|
||||
from app.services.hot_faq_aggregator import HotFaqAggregator
|
||||
|
||||
|
||||
@click.command('faq-aggregate-hot')
|
||||
@click.option('--agent-id', type=int, default=None, help='仅聚合指定 Agent')
|
||||
@click.option('--dry-run', is_flag=True, help='只统计不写 PostgreSQL')
|
||||
@with_appcontext
|
||||
def faq_aggregate_hot(agent_id: int | None, dry_run: bool):
|
||||
"""
|
||||
离线聚合 ChatLog 热点 FAQ 候选并写入 faq_hot_candidates 表。
|
||||
核心逻辑:委托 HotFaqAggregator.aggregate_hot_faq_candidates。
|
||||
"""
|
||||
result = HotFaqAggregator.aggregate_hot_faq_candidates(agent_id=agent_id, dry_run=dry_run)
|
||||
if not result.get('enabled'):
|
||||
click.echo(result.get('message', 'FAQ hot aggregation disabled'))
|
||||
return
|
||||
|
||||
click.echo(
|
||||
f"scanned={result['scanned_logs']} groups={result['group_count']} "
|
||||
f"promoted={result['promoted_count']} skipped={result['skipped_count']} dry_run={dry_run}"
|
||||
)
|
||||
for item in result.get('candidates', [])[:20]:
|
||||
click.echo(
|
||||
f" [{item.get('agent_name')}] {item.get('canonical_query')} "
|
||||
f"asks={item.get('ask_count_7d')} users={item.get('user_count_7d')} "
|
||||
f"dominance={item.get('answer_dominance')}"
|
||||
)
|
||||
if len(result.get('candidates', [])) > 20:
|
||||
click.echo(f" ... and {len(result['candidates']) - 20} more")
|
||||
|
||||
|
||||
def init_app(app):
|
||||
"""向 Flask app 注册 FAQ CLI 命令。"""
|
||||
app.cli.add_command(faq_aggregate_hot)
|
||||
@@ -1,25 +0,0 @@
|
||||
"""
|
||||
backend/app/config.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.config.settings。
|
||||
依赖:app.core.config.settings。
|
||||
逻辑:环境文件加载与 Config 类;新代码请 from app.core.config.settings import config。
|
||||
"""
|
||||
|
||||
from app.core.config.settings import ( # noqa: F401
|
||||
ACTIVE_ENV_NAME,
|
||||
Config,
|
||||
DevelopmentConfig,
|
||||
ProductionConfig,
|
||||
TestingConfig,
|
||||
config,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'ACTIVE_ENV_NAME',
|
||||
'Config',
|
||||
'DevelopmentConfig',
|
||||
'ProductionConfig',
|
||||
'TestingConfig',
|
||||
'config',
|
||||
]
|
||||
@@ -2,8 +2,7 @@
|
||||
backend/app/core/__init__.py
|
||||
|
||||
用途:横切能力包入口(errors、response、auth、config、decorators)。
|
||||
逻辑:业务代码优先 from app.core.errors / app.core.auth.jwt 等子模块 import;
|
||||
app/errors.py 等根路径 shim 仅作存量兼容。
|
||||
逻辑:业务代码 from app.core.errors / app.core.auth.jwt 等子模块 import。
|
||||
"""
|
||||
|
||||
from app.core.errors import AppError # noqa: F401
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/core/auth/jwt.py
|
||||
|
||||
用途:Casdoor JWT 校验、legacy header 回退与当前用户解析。
|
||||
依赖:app.extensions.db、app.models.User、PyJWT、requests。
|
||||
逻辑:api 层与 decorators 调用 get_current_user();旧路径 app.auth_jwt 为兼容 shim。
|
||||
逻辑:api 层与 decorators 调用 get_current_user()。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/core/decorators.py
|
||||
|
||||
用途:API 路由权限装饰器(admin、agent 权限)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.models。
|
||||
逻辑:api 路由使用 @require_admin、@require_agent_permission;旧路径 app.decorators 为兼容 shim。
|
||||
逻辑:api 路由使用 @require_admin、@require_agent_permission。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/core/errors.py
|
||||
|
||||
用途:定义后端统一业务异常类型,供全局异常处理器识别并输出标准错误响应。
|
||||
依赖:无 Flask 依赖。
|
||||
逻辑:业务层 raise AppError 子类;create_app 注册全局 handler;旧路径 app.errors 为兼容 shim。
|
||||
逻辑:业务层 raise AppError 子类;create_app 注册全局 handler。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
"""
|
||||
backend/app/decorators.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.decorators。
|
||||
依赖:app.core.decorators。
|
||||
逻辑:@require_admin / @require_agent_permission;新代码请 from app.core.decorators import ...。
|
||||
"""
|
||||
|
||||
from app.core.decorators import ( # noqa: F401
|
||||
_get_current_user,
|
||||
require_admin,
|
||||
require_agent_permission,
|
||||
)
|
||||
|
||||
__all__ = ['require_admin', 'require_agent_permission', '_get_current_user']
|
||||
@@ -1,23 +0,0 @@
|
||||
"""
|
||||
backend/app/env_persistence.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.config.env_persistence。
|
||||
依赖:app.core.config.env_persistence。
|
||||
逻辑:WeCom 等运行时配置 DB 持久化;create_app before_request 调用 apply_env_settings。
|
||||
"""
|
||||
|
||||
from app.core.config.env_persistence import ( # noqa: F401
|
||||
BACKEND_ENV_PATH,
|
||||
LEGACY_BACKEND_ENV_PATH,
|
||||
ROOT_ENV_LOCAL_PATH,
|
||||
apply_env_settings,
|
||||
persist_env_settings,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'BACKEND_ENV_PATH',
|
||||
'LEGACY_BACKEND_ENV_PATH',
|
||||
'ROOT_ENV_LOCAL_PATH',
|
||||
'apply_env_settings',
|
||||
'persist_env_settings',
|
||||
]
|
||||
@@ -1,9 +0,0 @@
|
||||
"""
|
||||
backend/app/errors.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.errors。
|
||||
依赖:app.core.errors。
|
||||
逻辑:存量代码 from app.errors import ... 仍可用;新代码请改用 app.core.errors。
|
||||
"""
|
||||
|
||||
from app.core.errors import * # noqa: F403
|
||||
@@ -1,11 +0,0 @@
|
||||
"""
|
||||
backend/app/response_utils.py
|
||||
|
||||
用途:兼容层 — 权威实现位于 app.core.response。
|
||||
依赖:app.core.response。
|
||||
逻辑:create_app 全局 handler 使用 error_payload;新代码请 from app.core.response import ...。
|
||||
"""
|
||||
|
||||
from app.core.response import error_payload, ok, utc_iso, utc_iso_now # noqa: F401
|
||||
|
||||
__all__ = ['error_payload', 'ok', 'utc_iso', 'utc_iso_now']
|
||||
@@ -3,7 +3,7 @@ backend/app/services/hot_faq_aggregator.py
|
||||
|
||||
用途:从 ChatLog 离线聚合热点 FAQ 候选,写入 PostgreSQL 候选表(不含在线命中)。
|
||||
依赖:ChatLog、Feedback、QuickQuestion、faq_text_utils、hot_faq_candidate_store。
|
||||
逻辑:CLI `flask faq-aggregate-hot` 与管理端「刷新」调用 aggregate_hot_faq_candidates。
|
||||
逻辑:管理端「刷新聚合」调用 aggregate_hot_faq_candidates。
|
||||
|
||||
## 热点选取规则(HOT_FAQ_SELECTION_RULES)
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str
|
||||
|
||||
def run_faq_hot_aggregate_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""
|
||||
执行 FAQ 热点离线聚合(等同 flask faq-aggregate-hot,非 dry-run)。
|
||||
执行 FAQ 热点离线聚合(非 dry-run)。
|
||||
核心逻辑:委托 HotFaqAggregator;可选 dify_agent_id 限定 Agent。
|
||||
@param task - 排程任务;dify_agent_id 可选作 agent_id 过滤
|
||||
@param run - 当前执行批次(未写入 run 字段,由 scheduler_service 汇总)
|
||||
|
||||
@@ -14,7 +14,7 @@ from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1] / "app"
|
||||
TARGETS = [
|
||||
ROOT / "decorators.py",
|
||||
ROOT / "core" / "decorators.py",
|
||||
*sorted(ROOT.glob("api/**/*.py")),
|
||||
]
|
||||
|
||||
|
||||
@@ -1,6 +1,28 @@
|
||||
import pytest
|
||||
|
||||
|
||||
def parse_api_error(body: dict) -> dict:
|
||||
"""
|
||||
从标准 API 错误 envelope 中提取 error 子对象,供测试断言 error.code / details。
|
||||
"""
|
||||
assert isinstance(body, dict)
|
||||
assert body.get('success') is False
|
||||
error = body.get('error')
|
||||
assert isinstance(error, dict)
|
||||
return error
|
||||
|
||||
|
||||
def flatten_api_error(body: dict) -> dict:
|
||||
"""
|
||||
将 envelope 错误扁平化为 { error_code, error, ...details },便于 WeCom 等历史测试断言。
|
||||
"""
|
||||
error = parse_api_error(body)
|
||||
flat = dict(error.get('details') or {})
|
||||
flat['error_code'] = error.get('code')
|
||||
flat['error'] = error.get('message')
|
||||
return flat
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _isolate_persisted_settings(monkeypatch, tmp_path):
|
||||
"""Prevent tests from inheriting the developer's local ``backend/.env``.
|
||||
@@ -12,7 +34,7 @@ def _isolate_persisted_settings(monkeypatch, tmp_path):
|
||||
calls inside test fixtures. Routing reads to a tmp path makes every test
|
||||
start from a clean slate.
|
||||
"""
|
||||
from app import env_persistence
|
||||
from app.core.config import env_persistence
|
||||
|
||||
monkeypatch.setattr(env_persistence, 'LEGACY_BACKEND_ENV_PATH', tmp_path / 'isolated.env')
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""
|
||||
backend/tests/test_api_error_contract.py
|
||||
|
||||
用途:冒烟验证标准 JSON API 错误 envelope 与 Dify Tool API legacy 错误格式。
|
||||
依赖:tests.conftest 的 client/app fixture、parse_api_error。
|
||||
逻辑:Wave 1 AppError 契约回归;Tool 路由刻意保持 { ok, error_code, message }。
|
||||
"""
|
||||
|
||||
from tests.conftest import parse_api_error
|
||||
|
||||
|
||||
def _assert_standard_error_envelope(body: dict, *, code: str, status: int) -> dict:
|
||||
"""断言标准 API 失败响应结构,返回 error 子对象供后续字段检查。"""
|
||||
assert isinstance(body, dict)
|
||||
assert body.get('success') is False
|
||||
assert 'timestamp' in body
|
||||
error = parse_api_error(body)
|
||||
assert error.get('code') == code
|
||||
assert isinstance(error.get('message'), str) and error['message'].strip()
|
||||
assert isinstance(error.get('details'), dict)
|
||||
assert isinstance(error.get('retryable'), bool)
|
||||
return error
|
||||
|
||||
|
||||
def test_validation_error_returns_standard_envelope(client):
|
||||
"""注册缺参 → VALIDATION.INVALID_PARAM + envelope。"""
|
||||
res = client.post('/api/user/register', json={'username': 'only-name'})
|
||||
assert res.status_code == 400
|
||||
_assert_standard_error_envelope(res.get_json(), code='VALIDATION.INVALID_PARAM', status=400)
|
||||
|
||||
|
||||
def test_unauthorized_error_returns_standard_envelope(client):
|
||||
"""未登录访问受保护路由 → AUTH.UNAUTHORIZED + envelope。"""
|
||||
res = client.get('/api/user/leave-balance')
|
||||
assert res.status_code == 401
|
||||
_assert_standard_error_envelope(res.get_json(), code='AUTH.UNAUTHORIZED', status=401)
|
||||
|
||||
|
||||
def test_app_error_code_not_duplicated_in_details(app, client):
|
||||
"""AUTH.PASSWORD_LOGIN_DISABLED:主码在 error.code,不在 details.error_code。"""
|
||||
with app.app_context():
|
||||
app.config['AUTH_ALLOW_LOCAL_PASSWORD_LOGIN'] = False
|
||||
res = client.post('/api/user/login', json={'username': 'u', 'password': 'p'})
|
||||
assert res.status_code == 403
|
||||
body = res.get_json()
|
||||
error = _assert_standard_error_envelope(body, code='AUTH.PASSWORD_LOGIN_DISABLED', status=403)
|
||||
assert 'error_code' not in (error.get('details') or {})
|
||||
|
||||
|
||||
def test_file_check_tool_api_uses_dify_legacy_format(app, client):
|
||||
"""文件检核 Tool API 保持 { ok, error_code, message },不走标准 envelope。"""
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
res = client.get('/api/file-check/tools/tasks')
|
||||
assert res.status_code == 401
|
||||
body = res.get_json()
|
||||
assert body.get('ok') is False
|
||||
assert body.get('error_code') == 'missing_auth'
|
||||
assert isinstance(body.get('message'), str)
|
||||
assert 'success' not in body
|
||||
|
||||
|
||||
def test_shipping_notice_tool_api_uses_dify_legacy_format(app, client):
|
||||
"""发货通知 Tool API 保持 { ok, error_code, message },不走标准 envelope。"""
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'test-key'
|
||||
res = client.post(
|
||||
'/api/shipping-notice/tools/create_task',
|
||||
headers={'Content-Type': 'application/json'},
|
||||
json={'source_type': 'manual'},
|
||||
)
|
||||
assert res.status_code == 401
|
||||
body = res.get_json()
|
||||
assert body.get('ok') is False
|
||||
assert body.get('error_code') == 'missing_auth'
|
||||
assert isinstance(body.get('message'), str)
|
||||
assert 'success' not in body
|
||||
@@ -1025,7 +1025,7 @@ def test_file_check_dify_chat_inputs(app):
|
||||
def test_file_check_dify_chat_inputs_without_extra_task_id(app):
|
||||
import pytest
|
||||
|
||||
from app.errors import ValidationError
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.file_check_tools.dify_inputs import (
|
||||
FILE_CHECK_TASK_ID_MISSING_CODE,
|
||||
build_file_check_dify_inputs,
|
||||
@@ -1046,7 +1046,7 @@ def test_file_check_dify_chat_inputs_without_extra_task_id(app):
|
||||
def test_file_check_dify_inputs_raises_when_capability_without_schedule_task_id(app):
|
||||
import pytest
|
||||
|
||||
from app.errors import ValidationError
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.file_check_tools.agent_resolver import (
|
||||
agent_declares_file_check_progress,
|
||||
is_file_check_chat_agent,
|
||||
@@ -1100,7 +1100,7 @@ def test_chat_completions_rejects_missing_file_check_task_id(app, client, mocker
|
||||
g.current_user = user
|
||||
return user
|
||||
|
||||
mocker.patch('app.decorators._get_current_user', side_effect=mock_get_user)
|
||||
mocker.patch('app.core.decorators._get_current_user', side_effect=mock_get_user)
|
||||
mocker.patch('app.models.Agent.query').get.return_value = misconfigured
|
||||
mock_post = mocker.patch('requests.post')
|
||||
mock_post.side_effect = AssertionError('Dify must not be called when task_id is missing')
|
||||
|
||||
@@ -2,7 +2,7 @@ import io
|
||||
from pathlib import Path
|
||||
|
||||
from app import db
|
||||
from app.auth_jwt import issue_local_access_token
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import KbDocument, KbDifySyncRecord, User
|
||||
from app.services.knowledge_cleaning import dify_sync_service as dify_sync_module
|
||||
from app.services.knowledge_cleaning import tasks as kb_tasks_module
|
||||
|
||||
@@ -12,7 +12,7 @@ from io import BytesIO
|
||||
|
||||
from app import db
|
||||
from app.models import Agent, ChatSession, Job, KbJob, ShippingBatch, ShippingTask, ShippingTaskEvent, User
|
||||
from app.auth_jwt import issue_local_access_token
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.queue import process_next_job
|
||||
from app.jobs.types import JobType
|
||||
|
||||
@@ -58,5 +58,5 @@ def test_feedback_config_logic():
|
||||
Backend /feedback endpoint checks FEEDBACK_ENABLED config.
|
||||
"""
|
||||
# This is covered by app/config.py having FEEDBACK_ENABLED default to True
|
||||
from app.config import Config
|
||||
from app.core.config.settings import Config
|
||||
assert Config.FEEDBACK_ENABLED is True
|
||||
@@ -283,7 +283,7 @@ def test_admin_create_agent_success(client, admin_headers, mock_db_session, mock
|
||||
}
|
||||
# Mock _get_current_user for require_admin
|
||||
admin_user = User(role='admin', username='admin')
|
||||
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
|
||||
mocker.patch('app.core.decorators._get_current_user', return_value=admin_user)
|
||||
|
||||
# Act
|
||||
response = client.post('/api/admin/agents', json=payload, headers=admin_headers)
|
||||
@@ -304,7 +304,7 @@ def test_admin_create_agent_missing_fields(client, admin_headers, mocker):
|
||||
# Missing dify_app_id and dify_api_key
|
||||
}
|
||||
admin_user = User(role='admin', username='admin')
|
||||
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
|
||||
mocker.patch('app.core.decorators._get_current_user', return_value=admin_user)
|
||||
|
||||
# Act
|
||||
response = client.post('/api/admin/agents', json=payload, headers=admin_headers)
|
||||
@@ -322,7 +322,7 @@ def test_admin_delete_agent(client, admin_headers, mock_agent_query, mock_db_ses
|
||||
mock_agent_query.get.return_value = mock_agent
|
||||
|
||||
admin_user = User(role='admin', username='admin')
|
||||
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
|
||||
mocker.patch('app.core.decorators._get_current_user', return_value=admin_user)
|
||||
|
||||
# Act
|
||||
response = client.delete('/api/admin/agents/1', headers=admin_headers)
|
||||
@@ -341,7 +341,7 @@ def test_admin_approve_user(client, admin_headers, mock_user_query, mock_db_sess
|
||||
mock_user_query.get.return_value = mock_user
|
||||
|
||||
admin_user = User(role='admin', username='admin')
|
||||
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
|
||||
mocker.patch('app.core.decorators._get_current_user', return_value=admin_user)
|
||||
|
||||
# Act
|
||||
response = client.post('/api/admin/users/2/approve', headers=admin_headers)
|
||||
@@ -360,7 +360,7 @@ def test_admin_reject_user(client, admin_headers, mock_user_query, mock_db_sessi
|
||||
mock_user_query.get.return_value = mock_user
|
||||
|
||||
admin_user = User(role='admin', username='admin')
|
||||
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
|
||||
mocker.patch('app.core.decorators._get_current_user', return_value=admin_user)
|
||||
|
||||
# Act
|
||||
response = client.post('/api/admin/users/3/reject', headers=admin_headers)
|
||||
@@ -402,13 +402,13 @@ def test_chat_completions_stream_success(client, mocker, mock_agent_query):
|
||||
mock_user.agents = [mock_agent] # Grant permission
|
||||
|
||||
# Mock decorator dependencies
|
||||
# IMPORTANT: require_agent_permission calls _get_current_user() from app.decorators
|
||||
# IMPORTANT: require_agent_permission calls _get_current_user() from app.core.decorators
|
||||
# We use side_effect to ensure g.current_user is set, as the real function does
|
||||
def mock_get_user():
|
||||
g.current_user = mock_user
|
||||
return mock_user
|
||||
|
||||
mocker.patch('app.decorators._get_current_user', side_effect=mock_get_user)
|
||||
mocker.patch('app.core.decorators._get_current_user', side_effect=mock_get_user)
|
||||
|
||||
# Mock Agent.query.get used in require_agent_permission
|
||||
mock_agent_query.get.return_value = mock_agent
|
||||
@@ -437,7 +437,7 @@ def test_chat_completions_no_permission(client, mocker, mock_agent_query):
|
||||
mock_agent = Agent(id=2, name="Restricted Agent")
|
||||
mock_user.agents = [] # No permission
|
||||
|
||||
mocker.patch('app.decorators._get_current_user', return_value=mock_user)
|
||||
mocker.patch('app.core.decorators._get_current_user', return_value=mock_user)
|
||||
mock_agent_query.get.return_value = mock_agent
|
||||
|
||||
# Act
|
||||
@@ -461,7 +461,7 @@ def test_submit_feedback_success(client, mocker, mock_chat_log_query, mock_agent
|
||||
g.current_user = mock_user
|
||||
return mock_user
|
||||
|
||||
mocker.patch('app.decorators._get_current_user', side_effect=mock_get_user)
|
||||
mocker.patch('app.core.decorators._get_current_user', side_effect=mock_get_user)
|
||||
mock_agent_query.get.return_value = mock_agent
|
||||
|
||||
# Mock ChatLog query
|
||||
@@ -490,7 +490,7 @@ def test_submit_feedback_invalid_score(client, mocker, mock_agent_query):
|
||||
mock_user = User(id=1)
|
||||
mock_agent = Agent(id=1)
|
||||
mock_user.agents = [mock_agent]
|
||||
mocker.patch('app.decorators._get_current_user', return_value=mock_user)
|
||||
mocker.patch('app.core.decorators._get_current_user', return_value=mock_user)
|
||||
mock_agent_query.get.return_value = mock_agent
|
||||
|
||||
# Act
|
||||
@@ -567,7 +567,7 @@ def test_admin_approve_permission_request(client, admin_headers, mock_permission
|
||||
mock_agent_query.get.return_value = mock_agent
|
||||
|
||||
admin_user = User(role='admin', username='admin')
|
||||
mocker.patch('app.decorators._get_current_user', return_value=admin_user)
|
||||
mocker.patch('app.core.decorators._get_current_user', return_value=admin_user)
|
||||
|
||||
# Act
|
||||
response = client.post('/api/admin/permission-requests/1/approve', headers=admin_headers)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from tests.conftest import flatten_api_error, parse_api_error
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.auth import wecom_auth_service
|
||||
@@ -92,5 +94,6 @@ def test_wecom_debug_user_by_code_returns_scope_error_when_only_openid(client, a
|
||||
)
|
||||
assert res.status_code == 401
|
||||
data = res.get_json()
|
||||
assert data['error_code'] == 'WECOM_NOT_IN_AGENT_SCOPE'
|
||||
assert data['openid'] == 'oExternal_xx'
|
||||
error = parse_api_error(data)
|
||||
assert error['code'] == 'WECOM_NOT_IN_AGENT_SCOPE'
|
||||
assert error['details']['openid'] == 'oExternal_xx'
|
||||
@@ -1,5 +1,7 @@
|
||||
import pytest
|
||||
|
||||
from tests.conftest import flatten_api_error
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import User
|
||||
from app.api import user as user_api
|
||||
@@ -77,7 +79,7 @@ def _start_input_verify_login(client, monkeypatch, *, userid, name='Test User',
|
||||
state = _issue_state(client)
|
||||
res = client.post('/api/user/wecom/login', json={'code': 'code-input-verify', 'state': state})
|
||||
assert res.status_code == 409
|
||||
data = res.get_json()
|
||||
data = flatten_api_error(res.get_json())
|
||||
assert data['error_code'] == 'WECOM_BIND_INPUT_REQUIRED'
|
||||
assert data['binding_token']
|
||||
return data
|
||||
@@ -164,7 +166,7 @@ def test_wecom_complete_bind_binds_user_by_selected_field(wecom_input_verify_cli
|
||||
'value': 'EMP001',
|
||||
})
|
||||
assert expired_res.status_code == 400
|
||||
assert expired_res.get_json()['error_code'] == 'WECOM_BIND_SESSION_EXPIRED'
|
||||
assert flatten_api_error(expired_res.get_json())['error_code'] == 'WECOM_BIND_SESSION_EXPIRED'
|
||||
|
||||
|
||||
def test_wecom_complete_bind_returns_not_found_when_value_does_not_match(wecom_input_verify_client, monkeypatch):
|
||||
@@ -198,7 +200,7 @@ def test_wecom_complete_bind_returns_not_found_when_value_does_not_match(wecom_i
|
||||
'value': 'missing@example.com',
|
||||
})
|
||||
assert bind_res.status_code == 404
|
||||
bind_data = bind_res.get_json()
|
||||
bind_data = flatten_api_error(bind_res.get_json())
|
||||
assert bind_data['error_code'] == 'WECOM_BIND_INPUT_NOT_FOUND'
|
||||
|
||||
|
||||
@@ -242,6 +244,6 @@ def test_wecom_complete_bind_returns_ambiguous_for_mobile_raw_and_normalized_dup
|
||||
'value': '+86 13800138000',
|
||||
})
|
||||
assert bind_res.status_code == 409
|
||||
bind_data = bind_res.get_json()
|
||||
bind_data = flatten_api_error(bind_res.get_json())
|
||||
assert bind_data['error_code'] == 'WECOM_BIND_INPUT_AMBIGUOUS'
|
||||
assert bind_data['candidate_count'] == 2
|
||||
@@ -1,5 +1,7 @@
|
||||
import pytest
|
||||
|
||||
from tests.conftest import flatten_api_error
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import User
|
||||
from app.api import user as user_api
|
||||
@@ -104,7 +106,7 @@ def test_wecom_login_bind_required_when_no_match(wecom_client, monkeypatch):
|
||||
state = _issue_state(client)
|
||||
res = client.post('/api/user/wecom/login', json={'code': 'code-2', 'state': state})
|
||||
assert res.status_code == 403
|
||||
data = res.get_json()
|
||||
data = flatten_api_error(res.get_json())
|
||||
assert data['error_code'] == 'WECOM_BIND_REQUIRED'
|
||||
assert data['reason'] == 'bind_required'
|
||||
|
||||
@@ -141,7 +143,7 @@ def test_wecom_login_ambiguous_match_returns_409(wecom_client, monkeypatch):
|
||||
state = _issue_state(client)
|
||||
res = client.post('/api/user/wecom/login', json={'code': 'code-3', 'state': state})
|
||||
assert res.status_code == 409
|
||||
data = res.get_json()
|
||||
data = flatten_api_error(res.get_json())
|
||||
assert data['error_code'] == 'WECOM_MATCH_AMBIGUOUS'
|
||||
assert data['reason'] == 'ambiguous_match'
|
||||
assert data['candidate_count'] == 2
|
||||
@@ -166,7 +168,7 @@ def test_wecom_login_missing_match_attr_returns_422(wecom_client, monkeypatch):
|
||||
state = _issue_state(client)
|
||||
res = client.post('/api/user/wecom/login', json={'code': 'code-4', 'state': state})
|
||||
assert res.status_code == 422
|
||||
data = res.get_json()
|
||||
data = flatten_api_error(res.get_json())
|
||||
assert data['error_code'] == 'WECOM_MATCH_ATTR_MISSING'
|
||||
assert data['missing_field'] == 'mobile'
|
||||
|
||||
@@ -189,7 +191,7 @@ def test_wecom_login_returns_clear_error_when_user_not_in_agent_scope(wecom_clie
|
||||
state = _issue_state(client)
|
||||
res = client.post('/api/user/wecom/login', json={'code': 'code-out-of-scope', 'state': state})
|
||||
assert res.status_code == 401
|
||||
data = res.get_json()
|
||||
data = flatten_api_error(res.get_json())
|
||||
assert data['error_code'] == 'WECOM_NOT_IN_AGENT_SCOPE'
|
||||
assert '可见范围' in data['error']
|
||||
assert 'WeCom auth failed: ok' not in data['error']
|
||||
@@ -1,6 +1,6 @@
|
||||
# 错误处理规范
|
||||
|
||||
> 更新时间:2026-06-22
|
||||
> 更新时间:2026-06-17
|
||||
> 适用范围:HXOPS 前后端 API 与 UI 错误反馈
|
||||
> 读者:组内同事、AI 编程助手
|
||||
> 文档定位:**错误契约、分层职责与禁止项**的权威说明。`AGENTS.md` §8 仅保留强约束摘要,细则以本文为准。
|
||||
@@ -40,7 +40,7 @@
|
||||
|
||||
| 字段 | 说明 |
|
||||
|------|------|
|
||||
| `error.code` | 机器可读错误码,格式 `DOMAIN.SUBTYPE`(如 `AUTH.UNAUTHORIZED`) |
|
||||
| `error.code` | 机器可读错误码;常规 API 用 `DOMAIN.SUBTYPE`(如 `AUTH.UNAUTHORIZED`);企微登录等历史域可保留 `WECOM_*` 扁平码 |
|
||||
| `error.message` | 英文或简短说明,供日志与 fallback;**前端优先用 i18n 映射** |
|
||||
| `error.details` | 可选结构化信息(字段名、冲突项等),供前端分支逻辑 |
|
||||
| `error.retryable` | 是否建议用户重试(503 等) |
|
||||
@@ -58,7 +58,7 @@
|
||||
| **Service(`services/`)** | 业务校验失败 `raise AppError` 子类;不构造 HTTP Response |
|
||||
| **全局 handler(`app/__init__.py`)** | 捕获 `AppError` / `HTTPException` / 未预期异常 → `error_payload` |
|
||||
|
||||
### 2.2 使用 `app/errors.py`
|
||||
### 2.2 使用 `app.core.errors`
|
||||
|
||||
优先使用已有子类,语义不明确时再 `raise AppError(...)`:
|
||||
|
||||
@@ -74,7 +74,7 @@
|
||||
**示例(service / route):**
|
||||
|
||||
```python
|
||||
from app.errors import ValidationError, NotFoundError, ConflictError
|
||||
from app.core.errors import ValidationError, NotFoundError, ConflictError, AppError
|
||||
|
||||
if not name:
|
||||
raise ValidationError("Name is required")
|
||||
@@ -82,9 +82,11 @@ if not row:
|
||||
raise NotFoundError("Agent not found")
|
||||
if email_exists:
|
||||
raise ConflictError("Email already exists", code="USER.EMAIL_EXISTS", details={"field": "email"})
|
||||
# 企微等业务码:code 字段即机器码,禁止再塞 details.error_code
|
||||
raise AppError(code="WECOM_NOT_IN_AGENT_SCOPE", message="...", http_status=401)
|
||||
```
|
||||
|
||||
**成功响应:** 使用 `app.response_utils.ok(data)`,或在 envelope 开启时返回 plain dict(由 `@app.after_request` 包装)。
|
||||
**成功响应:** 使用 `app.core.response.ok(data)`,或在 `ENABLE_API_ENVELOPE=true` 时返回 plain dict(由 `@app.after_request` 包装)。
|
||||
|
||||
### 2.3 错误码命名
|
||||
|
||||
@@ -101,8 +103,22 @@ if email_exists:
|
||||
| 在 service 里 `return (jsonify(...), 4xx)` | `raise AppError` 交给 handler |
|
||||
| 500 时把堆栈/ SQL 返回给客户端 | 日志记录细节;客户端仅 `SYSTEM.INTERNAL_ERROR` |
|
||||
| 随意字符串作 code(`"not_found"`) | `RESOURCE.NOT_FOUND` 等规范 code |
|
||||
| 用 `details.error_code` 传递主错误码 | 主码写在 `AppError.code`;`details` 只放结构化字段 |
|
||||
|
||||
> 历史路由(如部分 `workspace_shipping_notice.py`)仍有 legacy `{"error": "..."}` 写法;**新接口与改动处须改为 `AppError`**,逐步收敛。
|
||||
### 2.5 Dify Tool API 例外(刻意不走 Envelope)
|
||||
|
||||
供 Dify Chatflow / RPA 调用的 Tool 蓝图在 Blueprint 级注册 `@bp.errorhandler(AppError)`,返回:
|
||||
|
||||
```json
|
||||
{ "ok": false, "error_code": "missing_auth", "message": "..." }
|
||||
```
|
||||
|
||||
| 蓝图 | 前缀 |
|
||||
|------|------|
|
||||
| `api/file_check_tools.py` | `/api/file-check/tools/*` |
|
||||
| `api/shipping_notice_tools.py` | `/api/shipping-notice/tools/*` |
|
||||
|
||||
**禁止**将上述 Tool 路由改为标准 envelope;契约测试见 `backend/tests/test_api_error_contract.py`。
|
||||
|
||||
---
|
||||
|
||||
@@ -185,7 +201,7 @@ catch (e) {
|
||||
|
||||
## 4. 新增错误码检查清单
|
||||
|
||||
1. 后端:在 `app/errors.py` 选用或新增语义明确的 `code`。
|
||||
1. 后端:在 `app.core.errors` 选用或新增语义明确的 `code`。
|
||||
2. 前端:在 `locales/{zh-CN,zh-TW,en,th}/errors.json` 的 `codes` 下增加键(`USER.EMAIL_EXISTS` → `USER_EMAIL_EXISTS`)。
|
||||
3. 若需按 `details` 分支,在 composable 文档注释中说明字段约定。
|
||||
4. 自测:触发该错误,确认四语言文案与 HTTP 状态码正确。
|
||||
@@ -196,9 +212,10 @@ catch (e) {
|
||||
|
||||
| 文件 | 说明 |
|
||||
|------|------|
|
||||
| `backend/app/errors.py` | 业务异常类型 |
|
||||
| `backend/app/response_utils.py` | `ok()`、`error_payload()` |
|
||||
| `backend/app/core/errors.py` | 业务异常类型 |
|
||||
| `backend/app/core/response.py` | `ok()`、`error_payload()` |
|
||||
| `backend/app/__init__.py` | 全局 errorhandler、envelope 包装 |
|
||||
| `backend/tests/test_api_error_contract.py` | 标准 envelope + Tool API 契约冒烟 |
|
||||
| `frontend/src/shared/api/client.ts` | `requestJson`、`BusinessError` |
|
||||
| `frontend/src/locales/*/errors.json` | 错误码 i18n |
|
||||
| `frontend/src/shared/composables/useMessage.ts` | 全局 error/success 弹窗 |
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
| --- | --- | --- | --- |
|
||||
| L1 人工 FAQ | `quick_questions` | ✅ | 用户提问时 `FaqCacheService.try_match` 命中即 SSE 直答 |
|
||||
| L2 热点候选 | `faq_hot_candidates` | ❌ | 仅管理端展示;**必须晋升**后才进入 L1 |
|
||||
| 离线聚合 | ChatLog → PG | — | `flask faq-aggregate-hot` 或管理端「刷新聚合」 |
|
||||
| 离线聚合 | ChatLog → PG | — | 管理端「热点发现 → 刷新聚合」 |
|
||||
|
||||
**不需要 Redis**(热点功能已全走 PostgreSQL)。知识库 worker 若单独使用 Redis,与 FAQ 无关。
|
||||
|
||||
@@ -197,25 +197,15 @@ FAQ_HOT_BAD_SCORE=2
|
||||
|
||||
### 2.3 冒烟验证
|
||||
|
||||
```bash
|
||||
# 1) 预览聚合(不写库)
|
||||
flask --app manage.py faq-aggregate-hot --dry-run
|
||||
|
||||
# 2) 正式写入候选表
|
||||
flask --app manage.py faq-aggregate-hot
|
||||
|
||||
# 3) 管理端:系统管理 → 常用问题 → 「热点发现」Tab → 刷新聚合
|
||||
```
|
||||
1. 登录管理后台 → **常用问题** → **热点发现**
|
||||
2. 点击 **刷新聚合**(可选勾选 dry-run 预览)
|
||||
3. 确认候选列表有数据或提示「无新候选」
|
||||
|
||||
---
|
||||
|
||||
## 3. 定时任务(推荐)
|
||||
## 3. 定时任务(可选)
|
||||
|
||||
热点发现可通过 **排程管理** 配置 Cron,无需宿主机 crontab。
|
||||
|
||||
### 3.1 排程管理(推荐)
|
||||
|
||||
路径:**管理后台 → 排程管理 → 新增排程**
|
||||
热点发现也可通过 **排程管理** 配置 Cron(管理后台 → 排程管理 → 数据源类型选「FAQ 热点聚合」)。若仅需按需聚合,在 **热点发现** 页手动刷新即可。
|
||||
|
||||
| 配置项 | 建议值 |
|
||||
| --- | --- |
|
||||
@@ -224,66 +214,11 @@ flask --app manage.py faq-aggregate-hot
|
||||
| 限定应用 | 可选;留空=全部 Agent |
|
||||
| 所有者 | 必填 |
|
||||
|
||||
创建并 **启用** 后,后端 `schedule-worker` 会按 Cron 自动执行,等同 `flask faq-aggregate-hot`。执行记录在排程工作台可查看(处理数 = 本次产出候选 + 跳过组数)。
|
||||
创建并 **启用** 后,后端 `schedule-worker` 会按 Cron 自动执行。执行记录在排程工作台可查看。
|
||||
|
||||
**前提**:`SCHEDULE_WORKER_ENABLED=true`(默认开启),后端进程需正常运行。
|
||||
|
||||
### 3.2 Docker 环境(宿主机 crontab,备选)
|
||||
|
||||
若不用排程管理,仍可用 crontab:
|
||||
|
||||
```cron
|
||||
# 每天 02:30 聚合热点 FAQ(stdout 追加到日志)
|
||||
30 2 * * * cd /path/to/hxops && docker compose exec -T hxops-backend flask --app manage.py faq-aggregate-hot >> /var/log/hxops/faq-aggregate-hot.log 2>&1
|
||||
```
|
||||
|
||||
### 3.3 裸机 / systemd timer
|
||||
|
||||
```bash
|
||||
# 手动试跑
|
||||
cd /path/to/hxops/backend
|
||||
source venv/bin/activate
|
||||
flask --app manage.py faq-aggregate-hot
|
||||
```
|
||||
|
||||
```ini
|
||||
# /etc/systemd/system/hxops-faq-aggregate.service
|
||||
[Unit]
|
||||
Description=HXOPS FAQ hot aggregation
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
WorkingDirectory=/path/to/hxops/backend
|
||||
EnvironmentFile=/path/to/hxops/.env.prod
|
||||
ExecStart=/path/to/hxops/backend/venv/bin/flask --app manage.py faq-aggregate-hot
|
||||
```
|
||||
|
||||
```ini
|
||||
# /etc/systemd/system/hxops-faq-aggregate.timer
|
||||
[Unit]
|
||||
Description=Daily FAQ hot aggregation
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 02:30:00
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
```
|
||||
|
||||
```bash
|
||||
sudo systemctl enable --now hxops-faq-aggregate.timer
|
||||
```
|
||||
|
||||
### 3.4 按 Agent 拆分(可选)
|
||||
|
||||
大租户可分开跑,减轻单次扫描量:
|
||||
|
||||
```bash
|
||||
flask --app manage.py faq-aggregate-hot --agent-id 12
|
||||
```
|
||||
|
||||
### 3.5 与 SQL 检核排程的区别
|
||||
### 3.1 与 SQL 检核排程的区别
|
||||
|
||||
| 类型 | 用途 |
|
||||
| --- | --- |
|
||||
@@ -556,7 +491,6 @@ FAQ_HOT_ENABLED=false
|
||||
| 离线聚合 | `backend/app/services/hot_faq_aggregator.py` |
|
||||
| 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/`(如 `quick_questions.py`、`faq_candidates.py`) |
|
||||
| 对话入口 | `backend/app/api/chat.py`(Dify 前 `try_match`) |
|
||||
| 管理 UI | `frontend/src/features/admin/modules/questions/` |
|
||||
@@ -592,7 +526,8 @@ flask --app manage.py db upgrade # c6d7e8f9a0b1_add_faq_kb_stale_fields
|
||||
|
||||
| 频率 | 动作 | 负责人 |
|
||||
| --- | --- | --- |
|
||||
| 每日 | cron 跑 `faq-aggregate-hot` | 运维 |
|
||||
| 按需 | 管理端「热点发现」刷新聚合 | 业务管理员 |
|
||||
| 可选 | 排程管理配置 FAQ 热点 Cron | 运维 |
|
||||
| 每周 | 管理员审核热点发现,晋升高质量 FAQ | 业务管理员 |
|
||||
| 每月 | 查看 `hit_count`、清理过期/错误 FAQ | 业务管理员 |
|
||||
| 变更前 | 改 `FAQ_HOT_*` 先在 test 环境 `--dry-run` 对比 | 运维 + 开发 |
|
||||
| 变更前 | 改 `FAQ_HOT_*` 先在 test 环境用管理端 dry-run 预览 | 运维 + 开发 |
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
**合并前自检**:`pytest backend/tests` 通过;改表结构须配套 Alembic 迁移;对外 URL 保持不变。
|
||||
|
||||
**当前进度**:Wave 0 骨架已落地(`core/`、`jobs/`、`schemas/`、部分 `api/` / `services/` 分包);运行时仍走原单体 Blueprint,Wave 1 尚未接线。
|
||||
**当前进度**:Wave 1 基础设施已完成(`register_blueprints`、`extensions.py`、`core/*` 权威实现、根 shim 已删除、`AppError` envelope 统一、Tool API 保留 Dify 格式);Wave 3 进行中(`admin/` 已拆包,`user.py` / `chat.py` 待拆)。
|
||||
|
||||
---
|
||||
|
||||
@@ -211,7 +211,7 @@ backend/
|
||||
│ │ ├── file_check_run.py
|
||||
│ │ └── wecom_directory_sync.py
|
||||
│ │
|
||||
│ ├── cli/ # flask CLI(faq_commands 等)
|
||||
│ ├── cli/ # (预留)Flask CLI 扩展
|
||||
│ └── path_utils.py
|
||||
│
|
||||
├── edkb_system/ # 文档清洗管线(OCR、切块、loader;独立子系统)
|
||||
@@ -270,7 +270,7 @@ Python 3 中 **模块文件与同名包不能并存**,否则包覆盖模块、
|
||||
| 现有路径 | 目标路径 | Wave |
|
||||
| --- | --- | --- |
|
||||
| `app/__init__.py`(db) | `extensions.py` | 1 |
|
||||
| `app/errors.py` 等根模块 | `core/*` | 1 |
|
||||
| `app/errors.py` 等根 shim(已删除) | `core/*` | ✅ |
|
||||
| `app/models.py` | `models/*.py` | 1 |
|
||||
| `app/api/user.py` | `api/user/*` + `services/user/*` | 3 |
|
||||
| `app/api/chat.py` | `api/chat/*` + `services/chat/router.py` | 3 |
|
||||
@@ -505,7 +505,7 @@ from app.models import User, Agent # Wave 1 后仍保持此入口
|
||||
# from app.api.admin import something
|
||||
```
|
||||
|
||||
旧路径(`app.errors`、`app.auth_jwt`)Wave 1 前仍可用;**新代码必须使用 `app.core.*`**。
|
||||
旧路径(`app.errors`、`app.auth_jwt` 等根 shim)**已删除**;**必须使用 `app.core.*`**。
|
||||
|
||||
---
|
||||
|
||||
@@ -513,22 +513,22 @@ from app.models import User, Agent # Wave 1 后仍保持此入口
|
||||
|
||||
```text
|
||||
Wave 0 骨架建立 ✅ 目录 + 占位(行为不变)
|
||||
Wave 1 基础设施 ← 推荐从此开始
|
||||
Wave 1 基础设施 ✅ register_blueprints / extensions / core / AppError / models
|
||||
Wave 2 任务层 jobs/ 接 KB worker
|
||||
Wave 3 拆 god 文件 user → chat → admin → kb
|
||||
Wave 3 拆 god 文件 admin ✅ → user → chat → kb
|
||||
Wave 4 集成收敛 integrations/、scheduler 迁出 web
|
||||
```
|
||||
|
||||
### 9.1 Wave 1 任务清单
|
||||
|
||||
| # | 任务 | 风险 | 价值 |
|
||||
| # | 任务 | 风险 | 状态 |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | `create_app` 改用 `register_blueprints(app)` | 低 | 注册集中、为拆包做准备 |
|
||||
| 2 | 修复 `deploy/gunicorn_config.py` workers 未赋值 | 低 | 生产容量 |
|
||||
| 3 | `extensions.py` 抽离 `db` / `migrate` | 低 | 消除 `__init__` 膨胀 |
|
||||
| 4 | `core/*` 真正迁入(非 re-export)+ 旧路径 shim | 低 | 统一横切入口 |
|
||||
| 5 | 推进 `AppError` 统一(`migrate_jsonify_errors.py`) | 中 | 前后端错误契约 |
|
||||
| 6 | `models/` 按域拆分 | 中 | 降低合并冲突 |
|
||||
| 1 | `create_app` 改用 `register_blueprints(app)` | 低 | ✅ |
|
||||
| 2 | 修复 `deploy/gunicorn_config.py` workers 未赋值 | 低 | ✅ |
|
||||
| 3 | `extensions.py` 抽离 `db` / `migrate` | 低 | ✅ |
|
||||
| 4 | `core/*` 迁入 + 删除根 shim | 低 | ✅ |
|
||||
| 5 | `AppError` 统一 + 契约测试 | 中 | ✅ |
|
||||
| 6 | `models/` 按域拆分 | 中 | ✅ |
|
||||
|
||||
### 9.2 API 单体迁包标准步骤
|
||||
|
||||
@@ -544,7 +544,7 @@ Wave 4 集成收敛 integrations/、scheduler 迁出 web
|
||||
### 9.3 完成定义
|
||||
|
||||
- [ ] 无 >800 行业务源文件(`edkb_system/` 除外)
|
||||
- [ ] API 统一 `AppError`
|
||||
- [x] API 统一 `AppError`(Tool API 除外,见 `docs/convention/error_handling.md` §2.5)
|
||||
- [ ] `services/` 无 `flask.request`
|
||||
- [ ] 后台任务统一经 `jobs/`
|
||||
- [ ] web 进程无 scheduler thread
|
||||
|
||||
@@ -351,7 +351,11 @@ export function useLoginAuth(deps: LoginDeps, options: LoginAuthOptions) {
|
||||
msg.error(friendly);
|
||||
sessionStorage.removeItem('hxops_wecom_state');
|
||||
if (errorCode === 'WECOM_BIND_INPUT_REQUIRED') {
|
||||
openWecomBindPrompt({ error: rawError, error_code: errorCode });
|
||||
openWecomBindPrompt({
|
||||
error: rawError,
|
||||
error_code: errorCode,
|
||||
...(err instanceof BusinessError ? err.details : {}),
|
||||
});
|
||||
} else {
|
||||
openWecomLoginDialog({ error: rawError || t('login.wecomLoginFailed'), error_code: errorCode });
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user